Coverage Report

Created: 2026-10-17 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Modules/pwdmodule.c
Line
Count
Source
1
2
/* UNIX password file access module */
3
4
#include "Python.h"
5
#include "posixmodule.h"
6
7
#include <errno.h>                // ERANGE
8
#include <pwd.h>                  // getpwuid()
9
#include <unistd.h>               // sysconf()
10
11
#include "clinic/pwdmodule.c.h"
12
/*[clinic input]
13
module pwd
14
[clinic start generated code]*/
15
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=60f628ef356b97b6]*/
16
17
static PyStructSequence_Field struct_pwd_type_fields[] = {
18
    {"pw_name", "user name"},
19
    {"pw_passwd", "password"},
20
    {"pw_uid", "user id"},
21
    {"pw_gid", "group id"},
22
    {"pw_gecos", "real name"},
23
    {"pw_dir", "home directory"},
24
    {"pw_shell", "shell program"},
25
    {0}
26
};
27
28
PyDoc_STRVAR(struct_passwd__doc__,
29
"pwd.struct_passwd: Results from getpw*() routines.\n\n\
30
This object may be accessed either as a tuple of\n\
31
  (pw_name,pw_passwd,pw_uid,pw_gid,pw_gecos,pw_dir,pw_shell)\n\
32
or via the object attributes as named in the above tuple.");
33
34
static PyStructSequence_Desc struct_pwd_type_desc = {
35
    "pwd.struct_passwd",
36
    struct_passwd__doc__,
37
    struct_pwd_type_fields,
38
    7,
39
};
40
41
PyDoc_STRVAR(pwd__doc__,
42
"This module provides access to the Unix password database.\n\
43
It is available on all Unix versions.\n\
44
\n\
45
Password database entries are reported as 7-tuples containing the following\n\
46
items from the password database (see `<pwd.h>'), in order:\n\
47
pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell.\n\
48
The uid and gid items are integers, all others are strings. An\n\
49
exception is raised if the entry asked for cannot be found.");
50
51
52
typedef struct {
53
    PyTypeObject *StructPwdType;
54
} pwdmodulestate;
55
56
static inline pwdmodulestate*
57
get_pwd_state(PyObject *module)
58
100
{
59
100
    void *state = PyModule_GetState(module);
60
100
    assert(state != NULL);
61
100
    return (pwdmodulestate *)state;
62
100
}
63
64
static struct PyModuleDef pwdmodule;
65
66
/* Mutex to protect calls to getpwuid(), getpwnam(), and getpwent().
67
 * These functions return pointer to static data structure, which
68
 * may be overwritten by any subsequent calls. */
69
static PyMutex pwd_db_mutex = {0};
70
71
0
#define DEFAULT_BUFFER_SIZE 1024
72
73
static PyObject *
74
mkpwent(PyObject *module, struct passwd *p)
75
0
{
76
0
    PyObject *v = PyStructSequence_New(get_pwd_state(module)->StructPwdType);
77
0
    if (v == NULL) {
78
0
        return NULL;
79
0
    }
80
81
0
    int setIndex = 0;
82
83
0
#define SET_STRING(VAL) \
84
0
    SET_RESULT((VAL) ? PyUnicode_DecodeFSDefault((VAL)) : Py_NewRef(Py_None))
85
86
0
#define SET_RESULT(CALL)                                     \
87
0
    do {                                                     \
88
0
        PyObject *item = (CALL);                             \
89
0
        if (item == NULL) {                                  \
90
0
            goto error;                                      \
91
0
        }                                                    \
92
0
        PyStructSequence_SetItem(v, setIndex++, item);       \
93
0
    } while(0)
94
95
0
    SET_STRING(p->pw_name);
96
0
#if defined(HAVE_STRUCT_PASSWD_PW_PASSWD) && !defined(__ANDROID__)
97
0
    SET_STRING(p->pw_passwd);
98
#else
99
    SET_STRING("");
100
#endif
101
0
    SET_RESULT(_PyLong_FromUid(p->pw_uid));
102
0
    SET_RESULT(_PyLong_FromGid(p->pw_gid));
103
0
#if defined(HAVE_STRUCT_PASSWD_PW_GECOS)
104
0
    SET_STRING(p->pw_gecos);
105
#else
106
    SET_STRING("");
107
#endif
108
0
    SET_STRING(p->pw_dir);
109
0
    SET_STRING(p->pw_shell);
110
111
0
#undef SET_STRING
112
0
#undef SET_RESULT
113
114
0
    return v;
115
116
0
error:
117
0
    Py_DECREF(v);
118
0
    return NULL;
119
0
}
120
121
/*[clinic input]
122
pwd.getpwuid
123
124
    uidobj as uid: uid_t
125
    /
126
127
Return the password database entry for the given numeric user ID.
128
129
See `help(pwd)` for more on password database entries.
130
[clinic start generated code]*/
131
132
static PyObject *
133
pwd_getpwuid_impl(PyObject *module, uid_t uid)
134
/*[clinic end generated code: output=631bad376fa670c3 input=506d3a592ef19799]*/
135
0
{
136
0
    PyObject *retval = NULL;
137
0
    int nomem = 0;
138
0
    struct passwd *p;
139
0
    char *buf = NULL, *buf2 = NULL;
140
141
0
#ifdef HAVE_GETPWUID_R
142
0
    int status;
143
0
    Py_ssize_t bufsize;
144
    /* Note: 'pwd' will be used via pointer 'p' on getpwuid_r success. */
145
0
    struct passwd pwd;
146
147
0
    Py_BEGIN_ALLOW_THREADS
148
0
    bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
149
0
    if (bufsize == -1) {
150
0
        bufsize = DEFAULT_BUFFER_SIZE;
151
0
    }
152
153
0
    while(1) {
154
0
        buf2 = PyMem_RawRealloc(buf, bufsize);
155
0
        if (buf2 == NULL) {
156
0
            p = NULL;
157
0
            nomem = 1;
158
0
            break;
159
0
        }
160
0
        buf = buf2;
161
0
        status = getpwuid_r(uid, &pwd, buf, bufsize, &p);
162
0
        if (status != 0) {
163
0
            p = NULL;
164
0
        }
165
0
        if (p != NULL || status != ERANGE) {
166
0
            break;
167
0
        }
168
0
        if (bufsize > (PY_SSIZE_T_MAX >> 1)) {
169
0
            nomem = 1;
170
0
            break;
171
0
        }
172
0
        bufsize <<= 1;
173
0
    }
174
175
0
    Py_END_ALLOW_THREADS
176
#else
177
    PyMutex_Lock(&pwd_db_mutex);
178
    // The getpwuid() function is not required to be thread-safe.
179
    // https://pubs.opengroup.org/onlinepubs/009604499/functions/getpwuid.html
180
    p = getpwuid(uid);
181
#endif
182
0
    if (p == NULL) {
183
#ifndef HAVE_GETPWUID_R
184
        PyMutex_Unlock(&pwd_db_mutex);
185
#endif
186
0
        PyMem_RawFree(buf);
187
0
        if (nomem == 1) {
188
0
            return PyErr_NoMemory();
189
0
        }
190
0
        PyObject *uid_obj = _PyLong_FromUid(uid);
191
0
        if (uid_obj == NULL)
192
0
            return NULL;
193
0
        PyErr_Format(PyExc_KeyError,
194
0
                     "getpwuid(): uid not found: %S", uid_obj);
195
0
        Py_DECREF(uid_obj);
196
0
        return NULL;
197
0
    }
198
0
    retval = mkpwent(module, p);
199
0
#ifdef HAVE_GETPWUID_R
200
0
    PyMem_RawFree(buf);
201
#else
202
    PyMutex_Unlock(&pwd_db_mutex);
203
#endif
204
0
    return retval;
205
0
}
206
207
/*[clinic input]
208
pwd.getpwnam
209
210
    name: unicode
211
    /
212
213
Return the password database entry for the given user name.
214
215
See `help(pwd)` for more on password database entries.
216
[clinic start generated code]*/
217
218
static PyObject *
219
pwd_getpwnam_impl(PyObject *module, PyObject *name)
220
/*[clinic end generated code: output=359ce1ddeb7a824f input=a6aeb5e3447fb9e0]*/
221
0
{
222
0
    char *buf = NULL, *buf2 = NULL, *name_chars;
223
0
    int nomem = 0;
224
0
    struct passwd *p;
225
0
    PyObject *bytes, *retval = NULL;
226
227
0
    if ((bytes = PyUnicode_EncodeFSDefault(name)) == NULL)
228
0
        return NULL;
229
    /* check for embedded null bytes */
230
0
    if (PyBytes_AsStringAndSize(bytes, &name_chars, NULL) == -1)
231
0
        goto out;
232
0
#ifdef HAVE_GETPWNAM_R
233
0
    int status;
234
0
    Py_ssize_t bufsize;
235
    /* Note: 'pwd' will be used via pointer 'p' on getpwnam_r success. */
236
0
    struct passwd pwd;
237
238
0
    Py_BEGIN_ALLOW_THREADS
239
0
    bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
240
0
    if (bufsize == -1) {
241
0
        bufsize = DEFAULT_BUFFER_SIZE;
242
0
    }
243
244
0
    while(1) {
245
0
        buf2 = PyMem_RawRealloc(buf, bufsize);
246
0
        if (buf2 == NULL) {
247
0
            p = NULL;
248
0
            nomem = 1;
249
0
            break;
250
0
        }
251
0
        buf = buf2;
252
0
        status = getpwnam_r(name_chars, &pwd, buf, bufsize, &p);
253
0
        if (status != 0) {
254
0
            p = NULL;
255
0
        }
256
0
        if (p != NULL || status != ERANGE) {
257
0
            break;
258
0
        }
259
0
        if (bufsize > (PY_SSIZE_T_MAX >> 1)) {
260
0
            nomem = 1;
261
0
            break;
262
0
        }
263
0
        bufsize <<= 1;
264
0
    }
265
266
0
    Py_END_ALLOW_THREADS
267
#else
268
    PyMutex_Lock(&pwd_db_mutex);
269
    // The getpwnam() function is not required to be thread-safe.
270
    // https://pubs.opengroup.org/onlinepubs/009604599/functions/getpwnam.html
271
    p = getpwnam(name_chars);
272
#endif
273
0
    if (p == NULL) {
274
#ifndef HAVE_GETPWNAM_R
275
        PyMutex_Unlock(&pwd_db_mutex);
276
#endif
277
0
        if (nomem == 1) {
278
0
            PyErr_NoMemory();
279
0
        }
280
0
        else {
281
0
            PyErr_Format(PyExc_KeyError,
282
0
                         "getpwnam(): name not found: %R", name);
283
0
        }
284
0
        goto out;
285
0
    }
286
0
    retval = mkpwent(module, p);
287
#ifndef HAVE_GETPWNAM_R
288
    PyMutex_Unlock(&pwd_db_mutex);
289
#endif
290
0
out:
291
0
    PyMem_RawFree(buf);
292
0
    Py_DECREF(bytes);
293
0
    return retval;
294
0
}
295
296
#ifdef HAVE_GETPWENT
297
/*[clinic input]
298
@permit_long_summary
299
pwd.getpwall
300
301
Return a list of all available password database entries, in arbitrary order.
302
303
See help(pwd) for more on password database entries.
304
[clinic start generated code]*/
305
306
static PyObject *
307
pwd_getpwall_impl(PyObject *module)
308
/*[clinic end generated code: output=4853d2f5a0afac8a input=f8145e0d9a79e32c]*/
309
0
{
310
0
    PyObject *d;
311
0
    struct passwd *p;
312
0
    if ((d = PyList_New(0)) == NULL)
313
0
        return NULL;
314
315
0
    PyMutex_Lock(&pwd_db_mutex);
316
0
    int failure = 0;
317
0
    PyObject *v = NULL;
318
    // The setpwent(), getpwent() and endpwent() functions are not required to
319
    // be thread-safe.
320
    // https://pubs.opengroup.org/onlinepubs/009696799/functions/setpwent.html
321
0
    setpwent();
322
0
    while ((p = getpwent()) != NULL) {
323
0
        v = mkpwent(module, p);
324
0
        if (v == NULL || PyList_Append(d, v) != 0) {
325
            /* NOTE: cannot dec-ref here, while holding the mutex. */
326
0
            failure = 1;
327
0
            goto done;
328
0
        }
329
0
        Py_DECREF(v);
330
0
    }
331
332
0
done:
333
0
    endpwent();
334
0
    PyMutex_Unlock(&pwd_db_mutex);
335
0
    if (failure) {
336
0
        Py_XDECREF(v);
337
0
        Py_CLEAR(d);
338
0
    }
339
0
    return d;
340
0
}
341
#endif
342
343
static PyMethodDef pwd_methods[] = {
344
    PWD_GETPWUID_METHODDEF
345
    PWD_GETPWNAM_METHODDEF
346
#ifdef HAVE_GETPWENT
347
    PWD_GETPWALL_METHODDEF
348
#endif
349
    {NULL,              NULL}           /* sentinel */
350
};
351
352
static int
353
pwdmodule_exec(PyObject *module)
354
8
{
355
8
    pwdmodulestate *state = get_pwd_state(module);
356
357
8
    state->StructPwdType = PyStructSequence_NewType(&struct_pwd_type_desc);
358
8
    if (state->StructPwdType == NULL) {
359
0
        return -1;
360
0
    }
361
8
    if (PyModule_AddType(module, state->StructPwdType) < 0) {
362
0
        return -1;
363
0
    }
364
8
    return 0;
365
8
}
366
367
static PyModuleDef_Slot pwdmodule_slots[] = {
368
    _Py_ABI_SLOT,
369
    {Py_mod_exec, pwdmodule_exec},
370
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
371
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
372
    {0, NULL}
373
};
374
375
46
static int pwdmodule_traverse(PyObject *m, visitproc visit, void *arg) {
376
46
    Py_VISIT(get_pwd_state(m)->StructPwdType);
377
46
    return 0;
378
46
}
379
0
static int pwdmodule_clear(PyObject *m) {
380
0
    Py_CLEAR(get_pwd_state(m)->StructPwdType);
381
0
    return 0;
382
0
}
383
0
static void pwdmodule_free(void *m) {
384
0
    pwdmodule_clear((PyObject *)m);
385
0
}
386
387
static struct PyModuleDef pwdmodule = {
388
    PyModuleDef_HEAD_INIT,
389
    .m_name = "pwd",
390
    .m_doc = pwd__doc__,
391
    .m_size = sizeof(pwdmodulestate),
392
    .m_methods = pwd_methods,
393
    .m_slots = pwdmodule_slots,
394
    .m_traverse = pwdmodule_traverse,
395
    .m_clear = pwdmodule_clear,
396
    .m_free = pwdmodule_free,
397
};
398
399
400
PyMODINIT_FUNC
401
PyInit_pwd(void)
402
8
{
403
8
    return PyModuleDef_Init(&pwdmodule);
404
8
}