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