@@ -55,6 +55,11 @@ get_grp_state(PyObject *module)
5555
5656static struct PyModuleDef grpmodule ;
5757
58+ /* Mutex to protect calls to getgrgid(), getgrnam(), and getgrent().
59+ * These functions return pointer to static data structure, which
60+ * may be overwritten by any subsequent calls. */
61+ static PyMutex group_db_mutex = {0 };
62+
5863#define DEFAULT_BUFFER_SIZE 1024
5964
6065static PyObject *
@@ -168,15 +173,14 @@ grp_getgrgid_impl(PyObject *module, PyObject *id)
168173
169174 Py_END_ALLOW_THREADS
170175#else
171- static PyMutex getgrgid_mutex = {0 };
172- PyMutex_Lock (& getgrgid_mutex );
176+ PyMutex_Lock (& group_db_mutex );
173177 // The getgrgid() function need not be thread-safe.
174178 // https://pubs.opengroup.org/onlinepubs/9699919799/functions/getgrgid.html
175179 p = getgrgid (gid );
176180#endif
177181 if (p == NULL ) {
178182#ifndef HAVE_GETGRGID_R
179- PyMutex_Unlock (& getgrgid_mutex );
183+ PyMutex_Unlock (& group_db_mutex );
180184#endif
181185 PyMem_RawFree (buf );
182186 if (nomem == 1 ) {
@@ -193,7 +197,7 @@ grp_getgrgid_impl(PyObject *module, PyObject *id)
193197#ifdef HAVE_GETGRGID_R
194198 PyMem_RawFree (buf );
195199#else
196- PyMutex_Unlock (& getgrgid_mutex );
200+ PyMutex_Unlock (& group_db_mutex );
197201#endif
198202 return retval ;
199203}
@@ -258,15 +262,14 @@ grp_getgrnam_impl(PyObject *module, PyObject *name)
258262
259263 Py_END_ALLOW_THREADS
260264#else
261- static PyMutex getgrnam_mutex = {0 };
262- PyMutex_Lock (& getgrnam_mutex );
265+ PyMutex_Lock (& group_db_mutex );
263266 // The getgrnam() function need not be thread-safe.
264267 // https://pubs.opengroup.org/onlinepubs/9699919799/functions/getgrnam.html
265268 p = getgrnam (name_chars );
266269#endif
267270 if (p == NULL ) {
268271#ifndef HAVE_GETGRNAM_R
269- PyMutex_Unlock (& getgrnam_mutex );
272+ PyMutex_Unlock (& group_db_mutex );
270273#endif
271274 if (nomem == 1 ) {
272275 PyErr_NoMemory ();
@@ -278,7 +281,7 @@ grp_getgrnam_impl(PyObject *module, PyObject *name)
278281 }
279282 retval = mkgrent (module , p );
280283#ifndef HAVE_GETGRNAM_R
281- PyMutex_Unlock (& getgrnam_mutex );
284+ PyMutex_Unlock (& group_db_mutex );
282285#endif
283286out :
284287 PyMem_RawFree (buf );
@@ -304,8 +307,7 @@ grp_getgrall_impl(PyObject *module)
304307 return NULL ;
305308 }
306309
307- static PyMutex getgrall_mutex = {0 };
308- PyMutex_Lock (& getgrall_mutex );
310+ PyMutex_Lock (& group_db_mutex );
309311 setgrent ();
310312
311313 struct group * p ;
@@ -325,7 +327,7 @@ grp_getgrall_impl(PyObject *module)
325327
326328done :
327329 endgrent ();
328- PyMutex_Unlock (& getgrall_mutex );
330+ PyMutex_Unlock (& group_db_mutex );
329331 return d ;
330332}
331333
0 commit comments