| 1 |
/* |
| 2 |
* Copyright (c) 2009, Giampaolo Rodola'. |
| 3 |
* All rights reserved. |
| 4 |
* Use of this source code is governed by a BSD-style license that can be |
| 5 |
* found in the LICENSE file. |
| 6 |
*/ |
| 7 |
|
| 8 |
#include <Python.h> |
| 9 |
#include <utmp.h> |
| 10 |
|
| 11 |
#include "../../arch/all/init.h" |
| 12 |
|
| 13 |
|
| 14 |
PyObject * |
| 15 |
psutil_users(PyObject *self, PyObject *args) { |
| 16 |
PyObject *py_retlist = PyList_New(0); |
| 17 |
PyObject *py_username = NULL; |
| 18 |
PyObject *py_tty = NULL; |
| 19 |
PyObject *py_hostname = NULL; |
| 20 |
PyObject *py_tuple = NULL; |
| 21 |
|
| 22 |
if (py_retlist == NULL) |
| 23 |
return NULL; |
| 24 |
|
| 25 |
struct utmp ut; |
| 26 |
FILE *fp; |
| 27 |
|
| 28 |
Py_BEGIN_ALLOW_THREADS |
| 29 |
fp = fopen(_PATH_UTMP, "r"); |
| 30 |
Py_END_ALLOW_THREADS |
| 31 |
if (fp == NULL) { |
| 32 |
PyErr_SetFromErrnoWithFilename(PyExc_OSError, _PATH_UTMP); |
| 33 |
goto error; |
| 34 |
} |
| 35 |
|
| 36 |
while (fread(&ut, sizeof(ut), 1, fp) == 1) { |
| 37 |
if (*ut.ut_name == '\0') |
| 38 |
continue; |
| 39 |
py_username = PyUnicode_DecodeFSDefault(ut.ut_name); |
| 40 |
if (! py_username) |
| 41 |
goto error; |
| 42 |
py_tty = PyUnicode_DecodeFSDefault(ut.ut_line); |
| 43 |
if (! py_tty) |
| 44 |
goto error; |
| 45 |
py_hostname = PyUnicode_DecodeFSDefault(ut.ut_host); |
| 46 |
if (! py_hostname) |
| 47 |
goto error; |
| 48 |
py_tuple = Py_BuildValue( |
| 49 |
"(OOOdO)", |
| 50 |
py_username, // username |
| 51 |
py_tty, // tty |
| 52 |
py_hostname, // hostname |
| 53 |
(double)ut.ut_time, // start time |
| 54 |
Py_None // pid |
| 55 |
); |
| 56 |
if (!py_tuple) |
| 57 |
goto error; |
| 58 |
if (PyList_Append(py_retlist, py_tuple)) |
| 59 |
goto error; |
| 60 |
Py_CLEAR(py_username); |
| 61 |
Py_CLEAR(py_tty); |
| 62 |
Py_CLEAR(py_hostname); |
| 63 |
Py_CLEAR(py_tuple); |
| 64 |
} |
| 65 |
|
| 66 |
fclose(fp); |
| 67 |
return py_retlist; |
| 68 |
|
| 69 |
error: |
| 70 |
fclose(fp); |
| 71 |
Py_XDECREF(py_username); |
| 72 |
Py_XDECREF(py_tty); |
| 73 |
Py_XDECREF(py_hostname); |
| 74 |
Py_XDECREF(py_tuple); |
| 75 |
Py_DECREF(py_retlist); |
| 76 |
return NULL; |
| 77 |
} |