Skip to content

Commit

Permalink
#1040 / unicode / bsd: fix unicode handling for users()
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo committed May 1, 2017
1 parent 0fab2e5 commit b19ddf8
Showing 1 changed file with 39 additions and 10 deletions.
49 changes: 39 additions & 10 deletions psutil/_psutil_bsd.c
Expand Up @@ -791,6 +791,9 @@ psutil_net_io_counters(PyObject *self, PyObject *args) {
static PyObject *
psutil_users(PyObject *self, PyObject *args) {
PyObject *py_retlist = PyList_New(0);
PyObject *py_username = NULL;
PyObject *py_tty = NULL;
PyObject *py_hostname = NULL;
PyObject *py_tuple = NULL;

if (py_retlist == NULL)
Expand All @@ -809,12 +812,21 @@ psutil_users(PyObject *self, PyObject *args) {
while (fread(&ut, sizeof(ut), 1, fp) == 1) {
if (*ut.ut_name == '\0')
continue;
py_username = psutil_PyUnicode_DecodeFSDefault(ut.ut_name);
if (! py_username)
goto error;
py_tty = psutil_PyUnicode_DecodeFSDefault(ut.ut_line);
if (! py_tty)
goto error;
py_hostname = psutil_PyUnicode_DecodeFSDefault(ut.ut_host);
if (! py_hostname)
goto error;
py_tuple = Py_BuildValue(
"(sssfi)",
ut.ut_name, // username
ut.ut_line, // tty
ut.ut_host, // hostname
(float)ut.ut_time, // start time
"(OOOfi)",
py_username, // username
py_tty, // tty
py_hostname, // hostname
(float)ut.ut_time, // start time
ut.ut_pid // process id
);
if (!py_tuple) {
Expand All @@ -825,22 +837,33 @@ psutil_users(PyObject *self, PyObject *args) {
fclose(fp);
goto error;
}
Py_DECREF(py_username);
Py_DECREF(py_tty);
Py_DECREF(py_hostname);
Py_DECREF(py_tuple);
}

fclose(fp);
#else
struct utmpx *utx;

setutxent();
while ((utx = getutxent()) != NULL) {
if (utx->ut_type != USER_PROCESS)
continue;
py_username = psutil_PyUnicode_DecodeFSDefault(utx->ut_user);
if (! py_username)
goto error;
py_tty = psutil_PyUnicode_DecodeFSDefault(utx->ut_line);
if (! py_tty)
goto error;
py_hostname = psutil_PyUnicode_DecodeFSDefault(utx->ut_host);
if (! py_hostname)
goto error;
py_tuple = Py_BuildValue(
"(sssfi)",
utx->ut_user, // username
utx->ut_line, // tty
utx->ut_host, // hostname
"(OOOfi)",
py_username, // username
py_tty, // tty
py_hostname, // hostname
(float)utx->ut_tv.tv_sec, // start time
utx->ut_pid // process id
);
Expand All @@ -853,6 +876,9 @@ psutil_users(PyObject *self, PyObject *args) {
endutxent();
goto error;
}
Py_DECREF(py_username);
Py_DECREF(py_tty);
Py_DECREF(py_hostname);
Py_DECREF(py_tuple);
}

Expand All @@ -861,6 +887,9 @@ psutil_users(PyObject *self, PyObject *args) {
return py_retlist;

error:
Py_XDECREF(py_username);
Py_XDECREF(py_tty);
Py_XDECREF(py_hostname);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
return NULL;
Expand Down

0 comments on commit b19ddf8

Please sign in to comment.