_psutil_posix.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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. * Functions specific to all POSIX compliant platforms.
  7. */
  8. #include <Python.h>
  9. #include <errno.h>
  10. #include <stdlib.h>
  11. #include <sys/resource.h>
  12. #include <sys/types.h>
  13. #include <signal.h>
  14. #include <sys/socket.h>
  15. #include <sys/ioctl.h>
  16. #include <net/if.h>
  17. #include <unistd.h>
  18. #ifdef PSUTIL_SUNOS10
  19. #error #include "arch/solaris/v10/ifaddrs.h"
  20. #elif PSUTIL_AIX
  21. #error #include "arch/aix/ifaddrs.h"
  22. #else
  23. #include <ifaddrs.h>
  24. #endif
  25. #if defined(PSUTIL_LINUX)
  26. #include <netdb.h>
  27. #include <linux/types.h>
  28. #include <linux/if_packet.h>
  29. #endif
  30. #if defined(PSUTIL_BSD) || defined(PSUTIL_OSX)
  31. #include <netdb.h>
  32. #include <netinet/in.h>
  33. #include <net/if_dl.h>
  34. #include <sys/sockio.h>
  35. #include <net/if_media.h>
  36. #include <net/if.h>
  37. #endif
  38. #if defined(PSUTIL_SUNOS)
  39. #include <netdb.h>
  40. #include <sys/sockio.h>
  41. #endif
  42. #if defined(PSUTIL_AIX)
  43. #include <netdb.h>
  44. #endif
  45. #if defined(PSUTIL_LINUX) || defined(PSUTIL_FREEBSD)
  46. #include <sys/resource.h>
  47. #endif
  48. #include "_psutil_common.h"
  49. // ====================================================================
  50. // --- Utils
  51. // ====================================================================
  52. /*
  53. * From "man getpagesize" on Linux, https://linux.die.net/man/2/getpagesize:
  54. *
  55. * > In SUSv2 the getpagesize() call is labeled LEGACY, and in POSIX.1-2001
  56. * > it has been dropped.
  57. * > Portable applications should employ sysconf(_SC_PAGESIZE) instead
  58. * > of getpagesize().
  59. * > Most systems allow the synonym _SC_PAGE_SIZE for _SC_PAGESIZE.
  60. * > Whether getpagesize() is present as a Linux system call depends on the
  61. * > architecture.
  62. */
  63. long
  64. psutil_getpagesize(void) {
  65. #ifdef _SC_PAGESIZE
  66. // recommended POSIX
  67. return sysconf(_SC_PAGESIZE);
  68. #elif _SC_PAGE_SIZE
  69. // alias
  70. return sysconf(_SC_PAGE_SIZE);
  71. #else
  72. // legacy
  73. return (long) getpagesize();
  74. #endif
  75. }
  76. /*
  77. * Check if PID exists. Return values:
  78. * 1: exists
  79. * 0: does not exist
  80. * -1: error (Python exception is set)
  81. */
  82. int
  83. psutil_pid_exists(pid_t pid) {
  84. int ret;
  85. // No negative PID exists, plus -1 is an alias for sending signal
  86. // too all processes except system ones. Not what we want.
  87. if (pid < 0)
  88. return 0;
  89. // As per "man 2 kill" PID 0 is an alias for sending the signal to
  90. // every process in the process group of the calling process.
  91. // Not what we want. Some platforms have PID 0, some do not.
  92. // We decide that at runtime.
  93. if (pid == 0) {
  94. #if defined(PSUTIL_LINUX) || defined(PSUTIL_FREEBSD)
  95. return 0;
  96. #else
  97. return 1;
  98. #endif
  99. }
  100. ret = kill(pid , 0);
  101. if (ret == 0)
  102. return 1;
  103. else {
  104. if (errno == ESRCH) {
  105. // ESRCH == No such process
  106. return 0;
  107. }
  108. else if (errno == EPERM) {
  109. // EPERM clearly indicates there's a process to deny
  110. // access to.
  111. return 1;
  112. }
  113. else {
  114. // According to "man 2 kill" possible error values are
  115. // (EINVAL, EPERM, ESRCH) therefore we should never get
  116. // here. If we do let's be explicit in considering this
  117. // an error.
  118. PyErr_SetFromErrno(PyExc_OSError);
  119. return -1;
  120. }
  121. }
  122. }
  123. /*
  124. * Utility used for those syscalls which do not return a meaningful
  125. * error that we can translate into an exception which makes sense.
  126. * As such, we'll have to guess.
  127. * On UNIX, if errno is set, we return that one (OSError).
  128. * Else, if PID does not exist we assume the syscall failed because
  129. * of that so we raise NoSuchProcess.
  130. * If none of this is true we giveup and raise RuntimeError(msg).
  131. * This will always set a Python exception and return NULL.
  132. */
  133. void
  134. psutil_raise_for_pid(long pid, char *syscall) {
  135. if (errno != 0)
  136. psutil_PyErr_SetFromOSErrnoWithSyscall(syscall);
  137. else if (psutil_pid_exists(pid) == 0)
  138. NoSuchProcess(syscall);
  139. else
  140. PyErr_Format(PyExc_RuntimeError, "%s syscall failed", syscall);
  141. }
  142. // ====================================================================
  143. // --- Python wrappers
  144. // ====================================================================
  145. // Exposed so we can test it against Python's stdlib.
  146. static PyObject *
  147. psutil_getpagesize_pywrapper(PyObject *self, PyObject *args) {
  148. return Py_BuildValue("l", psutil_getpagesize());
  149. }
  150. /*
  151. * Given a PID return process priority as a Python integer.
  152. */
  153. static PyObject *
  154. psutil_posix_getpriority(PyObject *self, PyObject *args) {
  155. pid_t pid;
  156. int priority;
  157. errno = 0;
  158. if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
  159. return NULL;
  160. #ifdef PSUTIL_OSX
  161. priority = getpriority(PRIO_PROCESS, (id_t)pid);
  162. #else
  163. priority = getpriority(PRIO_PROCESS, pid);
  164. #endif
  165. if (errno != 0)
  166. return PyErr_SetFromErrno(PyExc_OSError);
  167. return Py_BuildValue("i", priority);
  168. }
  169. /*
  170. * Given a PID and a value change process priority.
  171. */
  172. static PyObject *
  173. psutil_posix_setpriority(PyObject *self, PyObject *args) {
  174. pid_t pid;
  175. int priority;
  176. int retval;
  177. if (! PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &priority))
  178. return NULL;
  179. #ifdef PSUTIL_OSX
  180. retval = setpriority(PRIO_PROCESS, (id_t)pid, priority);
  181. #else
  182. retval = setpriority(PRIO_PROCESS, pid, priority);
  183. #endif
  184. if (retval == -1)
  185. return PyErr_SetFromErrno(PyExc_OSError);
  186. Py_RETURN_NONE;
  187. }
  188. /*
  189. * Translate a sockaddr struct into a Python string.
  190. * Return None if address family is not AF_INET* or AF_PACKET.
  191. */
  192. static PyObject *
  193. psutil_convert_ipaddr(struct sockaddr *addr, int family) {
  194. char buf[NI_MAXHOST];
  195. int err;
  196. int addrlen;
  197. size_t n;
  198. size_t len;
  199. const char *data;
  200. char *ptr;
  201. if (addr == NULL) {
  202. Py_INCREF(Py_None);
  203. return Py_None;
  204. }
  205. else if (family == AF_INET || family == AF_INET6) {
  206. if (family == AF_INET)
  207. addrlen = sizeof(struct sockaddr_in);
  208. else
  209. addrlen = sizeof(struct sockaddr_in6);
  210. err = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
  211. NI_NUMERICHOST);
  212. if (err != 0) {
  213. // XXX we get here on FreeBSD when processing 'lo' / AF_INET6
  214. // broadcast. Not sure what to do other than returning None.
  215. // ifconfig does not show anything BTW.
  216. // PyErr_Format(PyExc_RuntimeError, gai_strerror(err));
  217. // return NULL;
  218. Py_INCREF(Py_None);
  219. return Py_None;
  220. }
  221. else {
  222. return Py_BuildValue("s", buf);
  223. }
  224. }
  225. #ifdef PSUTIL_LINUX
  226. else if (family == AF_PACKET) {
  227. struct sockaddr_ll *lladdr = (struct sockaddr_ll *)addr;
  228. len = lladdr->sll_halen;
  229. data = (const char *)lladdr->sll_addr;
  230. }
  231. #elif defined(PSUTIL_BSD) || defined(PSUTIL_OSX)
  232. else if (addr->sa_family == AF_LINK) {
  233. // Note: prior to Python 3.4 socket module does not expose
  234. // AF_LINK so we'll do.
  235. struct sockaddr_dl *dladdr = (struct sockaddr_dl *)addr;
  236. len = dladdr->sdl_alen;
  237. data = LLADDR(dladdr);
  238. }
  239. #endif
  240. else {
  241. // unknown family
  242. Py_INCREF(Py_None);
  243. return Py_None;
  244. }
  245. // AF_PACKET or AF_LINK
  246. if (len > 0) {
  247. ptr = buf;
  248. for (n = 0; n < len; ++n) {
  249. sprintf(ptr, "%02x:", data[n] & 0xff);
  250. ptr += 3;
  251. }
  252. *--ptr = '\0';
  253. return Py_BuildValue("s", buf);
  254. }
  255. else {
  256. Py_INCREF(Py_None);
  257. return Py_None;
  258. }
  259. }
  260. /*
  261. * Return NICs information a-la ifconfig as a list of tuples.
  262. * TODO: on Solaris we won't get any MAC address.
  263. */
  264. static PyObject*
  265. psutil_net_if_addrs(PyObject* self, PyObject* args) {
  266. struct ifaddrs *ifaddr, *ifa;
  267. int family;
  268. PyObject *py_retlist = PyList_New(0);
  269. PyObject *py_tuple = NULL;
  270. PyObject *py_address = NULL;
  271. PyObject *py_netmask = NULL;
  272. PyObject *py_broadcast = NULL;
  273. PyObject *py_ptp = NULL;
  274. if (py_retlist == NULL)
  275. return NULL;
  276. if (getifaddrs(&ifaddr) == -1) {
  277. PyErr_SetFromErrno(PyExc_OSError);
  278. goto error;
  279. }
  280. for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
  281. if (!ifa->ifa_addr)
  282. continue;
  283. family = ifa->ifa_addr->sa_family;
  284. py_address = psutil_convert_ipaddr(ifa->ifa_addr, family);
  285. // If the primary address can't be determined just skip it.
  286. // I've never seen this happen on Linux but I did on FreeBSD.
  287. if (py_address == Py_None)
  288. continue;
  289. if (py_address == NULL)
  290. goto error;
  291. py_netmask = psutil_convert_ipaddr(ifa->ifa_netmask, family);
  292. if (py_netmask == NULL)
  293. goto error;
  294. if (ifa->ifa_flags & IFF_BROADCAST) {
  295. py_broadcast = psutil_convert_ipaddr(ifa->ifa_broadaddr, family);
  296. Py_INCREF(Py_None);
  297. py_ptp = Py_None;
  298. }
  299. else if (ifa->ifa_flags & IFF_POINTOPOINT) {
  300. py_ptp = psutil_convert_ipaddr(ifa->ifa_dstaddr, family);
  301. Py_INCREF(Py_None);
  302. py_broadcast = Py_None;
  303. }
  304. else {
  305. Py_INCREF(Py_None);
  306. Py_INCREF(Py_None);
  307. py_broadcast = Py_None;
  308. py_ptp = Py_None;
  309. }
  310. if ((py_broadcast == NULL) || (py_ptp == NULL))
  311. goto error;
  312. py_tuple = Py_BuildValue(
  313. "(siOOOO)",
  314. ifa->ifa_name,
  315. family,
  316. py_address,
  317. py_netmask,
  318. py_broadcast,
  319. py_ptp
  320. );
  321. if (! py_tuple)
  322. goto error;
  323. if (PyList_Append(py_retlist, py_tuple))
  324. goto error;
  325. Py_CLEAR(py_tuple);
  326. Py_CLEAR(py_address);
  327. Py_CLEAR(py_netmask);
  328. Py_CLEAR(py_broadcast);
  329. Py_CLEAR(py_ptp);
  330. }
  331. freeifaddrs(ifaddr);
  332. return py_retlist;
  333. error:
  334. if (ifaddr != NULL)
  335. freeifaddrs(ifaddr);
  336. Py_DECREF(py_retlist);
  337. Py_XDECREF(py_tuple);
  338. Py_XDECREF(py_address);
  339. Py_XDECREF(py_netmask);
  340. Py_XDECREF(py_broadcast);
  341. Py_XDECREF(py_ptp);
  342. return NULL;
  343. }
  344. /*
  345. * Return NIC MTU. References:
  346. * http://www.i-scream.org/libstatgrab/
  347. */
  348. static PyObject *
  349. psutil_net_if_mtu(PyObject *self, PyObject *args) {
  350. char *nic_name;
  351. int sock = -1;
  352. int ret;
  353. #ifdef PSUTIL_SUNOS10
  354. struct lifreq lifr;
  355. #else
  356. struct ifreq ifr;
  357. #endif
  358. if (! PyArg_ParseTuple(args, "s", &nic_name))
  359. return NULL;
  360. sock = socket(AF_INET, SOCK_DGRAM, 0);
  361. if (sock == -1)
  362. goto error;
  363. #ifdef PSUTIL_SUNOS10
  364. PSUTIL_STRNCPY(lifr.lifr_name, nic_name, sizeof(lifr.lifr_name));
  365. ret = ioctl(sock, SIOCGIFMTU, &lifr);
  366. #else
  367. PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name));
  368. ret = ioctl(sock, SIOCGIFMTU, &ifr);
  369. #endif
  370. if (ret == -1)
  371. goto error;
  372. close(sock);
  373. #ifdef PSUTIL_SUNOS10
  374. return Py_BuildValue("i", lifr.lifr_mtu);
  375. #else
  376. return Py_BuildValue("i", ifr.ifr_mtu);
  377. #endif
  378. error:
  379. if (sock != -1)
  380. close(sock);
  381. return PyErr_SetFromErrno(PyExc_OSError);
  382. }
  383. static int
  384. append_flag(PyObject *py_retlist, const char * flag_name)
  385. {
  386. PyObject *py_str = NULL;
  387. #if PY_MAJOR_VERSION >= 3
  388. py_str = PyUnicode_FromString(flag_name);
  389. #else
  390. py_str = PyString_FromString(flag_name);
  391. #endif
  392. if (! py_str)
  393. return 0;
  394. if (PyList_Append(py_retlist, py_str)) {
  395. Py_DECREF(py_str);
  396. return 0;
  397. }
  398. Py_CLEAR(py_str);
  399. return 1;
  400. }
  401. /*
  402. * Get all of the NIC flags and return them.
  403. */
  404. static PyObject *
  405. psutil_net_if_flags(PyObject *self, PyObject *args) {
  406. char *nic_name;
  407. int sock = -1;
  408. int ret;
  409. struct ifreq ifr;
  410. PyObject *py_retlist = PyList_New(0);
  411. short int flags;
  412. if (py_retlist == NULL)
  413. return NULL;
  414. if (! PyArg_ParseTuple(args, "s", &nic_name))
  415. goto error;
  416. sock = socket(AF_INET, SOCK_DGRAM, 0);
  417. if (sock == -1) {
  418. psutil_PyErr_SetFromOSErrnoWithSyscall("socket(SOCK_DGRAM)");
  419. goto error;
  420. }
  421. PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name));
  422. ret = ioctl(sock, SIOCGIFFLAGS, &ifr);
  423. if (ret == -1) {
  424. psutil_PyErr_SetFromOSErrnoWithSyscall("ioctl(SIOCGIFFLAGS)");
  425. goto error;
  426. }
  427. close(sock);
  428. sock = -1;
  429. flags = ifr.ifr_flags & 0xFFFF;
  430. // Linux/glibc IFF flags: https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/gnu/net/if.h;h=251418f82331c0426e58707fe4473d454893b132;hb=HEAD
  431. // macOS IFF flags: https://opensource.apple.com/source/xnu/xnu-792/bsd/net/if.h.auto.html
  432. // AIX IFF flags: https://www.ibm.com/support/pages/how-hexadecimal-flags-displayed-ifconfig-are-calculated
  433. // FreeBSD IFF flags: https://www.freebsd.org/cgi/man.cgi?query=if_allmulti&apropos=0&sektion=0&manpath=FreeBSD+10-current&format=html
  434. #ifdef IFF_UP
  435. // Available in (at least) Linux, macOS, AIX, BSD
  436. if (flags & IFF_UP)
  437. if (!append_flag(py_retlist, "up"))
  438. goto error;
  439. #endif
  440. #ifdef IFF_BROADCAST
  441. // Available in (at least) Linux, macOS, AIX, BSD
  442. if (flags & IFF_BROADCAST)
  443. if (!append_flag(py_retlist, "broadcast"))
  444. goto error;
  445. #endif
  446. #ifdef IFF_DEBUG
  447. // Available in (at least) Linux, macOS, BSD
  448. if (flags & IFF_DEBUG)
  449. if (!append_flag(py_retlist, "debug"))
  450. goto error;
  451. #endif
  452. #ifdef IFF_LOOPBACK
  453. // Available in (at least) Linux, macOS, BSD
  454. if (flags & IFF_LOOPBACK)
  455. if (!append_flag(py_retlist, "loopback"))
  456. goto error;
  457. #endif
  458. #ifdef IFF_POINTOPOINT
  459. // Available in (at least) Linux, macOS, BSD
  460. if (flags & IFF_POINTOPOINT)
  461. if (!append_flag(py_retlist, "pointopoint"))
  462. goto error;
  463. #endif
  464. #ifdef IFF_NOTRAILERS
  465. // Available in (at least) Linux, macOS, AIX
  466. if (flags & IFF_NOTRAILERS)
  467. if (!append_flag(py_retlist, "notrailers"))
  468. goto error;
  469. #endif
  470. #ifdef IFF_RUNNING
  471. // Available in (at least) Linux, macOS, AIX, BSD
  472. if (flags & IFF_RUNNING)
  473. if (!append_flag(py_retlist, "running"))
  474. goto error;
  475. #endif
  476. #ifdef IFF_NOARP
  477. // Available in (at least) Linux, macOS, BSD
  478. if (flags & IFF_NOARP)
  479. if (!append_flag(py_retlist, "noarp"))
  480. goto error;
  481. #endif
  482. #ifdef IFF_PROMISC
  483. // Available in (at least) Linux, macOS, BSD
  484. if (flags & IFF_PROMISC)
  485. if (!append_flag(py_retlist, "promisc"))
  486. goto error;
  487. #endif
  488. #ifdef IFF_ALLMULTI
  489. // Available in (at least) Linux, macOS, BSD
  490. if (flags & IFF_ALLMULTI)
  491. if (!append_flag(py_retlist, "allmulti"))
  492. goto error;
  493. #endif
  494. #ifdef IFF_MASTER
  495. // Available in (at least) Linux
  496. if (flags & IFF_MASTER)
  497. if (!append_flag(py_retlist, "master"))
  498. goto error;
  499. #endif
  500. #ifdef IFF_SLAVE
  501. // Available in (at least) Linux
  502. if (flags & IFF_SLAVE)
  503. if (!append_flag(py_retlist, "slave"))
  504. goto error;
  505. #endif
  506. #ifdef IFF_MULTICAST
  507. // Available in (at least) Linux, macOS, BSD
  508. if (flags & IFF_MULTICAST)
  509. if (!append_flag(py_retlist, "multicast"))
  510. goto error;
  511. #endif
  512. #ifdef IFF_PORTSEL
  513. // Available in (at least) Linux
  514. if (flags & IFF_PORTSEL)
  515. if (!append_flag(py_retlist, "portsel"))
  516. goto error;
  517. #endif
  518. #ifdef IFF_AUTOMEDIA
  519. // Available in (at least) Linux
  520. if (flags & IFF_AUTOMEDIA)
  521. if (!append_flag(py_retlist, "automedia"))
  522. goto error;
  523. #endif
  524. #ifdef IFF_DYNAMIC
  525. // Available in (at least) Linux
  526. if (flags & IFF_DYNAMIC)
  527. if (!append_flag(py_retlist, "dynamic"))
  528. goto error;
  529. #endif
  530. #ifdef IFF_OACTIVE
  531. // Available in (at least) macOS, BSD
  532. if (flags & IFF_OACTIVE)
  533. if (!append_flag(py_retlist, "oactive"))
  534. goto error;
  535. #endif
  536. #ifdef IFF_SIMPLEX
  537. // Available in (at least) macOS, AIX, BSD
  538. if (flags & IFF_SIMPLEX)
  539. if (!append_flag(py_retlist, "simplex"))
  540. goto error;
  541. #endif
  542. #ifdef IFF_LINK0
  543. // Available in (at least) macOS, BSD
  544. if (flags & IFF_LINK0)
  545. if (!append_flag(py_retlist, "link0"))
  546. goto error;
  547. #endif
  548. #ifdef IFF_LINK1
  549. // Available in (at least) macOS, BSD
  550. if (flags & IFF_LINK1)
  551. if (!append_flag(py_retlist, "link1"))
  552. goto error;
  553. #endif
  554. #ifdef IFF_LINK2
  555. // Available in (at least) macOS, BSD
  556. if (flags & IFF_LINK2)
  557. if (!append_flag(py_retlist, "link2"))
  558. goto error;
  559. #endif
  560. #ifdef IFF_D2
  561. // Available in (at least) AIX
  562. if (flags & IFF_D2)
  563. if (!append_flag(py_retlist, "d2"))
  564. goto error;
  565. #endif
  566. return py_retlist;
  567. error:
  568. Py_DECREF(py_retlist);
  569. if (sock != -1)
  570. close(sock);
  571. return NULL;
  572. }
  573. /*
  574. * Inspect NIC flags, returns a bool indicating whether the NIC is
  575. * running. References:
  576. * http://www.i-scream.org/libstatgrab/
  577. */
  578. static PyObject *
  579. psutil_net_if_is_running(PyObject *self, PyObject *args) {
  580. char *nic_name;
  581. int sock = -1;
  582. int ret;
  583. struct ifreq ifr;
  584. if (! PyArg_ParseTuple(args, "s", &nic_name))
  585. return NULL;
  586. sock = socket(AF_INET, SOCK_DGRAM, 0);
  587. if (sock == -1)
  588. goto error;
  589. PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name));
  590. ret = ioctl(sock, SIOCGIFFLAGS, &ifr);
  591. if (ret == -1)
  592. goto error;
  593. close(sock);
  594. if ((ifr.ifr_flags & IFF_RUNNING) != 0)
  595. return Py_BuildValue("O", Py_True);
  596. else
  597. return Py_BuildValue("O", Py_False);
  598. error:
  599. if (sock != -1)
  600. close(sock);
  601. return PyErr_SetFromErrno(PyExc_OSError);
  602. }
  603. /*
  604. * net_if_stats() macOS/BSD implementation.
  605. */
  606. #if defined(PSUTIL_BSD) || defined(PSUTIL_OSX)
  607. int psutil_get_nic_speed(int ifm_active) {
  608. // Determine NIC speed. Taken from:
  609. // http://www.i-scream.org/libstatgrab/
  610. // Assuming only ETHER devices
  611. switch(IFM_TYPE(ifm_active)) {
  612. case IFM_ETHER:
  613. switch(IFM_SUBTYPE(ifm_active)) {
  614. #if defined(IFM_HPNA_1) && ((!defined(IFM_10G_LR)) \
  615. || (IFM_10G_LR != IFM_HPNA_1))
  616. // HomePNA 1.0 (1Mb/s)
  617. case(IFM_HPNA_1):
  618. return 1;
  619. #endif
  620. // 10 Mbit
  621. case(IFM_10_T): // 10BaseT - RJ45
  622. case(IFM_10_2): // 10Base2 - Thinnet
  623. case(IFM_10_5): // 10Base5 - AUI
  624. case(IFM_10_STP): // 10BaseT over shielded TP
  625. case(IFM_10_FL): // 10baseFL - Fiber
  626. return 10;
  627. // 100 Mbit
  628. case(IFM_100_TX): // 100BaseTX - RJ45
  629. case(IFM_100_FX): // 100BaseFX - Fiber
  630. case(IFM_100_T4): // 100BaseT4 - 4 pair cat 3
  631. case(IFM_100_VG): // 100VG-AnyLAN
  632. case(IFM_100_T2): // 100BaseT2
  633. return 100;
  634. // 1000 Mbit
  635. case(IFM_1000_SX): // 1000BaseSX - multi-mode fiber
  636. case(IFM_1000_LX): // 1000baseLX - single-mode fiber
  637. case(IFM_1000_CX): // 1000baseCX - 150ohm STP
  638. #if defined(IFM_1000_TX) && !defined(PSUTIL_OPENBSD)
  639. #define HAS_CASE_IFM_1000_TX 1
  640. // FreeBSD 4 and others (but NOT OpenBSD) -> #define IFM_1000_T in net/if_media.h
  641. case(IFM_1000_TX):
  642. #endif
  643. #ifdef IFM_1000_FX
  644. case(IFM_1000_FX):
  645. #endif
  646. #if defined(IFM_1000_T) && (!HAS_CASE_IFM_1000_TX || IFM_1000_T != IFM_1000_TX)
  647. case(IFM_1000_T):
  648. #endif
  649. return 1000;
  650. #if defined(IFM_10G_SR) || defined(IFM_10G_LR) || defined(IFM_10G_CX4) \
  651. || defined(IFM_10G_T)
  652. #ifdef IFM_10G_SR
  653. case(IFM_10G_SR):
  654. #endif
  655. #ifdef IFM_10G_LR
  656. case(IFM_10G_LR):
  657. #endif
  658. #ifdef IFM_10G_CX4
  659. case(IFM_10G_CX4):
  660. #endif
  661. #ifdef IFM_10G_TWINAX
  662. case(IFM_10G_TWINAX):
  663. #endif
  664. #ifdef IFM_10G_TWINAX_LONG
  665. case(IFM_10G_TWINAX_LONG):
  666. #endif
  667. #ifdef IFM_10G_T
  668. case(IFM_10G_T):
  669. #endif
  670. return 10000;
  671. #endif
  672. #if defined(IFM_2500_SX)
  673. #ifdef IFM_2500_SX
  674. case(IFM_2500_SX):
  675. #endif
  676. return 2500;
  677. #endif // any 2.5GBit stuff...
  678. // We don't know what it is
  679. default:
  680. return 0;
  681. }
  682. break;
  683. #ifdef IFM_TOKEN
  684. case IFM_TOKEN:
  685. switch(IFM_SUBTYPE(ifm_active)) {
  686. case IFM_TOK_STP4: // Shielded twisted pair 4m - DB9
  687. case IFM_TOK_UTP4: // Unshielded twisted pair 4m - RJ45
  688. return 4;
  689. case IFM_TOK_STP16: // Shielded twisted pair 16m - DB9
  690. case IFM_TOK_UTP16: // Unshielded twisted pair 16m - RJ45
  691. return 16;
  692. #if defined(IFM_TOK_STP100) || defined(IFM_TOK_UTP100)
  693. #ifdef IFM_TOK_STP100
  694. case IFM_TOK_STP100: // Shielded twisted pair 100m - DB9
  695. #endif
  696. #ifdef IFM_TOK_UTP100
  697. case IFM_TOK_UTP100: // Unshielded twisted pair 100m - RJ45
  698. #endif
  699. return 100;
  700. #endif
  701. // We don't know what it is
  702. default:
  703. return 0;
  704. }
  705. break;
  706. #endif
  707. #ifdef IFM_FDDI
  708. case IFM_FDDI:
  709. switch(IFM_SUBTYPE(ifm_active)) {
  710. // We don't know what it is
  711. default:
  712. return 0;
  713. }
  714. break;
  715. #endif
  716. case IFM_IEEE80211:
  717. switch(IFM_SUBTYPE(ifm_active)) {
  718. case IFM_IEEE80211_FH1: // Frequency Hopping 1Mbps
  719. case IFM_IEEE80211_DS1: // Direct Sequence 1Mbps
  720. return 1;
  721. case IFM_IEEE80211_FH2: // Frequency Hopping 2Mbps
  722. case IFM_IEEE80211_DS2: // Direct Sequence 2Mbps
  723. return 2;
  724. case IFM_IEEE80211_DS5: // Direct Sequence 5Mbps
  725. return 5;
  726. case IFM_IEEE80211_DS11: // Direct Sequence 11Mbps
  727. return 11;
  728. case IFM_IEEE80211_DS22: // Direct Sequence 22Mbps
  729. return 22;
  730. // We don't know what it is
  731. default:
  732. return 0;
  733. }
  734. break;
  735. default:
  736. return 0;
  737. }
  738. }
  739. /*
  740. * Return stats about a particular network interface.
  741. * References:
  742. * http://www.i-scream.org/libstatgrab/
  743. */
  744. static PyObject *
  745. psutil_net_if_duplex_speed(PyObject *self, PyObject *args) {
  746. char *nic_name;
  747. int sock = -1;
  748. int ret;
  749. int duplex;
  750. int speed;
  751. struct ifreq ifr;
  752. struct ifmediareq ifmed;
  753. if (! PyArg_ParseTuple(args, "s", &nic_name))
  754. return NULL;
  755. sock = socket(AF_INET, SOCK_DGRAM, 0);
  756. if (sock == -1)
  757. return PyErr_SetFromErrno(PyExc_OSError);
  758. PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name));
  759. // speed / duplex
  760. memset(&ifmed, 0, sizeof(struct ifmediareq));
  761. strlcpy(ifmed.ifm_name, nic_name, sizeof(ifmed.ifm_name));
  762. ret = ioctl(sock, SIOCGIFMEDIA, (caddr_t)&ifmed);
  763. if (ret == -1) {
  764. speed = 0;
  765. duplex = 0;
  766. }
  767. else {
  768. speed = psutil_get_nic_speed(ifmed.ifm_active);
  769. if ((ifmed.ifm_active | IFM_FDX) == ifmed.ifm_active)
  770. duplex = 2;
  771. else if ((ifmed.ifm_active | IFM_HDX) == ifmed.ifm_active)
  772. duplex = 1;
  773. else
  774. duplex = 0;
  775. }
  776. close(sock);
  777. return Py_BuildValue("[ii]", duplex, speed);
  778. }
  779. #endif // net_if_stats() macOS/BSD implementation
  780. #ifdef __cplusplus
  781. extern "C" {
  782. #endif
  783. /*
  784. * define the psutil C module methods and initialize the module.
  785. */
  786. static PyMethodDef mod_methods[] = {
  787. {"getpagesize", psutil_getpagesize_pywrapper, METH_VARARGS},
  788. {"getpriority", psutil_posix_getpriority, METH_VARARGS},
  789. {"net_if_addrs", psutil_net_if_addrs, METH_VARARGS},
  790. {"net_if_flags", psutil_net_if_flags, METH_VARARGS},
  791. {"net_if_is_running", psutil_net_if_is_running, METH_VARARGS},
  792. {"net_if_mtu", psutil_net_if_mtu, METH_VARARGS},
  793. {"setpriority", psutil_posix_setpriority, METH_VARARGS},
  794. #if defined(PSUTIL_BSD) || defined(PSUTIL_OSX)
  795. {"net_if_duplex_speed", psutil_net_if_duplex_speed, METH_VARARGS},
  796. #endif
  797. {NULL, NULL, 0, NULL}
  798. };
  799. #if PY_MAJOR_VERSION >= 3
  800. #define INITERR return NULL
  801. static struct PyModuleDef moduledef = {
  802. PyModuleDef_HEAD_INIT,
  803. "_psutil_posix",
  804. NULL,
  805. -1,
  806. mod_methods,
  807. NULL,
  808. NULL,
  809. NULL,
  810. NULL
  811. };
  812. PyObject *PyInit__psutil_posix(void)
  813. #else /* PY_MAJOR_VERSION */
  814. #define INITERR return
  815. void init_psutil_posix(void)
  816. #endif /* PY_MAJOR_VERSION */
  817. {
  818. #if PY_MAJOR_VERSION >= 3
  819. PyObject *mod = PyModule_Create(&moduledef);
  820. #else
  821. PyObject *mod = Py_InitModule("_psutil_posix", mod_methods);
  822. #endif
  823. if (mod == NULL)
  824. INITERR;
  825. #ifdef Py_GIL_DISABLED
  826. PyUnstable_Module_SetGIL(mod, Py_MOD_GIL_NOT_USED);
  827. #endif
  828. #if defined(PSUTIL_BSD) || \
  829. defined(PSUTIL_OSX) || \
  830. defined(PSUTIL_SUNOS) || \
  831. defined(PSUTIL_AIX)
  832. if (PyModule_AddIntConstant(mod, "AF_LINK", AF_LINK)) INITERR;
  833. #endif
  834. #if defined(PSUTIL_LINUX) || defined(PSUTIL_FREEBSD)
  835. PyObject *v;
  836. #ifdef RLIMIT_AS
  837. if (PyModule_AddIntConstant(mod, "RLIMIT_AS", RLIMIT_AS)) INITERR;
  838. #endif
  839. #ifdef RLIMIT_CORE
  840. if (PyModule_AddIntConstant(mod, "RLIMIT_CORE", RLIMIT_CORE)) INITERR;
  841. #endif
  842. #ifdef RLIMIT_CPU
  843. if (PyModule_AddIntConstant(mod, "RLIMIT_CPU", RLIMIT_CPU)) INITERR;
  844. #endif
  845. #ifdef RLIMIT_DATA
  846. if (PyModule_AddIntConstant(mod, "RLIMIT_DATA", RLIMIT_DATA)) INITERR;
  847. #endif
  848. #ifdef RLIMIT_FSIZE
  849. if (PyModule_AddIntConstant(mod, "RLIMIT_FSIZE", RLIMIT_FSIZE)) INITERR;
  850. #endif
  851. #ifdef RLIMIT_MEMLOCK
  852. if (PyModule_AddIntConstant(mod, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK)) INITERR;
  853. #endif
  854. #ifdef RLIMIT_NOFILE
  855. if (PyModule_AddIntConstant(mod, "RLIMIT_NOFILE", RLIMIT_NOFILE)) INITERR;
  856. #endif
  857. #ifdef RLIMIT_NPROC
  858. if (PyModule_AddIntConstant(mod, "RLIMIT_NPROC", RLIMIT_NPROC)) INITERR;
  859. #endif
  860. #ifdef RLIMIT_RSS
  861. if (PyModule_AddIntConstant(mod, "RLIMIT_RSS", RLIMIT_RSS)) INITERR;
  862. #endif
  863. #ifdef RLIMIT_STACK
  864. if (PyModule_AddIntConstant(mod, "RLIMIT_STACK", RLIMIT_STACK)) INITERR;
  865. #endif
  866. // Linux specific
  867. #ifdef RLIMIT_LOCKS
  868. if (PyModule_AddIntConstant(mod, "RLIMIT_LOCKS", RLIMIT_LOCKS)) INITERR;
  869. #endif
  870. #ifdef RLIMIT_MSGQUEUE
  871. if (PyModule_AddIntConstant(mod, "RLIMIT_MSGQUEUE", RLIMIT_MSGQUEUE)) INITERR;
  872. #endif
  873. #ifdef RLIMIT_NICE
  874. if (PyModule_AddIntConstant(mod, "RLIMIT_NICE", RLIMIT_NICE)) INITERR;
  875. #endif
  876. #ifdef RLIMIT_RTPRIO
  877. if (PyModule_AddIntConstant(mod, "RLIMIT_RTPRIO", RLIMIT_RTPRIO)) INITERR;
  878. #endif
  879. #ifdef RLIMIT_RTTIME
  880. if (PyModule_AddIntConstant(mod, "RLIMIT_RTTIME", RLIMIT_RTTIME)) INITERR;
  881. #endif
  882. #ifdef RLIMIT_SIGPENDING
  883. if (PyModule_AddIntConstant(mod, "RLIMIT_SIGPENDING", RLIMIT_SIGPENDING)) INITERR;
  884. #endif
  885. // Free specific
  886. #ifdef RLIMIT_SWAP
  887. if (PyModule_AddIntConstant(mod, "RLIMIT_SWAP", RLIMIT_SWAP)) INITERR;
  888. #endif
  889. #ifdef RLIMIT_SBSIZE
  890. if (PyModule_AddIntConstant(mod, "RLIMIT_SBSIZE", RLIMIT_SBSIZE)) INITERR;
  891. #endif
  892. #ifdef RLIMIT_NPTS
  893. if (PyModule_AddIntConstant(mod, "RLIMIT_NPTS", RLIMIT_NPTS)) INITERR;
  894. #endif
  895. #if defined(HAVE_LONG_LONG)
  896. if (sizeof(RLIM_INFINITY) > sizeof(long)) {
  897. v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY);
  898. } else
  899. #endif
  900. {
  901. v = PyLong_FromLong((long) RLIM_INFINITY);
  902. }
  903. if (v) {
  904. PyModule_AddObject(mod, "RLIM_INFINITY", v);
  905. }
  906. #endif // defined(PSUTIL_LINUX) || defined(PSUTIL_FREEBSD)
  907. if (mod == NULL)
  908. INITERR;
  909. #if PY_MAJOR_VERSION >= 3
  910. return mod;
  911. #endif
  912. }
  913. #ifdef __cplusplus
  914. }
  915. #endif