Debian Codegraph @

psutil/arch/sunos/net.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 <Python.h>
8 #include <inet/mib2.h>
9 #include <kstat.h>
10 #include <netinet/in.h>
11 #include <stdio.h>
12 #include <stropts.h>
13 #include <sys/fcntl.h>
14 #include <sys/types.h>
15 #include <sys/socket.h>
16 #include <sys/sockio.h>
17 #include <netinet/in.h>
18 #include <netinet/in.h>
19 #include <arpa/inet.h>
20 #include <sys/stropts.h>
21 #include <sys/tihdr.h>
22 #include <net/if.h>
23 #include <fcntl.h>
24
25 #include "../../arch/all/init.h"
26
27
28 PyObject *
29 psutil_net_io_counters(PyObject *self, PyObject *args) {
30 kstat_ctl_t *kc = NULL;
31 kstat_t *ksp;
32 kstat_named_t *rbytes, *wbytes, *rpkts, *wpkts, *ierrs, *oerrs;
33 int ret;
34 int sock = -1;
35 struct lifreq ifr;
36
37 PyObject *py_retdict = PyDict_New();
38 PyObject *py_ifc_info = NULL;
39
40 if (py_retdict == NULL)
41 return NULL;
42 kc = kstat_open();
43 if (kc == NULL)
44 goto error;
45
46 sock = socket(AF_INET, SOCK_DGRAM, 0);
47 if (sock == -1) {
48 PyErr_SetFromErrno(PyExc_OSError);
49 goto error;
50 }
51
52 ksp = kc->kc_chain;
53 while (ksp != NULL) {
54 if (ksp->ks_type != KSTAT_TYPE_NAMED)
55 goto next;
56 if (strcmp(ksp->ks_class, "net") != 0)
57 goto next;
58 // skip 'lo' (localhost) because it doesn't have the statistics we need
59 // and it makes kstat_data_lookup() fail
60 if (strcmp(ksp->ks_module, "lo") == 0)
61 goto next;
62
63 // check if this is a network interface by sending a ioctl
64 PSUTIL_STRNCPY(ifr.lifr_name, ksp->ks_name, sizeof(ifr.lifr_name));
65 ret = ioctl(sock, SIOCGLIFFLAGS, &ifr);
66 if (ret == -1)
67 goto next;
68
69 if (kstat_read(kc, ksp, NULL) == -1) {
70 errno = 0;
71 goto next;
72 }
73
74 rbytes = (kstat_named_t *)kstat_data_lookup(ksp, "rbytes");
75 wbytes = (kstat_named_t *)kstat_data_lookup(ksp, "obytes");
76 rpkts = (kstat_named_t *)kstat_data_lookup(ksp, "ipackets");
77 wpkts = (kstat_named_t *)kstat_data_lookup(ksp, "opackets");
78 ierrs = (kstat_named_t *)kstat_data_lookup(ksp, "ierrors");
79 oerrs = (kstat_named_t *)kstat_data_lookup(ksp, "oerrors");
80
81 if ((rbytes == NULL) || (wbytes == NULL) || (rpkts == NULL) ||
82 (wpkts == NULL) || (ierrs == NULL) || (oerrs == NULL))
83 {
84 PyErr_SetString(PyExc_RuntimeError, "kstat_data_lookup() failed");
85 goto error;
86 }
87
88 if (rbytes->data_type == KSTAT_DATA_UINT64)
89 {
90 py_ifc_info = Py_BuildValue("(KKKKIIii)",
91 wbytes->value.ui64,
92 rbytes->value.ui64,
93 wpkts->value.ui64,
94 rpkts->value.ui64,
95 ierrs->value.ui32,
96 oerrs->value.ui32,
97 0, // dropin not supported
98 0 // dropout not supported
99 );
100 }
101 else
102 {
103 py_ifc_info = Py_BuildValue("(IIIIIIii)",
104 wbytes->value.ui32,
105 rbytes->value.ui32,
106 wpkts->value.ui32,
107 rpkts->value.ui32,
108 ierrs->value.ui32,
109 oerrs->value.ui32,
110 0, // dropin not supported
111 0 // dropout not supported
112 );
113 }
114 if (!py_ifc_info)
115 goto error;
116 if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_ifc_info))
117 goto error;
118 Py_CLEAR(py_ifc_info);
119 goto next;
120
121 next:
122 ksp = ksp->ks_next;
123 }
124
125 kstat_close(kc);
126 close(sock);
127 return py_retdict;
128
129 error:
130 Py_XDECREF(py_ifc_info);
131 Py_DECREF(py_retdict);
132 if (kc != NULL)
133 kstat_close(kc);
134 if (sock != -1) {
135 close(sock);
136 }
137 return NULL;
138 }
139
140
141 // Return stats about a particular network interface. Refs:
142 // * https://github.com/dpaleino/wicd/blob/master/wicd/backends/be-ioctl.py
143 // * http://www.i-scream.org/libstatgrab/
144 PyObject*
145 psutil_net_if_stats(PyObject* self, PyObject* args) {
146 kstat_ctl_t *kc = NULL;
147 kstat_t *ksp;
148 kstat_named_t *knp;
149 int ret;
150 int sock = -1;
151 int duplex;
152 int speed;
153
154 PyObject *py_retdict = PyDict_New();
155 PyObject *py_ifc_info = NULL;
156 PyObject *py_is_up = NULL;
157
158 if (py_retdict == NULL)
159 return NULL;
160 kc = kstat_open();
161 if (kc == NULL)
162 goto error;
163 sock = socket(AF_INET, SOCK_DGRAM, 0);
164 if (sock == -1) {
165 PyErr_SetFromErrno(PyExc_OSError);
166 goto error;
167 }
168
169 for (ksp = kc->kc_chain; ksp; ksp = ksp->ks_next) {
170 if (strcmp(ksp->ks_class, "net") == 0) {
171 struct lifreq ifr;
172
173 kstat_read(kc, ksp, NULL);
174 if (ksp->ks_type != KSTAT_TYPE_NAMED)
175 continue;
176 if (strcmp(ksp->ks_class, "net") != 0)
177 continue;
178
179 PSUTIL_STRNCPY(ifr.lifr_name, ksp->ks_name, sizeof(ifr.lifr_name));
180 ret = ioctl(sock, SIOCGLIFFLAGS, &ifr);
181 if (ret == -1)
182 continue; // not a network interface
183
184 // is up?
185 if ((ifr.lifr_flags & IFF_UP) != 0) {
186 if ((knp = kstat_data_lookup(ksp, "link_up")) != NULL) {
187 if (knp->value.ui32 != 0u)
188 py_is_up = Py_True;
189 else
190 py_is_up = Py_False;
191 }
192 else {
193 py_is_up = Py_True;
194 }
195 }
196 else {
197 py_is_up = Py_False;
198 }
199 Py_INCREF(py_is_up);
200
201 // duplex
202 duplex = 0; // unknown
203 if ((knp = kstat_data_lookup(ksp, "link_duplex")) != NULL) {
204 if (knp->value.ui32 == 1)
205 duplex = 1; // half
206 else if (knp->value.ui32 == 2)
207 duplex = 2; // full
208 }
209
210 // speed
211 if ((knp = kstat_data_lookup(ksp, "ifspeed")) != NULL)
212 // expressed in bits per sec, we want mega bits per sec
213 speed = (int)knp->value.ui64 / 1000000;
214 else
215 speed = 0;
216
217 // mtu
218 ret = ioctl(sock, SIOCGLIFMTU, &ifr);
219 if (ret == -1)
220 goto error;
221
222 py_ifc_info = Py_BuildValue("(Oiii)", py_is_up, duplex, speed,
223 ifr.lifr_mtu);
224 if (!py_ifc_info)
225 goto error;
226 if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_ifc_info))
227 goto error;
228 Py_CLEAR(py_ifc_info);
229 }
230 }
231
232 close(sock);
233 kstat_close(kc);
234 return py_retdict;
235
236 error:
237 Py_XDECREF(py_is_up);
238 Py_XDECREF(py_ifc_info);
239 Py_DECREF(py_retdict);
240 if (sock != -1)
241 close(sock);
242 if (kc != NULL)
243 kstat_close(kc);
244 PyErr_SetFromErrno(PyExc_OSError);
245 return NULL;
246 }
247
248
249 /*
250 * Return TCP and UDP connections opened by process.
251 * UNIX sockets are excluded.
252 *
253 * Thanks to:
254 * https://github.com/DavidGriffith/finx/blob/master/
255 * nxsensor-3.5.0-1/src/sysdeps/solaris.c
256 * ...and:
257 * https://hg.java.net/hg/solaris~on-src/file/tip/usr/src/cmd/
258 * cmd-inet/usr.bin/netstat/netstat.c
259 */
260 PyObject *
261 psutil_net_connections(PyObject *self, PyObject *args) {
262 long pid;
263 int sd = 0;
264 mib2_tcpConnEntry_t tp;
265 mib2_udpEntry_t ude;
266 #if defined(AF_INET6)
267 mib2_tcp6ConnEntry_t tp6;
268 mib2_udp6Entry_t ude6;
269 #endif
270 char buf[512];
271 int i, flags, getcode, num_ent, state, ret;
272 char lip[INET6_ADDRSTRLEN], rip[INET6_ADDRSTRLEN];
273 int lport, rport;
274 int processed_pid;
275 int databuf_init = 0;
276 struct strbuf ctlbuf, databuf;
277 struct T_optmgmt_req tor = {0};
278 struct T_optmgmt_ack toa = {0};
279 struct T_error_ack tea = {0};
280 struct opthdr mibhdr = {0};
281
282 PyObject *py_retlist = PyList_New(0);
283 PyObject *py_tuple = NULL;
284 PyObject *py_laddr = NULL;
285 PyObject *py_raddr = NULL;
286
287 if (py_retlist == NULL)
288 return NULL;
289 if (! PyArg_ParseTuple(args, "l", &pid))
290 goto error;
291
292 sd = open("/dev/arp", O_RDWR);
293 if (sd == -1) {
294 PyErr_SetFromErrnoWithFilename(PyExc_OSError, "/dev/arp");
295 goto error;
296 }
297
298 ret = ioctl(sd, I_PUSH, "tcp");
299 if (ret == -1) {
300 PyErr_SetFromErrno(PyExc_OSError);
301 goto error;
302 }
303 ret = ioctl(sd, I_PUSH, "udp");
304 if (ret == -1) {
305 PyErr_SetFromErrno(PyExc_OSError);
306 goto error;
307 }
308 //
309 // OK, this mess is basically copied and pasted from nxsensor project
310 // which copied and pasted it from netstat source code, mibget()
311 // function. Also see:
312 // http://stackoverflow.com/questions/8723598/
313 tor.PRIM_type = T_SVR4_OPTMGMT_REQ;
314 tor.OPT_offset = sizeof (struct T_optmgmt_req);
315 tor.OPT_length = sizeof (struct opthdr);
316 tor.MGMT_flags = T_CURRENT;
317 mibhdr.level = MIB2_IP;
318 mibhdr.name = 0;
319
320 #ifdef NEW_MIB_COMPLIANT
321 mibhdr.len = 1;
322 #else
323 mibhdr.len = 0;
324 #endif
325 memcpy(buf, &tor, sizeof tor);
326 memcpy(buf + tor.OPT_offset, &mibhdr, sizeof mibhdr);
327
328 ctlbuf.buf = buf;
329 ctlbuf.len = tor.OPT_offset + tor.OPT_length;
330 flags = 0; // request to be sent in non-priority
331
332 if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) {
333 PyErr_SetFromErrno(PyExc_OSError);
334 goto error;
335 }
336
337 ctlbuf.maxlen = sizeof (buf);
338 for (;;) {
339 flags = 0;
340 getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags);
341 memcpy(&toa, buf, sizeof toa);
342 memcpy(&tea, buf, sizeof tea);
343
344 if (getcode != MOREDATA ||
345 ctlbuf.len < (int)sizeof (struct T_optmgmt_ack) ||
346 toa.PRIM_type != T_OPTMGMT_ACK ||
347 toa.MGMT_flags != T_SUCCESS)
348 {
349 break;
350 }
351 if (ctlbuf.len >= (int)sizeof (struct T_error_ack) &&
352 tea.PRIM_type == T_ERROR_ACK)
353 {
354 PyErr_SetString(PyExc_RuntimeError, "ERROR_ACK");
355 goto error;
356 }
357 if (getcode == 0 &&
358 ctlbuf.len >= (int)sizeof (struct T_optmgmt_ack) &&
359 toa.PRIM_type == T_OPTMGMT_ACK &&
360 toa.MGMT_flags == T_SUCCESS)
361 {
362 PyErr_SetString(PyExc_RuntimeError, "ERROR_T_OPTMGMT_ACK");
363 goto error;
364 }
365
366 memset(&mibhdr, 0x0, sizeof(mibhdr));
367 memcpy(&mibhdr, buf + toa.OPT_offset, toa.OPT_length);
368
369 databuf.maxlen = mibhdr.len;
370 databuf.len = 0;
371 databuf.buf = (char *)malloc((int)mibhdr.len);
372 if (!databuf.buf) {
373 PyErr_NoMemory();
374 goto error;
375 }
376 databuf_init = 1;
377
378 flags = 0;
379 getcode = getmsg(sd, (struct strbuf *)0, &databuf, &flags);
380 if (getcode < 0) {
381 PyErr_SetFromErrno(PyExc_OSError);
382 goto error;
383 }
384
385 // TCPv4
386 if (mibhdr.level == MIB2_TCP && mibhdr.name == MIB2_TCP_13) {
387 num_ent = mibhdr.len / sizeof(mib2_tcpConnEntry_t);
388 for (i = 0; i < num_ent; i++) {
389 memcpy(&tp, databuf.buf + i * sizeof tp, sizeof tp);
390 #ifdef NEW_MIB_COMPLIANT
391 processed_pid = tp.tcpConnCreationProcess;
392 #else
393 processed_pid = 0;
394 #endif
395 if (pid != -1 && processed_pid != pid)
396 continue;
397 // construct local/remote addresses
398 inet_ntop(AF_INET, &tp.tcpConnLocalAddress, lip, sizeof(lip));
399 inet_ntop(AF_INET, &tp.tcpConnRemAddress, rip, sizeof(rip));
400 lport = tp.tcpConnLocalPort;
401 rport = tp.tcpConnRemPort;
402
403 // construct python tuple/list
404 py_laddr = Py_BuildValue("(si)", lip, lport);
405 if (!py_laddr)
406 goto error;
407 if (rport != 0)
408 py_raddr = Py_BuildValue("(si)", rip, rport);
409 else {
410 py_raddr = Py_BuildValue("()");
411 }
412 if (!py_raddr)
413 goto error;
414 state = tp.tcpConnEntryInfo.ce_state;
415
416 // add item
417 py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_STREAM,
418 py_laddr, py_raddr, state,
419 processed_pid);
420 if (!py_tuple)
421 goto error;
422 if (PyList_Append(py_retlist, py_tuple))
423 goto error;
424 Py_CLEAR(py_tuple);
425 }
426 }
427 #if defined(AF_INET6)
428 // TCPv6
429 else if (mibhdr.level == MIB2_TCP6 && mibhdr.name == MIB2_TCP6_CONN)
430 {
431 num_ent = mibhdr.len / sizeof(mib2_tcp6ConnEntry_t);
432
433 for (i = 0; i < num_ent; i++) {
434 memcpy(&tp6, databuf.buf + i * sizeof tp6, sizeof tp6);
435 #ifdef NEW_MIB_COMPLIANT
436 processed_pid = tp6.tcp6ConnCreationProcess;
437 #else
438 processed_pid = 0;
439 #endif
440 if (pid != -1 && processed_pid != pid)
441 continue;
442 // construct local/remote addresses
443 inet_ntop(AF_INET6, &tp6.tcp6ConnLocalAddress, lip, sizeof(lip));
444 inet_ntop(AF_INET6, &tp6.tcp6ConnRemAddress, rip, sizeof(rip));
445 lport = tp6.tcp6ConnLocalPort;
446 rport = tp6.tcp6ConnRemPort;
447
448 // construct python tuple/list
449 py_laddr = Py_BuildValue("(si)", lip, lport);
450 if (!py_laddr)
451 goto error;
452 if (rport != 0)
453 py_raddr = Py_BuildValue("(si)", rip, rport);
454 else
455 py_raddr = Py_BuildValue("()");
456 if (!py_raddr)
457 goto error;
458 state = tp6.tcp6ConnEntryInfo.ce_state;
459
460 // add item
461 py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_STREAM,
462 py_laddr, py_raddr, state, processed_pid);
463 if (!py_tuple)
464 goto error;
465 if (PyList_Append(py_retlist, py_tuple))
466 goto error;
467 Py_CLEAR(py_tuple);
468 }
469 }
470 #endif
471 // UDPv4
472 else if (mibhdr.level == MIB2_UDP && mibhdr.name == MIB2_UDP_ENTRY) {
473 num_ent = mibhdr.len / sizeof(mib2_udpEntry_t);
474 assert(num_ent * sizeof(mib2_udpEntry_t) == mibhdr.len);
475 for (i = 0; i < num_ent; i++) {
476 memcpy(&ude, databuf.buf + i * sizeof ude, sizeof ude);
477 #ifdef NEW_MIB_COMPLIANT
478 processed_pid = ude.udpCreationProcess;
479 #else
480 processed_pid = 0;
481 #endif
482 if (pid != -1 && processed_pid != pid)
483 continue;
484 // XXX Very ugly hack! It seems we get here only the first
485 // time we bump into a UDPv4 socket. PID is a very high
486 // number (clearly impossible) and the address does not
487 // belong to any valid interface. Not sure what else
488 // to do other than skipping.
489 if (processed_pid > 131072)
490 continue;
491 inet_ntop(AF_INET, &ude.udpLocalAddress, lip, sizeof(lip));
492 lport = ude.udpLocalPort;
493 py_laddr = Py_BuildValue("(si)", lip, lport);
494 if (!py_laddr)
495 goto error;
496 py_raddr = Py_BuildValue("()");
497 if (!py_raddr)
498 goto error;
499 py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_DGRAM,
500 py_laddr, py_raddr, PSUTIL_CONN_NONE,
501 processed_pid);
502 if (!py_tuple)
503 goto error;
504 if (PyList_Append(py_retlist, py_tuple))
505 goto error;
506 Py_CLEAR(py_tuple);
507 }
508 }
509 #if defined(AF_INET6)
510 // UDPv6
511 else if (mibhdr.level == MIB2_UDP6 ||
512 mibhdr.level == MIB2_UDP6_ENTRY)
513 {
514 num_ent = mibhdr.len / sizeof(mib2_udp6Entry_t);
515 for (i = 0; i < num_ent; i++) {
516 memcpy(&ude6, databuf.buf + i * sizeof ude6, sizeof ude6);
517 #ifdef NEW_MIB_COMPLIANT
518 processed_pid = ude6.udp6CreationProcess;
519 #else
520 processed_pid = 0;
521 #endif
522 if (pid != -1 && processed_pid != pid)
523 continue;
524 inet_ntop(AF_INET6, &ude6.udp6LocalAddress, lip, sizeof(lip));
525 lport = ude6.udp6LocalPort;
526 py_laddr = Py_BuildValue("(si)", lip, lport);
527 if (!py_laddr)
528 goto error;
529 py_raddr = Py_BuildValue("()");
530 if (!py_raddr)
531 goto error;
532 py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_DGRAM,
533 py_laddr, py_raddr, PSUTIL_CONN_NONE,
534 processed_pid);
535 if (!py_tuple)
536 goto error;
537 if (PyList_Append(py_retlist, py_tuple))
538 goto error;
539 Py_CLEAR(py_tuple);
540 }
541 }
542 #endif
543 free(databuf.buf);
544 }
545
546 close(sd);
547 return py_retlist;
548
549 error:
550 Py_XDECREF(py_tuple);
551 Py_XDECREF(py_laddr);
552 Py_XDECREF(py_raddr);
553 Py_DECREF(py_retlist);
554 if (databuf_init == 1)
555 free(databuf.buf);
556 if (sd != 0)
557 close(sd);
558 return NULL;
559 }