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