Debian Codegraph @

psutil/arch/posix/users.c

raw
1 /*
2 * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
5 */
6
7 #include "../../arch/all/init.h"
8
9 #ifdef PSUTIL_HAS_POSIX_USERS
10 #include <Python.h>
11 #include <string.h>
12
13 #include <utmpx.h>
14
15
16
17 static void
18 setup() {
19 UTXENT_MUTEX_LOCK();
20 setutxent();
21 }
22
23
24 static void
25 teardown() {
26 endutxent();
27 UTXENT_MUTEX_UNLOCK();
28 }
29
30
31 PyObject *
32 psutil_users(PyObject *self, PyObject *args) {
33 struct utmpx *ut;
34 PyObject *py_username = NULL;
35 PyObject *py_tty = NULL;
36 PyObject *py_hostname = NULL;
37 PyObject *py_tuple = NULL;
38 PyObject *py_retlist = PyList_New(0);
39
40 if (py_retlist == NULL)
41 return NULL;
42
43 setup();
44
45 while ((ut = getutxent()) != NULL) {
46 if (ut->ut_type != USER_PROCESS)
47 continue;
48 py_tuple = NULL;
49
50 py_username = PyUnicode_DecodeFSDefault(ut->ut_user);
51 if (! py_username)
52 goto error;
53
54 py_tty = PyUnicode_DecodeFSDefault(ut->ut_line);
55 if (! py_tty)
56 goto error;
57
58 if (strcmp(ut->ut_host, ":0") == 0 || strcmp(ut->ut_host, ":0.0") == 0)
59 py_hostname = PyUnicode_DecodeFSDefault("localhost");
60 else
61 py_hostname = PyUnicode_DecodeFSDefault(ut->ut_host);
62 if (! py_hostname)
63 goto error;
64
65 py_tuple = Py_BuildValue(
66 "OOOd" _Py_PARSE_PID,
67 py_username, // username
68 py_tty, // tty
69 py_hostname, // hostname
70 (double)ut->ut_tv.tv_sec, // tstamp
71 ut->ut_pid // process id
72 );
73 if (! py_tuple)
74 goto error;
75 if (PyList_Append(py_retlist, py_tuple))
76 goto error;
77 Py_CLEAR(py_username);
78 Py_CLEAR(py_tty);
79 Py_CLEAR(py_hostname);
80 Py_CLEAR(py_tuple);
81 }
82
83 teardown();
84 return py_retlist;
85
86 error:
87 teardown();
88 Py_XDECREF(py_username);
89 Py_XDECREF(py_tty);
90 Py_XDECREF(py_hostname);
91 Py_XDECREF(py_tuple);
92 Py_DECREF(py_retlist);
93 return NULL;
94 }
95 #endif // PSUTIL_HAS_POSIX_USERS