summaryrefslogtreecommitdiffstats
path: root/python-ethtool/ethtool.c
blob: e37bcf151e712a557a8a2e4769f33f6a1dfdb121 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
/*
 * Copyright (C) 2008-2013 Red Hat Inc.
 *
 * Arnaldo Carvalho de Melo <acme@redhat.com>
 * David Sommerseth <davids@redhat.com>
 *
 * First bits from a Red Hat config tool by Harald Hoyer.
 *
 * This application is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; version 2.
 *
 * This application is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 */
#include <Python.h>

#include <errno.h>
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netlink/route/addr.h>

#include "etherinfo_struct.h"
#include "etherinfo_obj.h"
#include "etherinfo.h"

extern PyTypeObject ethtool_etherinfoType;

#ifndef IFF_DYNAMIC
#define IFF_DYNAMIC     0x8000          /* dialup device with changing addresses*/
#endif

typedef unsigned long long u64;
typedef __uint32_t u32;
typedef __uint16_t u16;
typedef __uint8_t u8;

#include "ethtool-copy.h"
#include <linux/sockios.h> /* for SIOCETHTOOL */

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))

#define _PATH_PROCNET_DEV "/proc/net/dev"

static PyObject *get_active_devices(PyObject *self __unused, PyObject *args __unused)
{
	PyObject *list;
	struct ifaddrs *ifaddr, *ifa;

	if (getifaddrs(&ifaddr) == -1) {
		PyErr_SetString(PyExc_OSError, strerror(errno));
		return NULL;
	}

	list = PyList_New(0);
	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		PyObject *str = PyString_FromString(ifa->ifa_name);
		/* names are not unique (listed for both ipv4 and ipv6) */
		if (!PySequence_Contains(list, str) && (ifa->ifa_flags & (IFF_UP))) {
			PyList_Append(list, str);
		}
	Py_DECREF(str);
	}

	freeifaddrs(ifaddr);

	return list;
}

static PyObject *get_devices(PyObject *self __unused, PyObject *args __unused)
{
	char buffer[256];
	char *ret;
	PyObject *list = PyList_New(0);
	FILE *fd = fopen(_PATH_PROCNET_DEV, "r");

	if (fd == NULL) {
		PyErr_SetString(PyExc_OSError, strerror(errno));
		return NULL;
	}
	/* skip over first two lines */
	ret = fgets(buffer, 256, fd);
	ret = fgets(buffer, 256, fd);
	if( !ret ) {
		PyErr_SetString(PyExc_OSError, strerror(errno));
		return NULL;
	}

	while (!feof(fd)) {
		PyObject *str;
		char *name = buffer;
		char *end = buffer;

		if (fgets(buffer, 256, fd) == NULL)
			break;
		/* find colon */
		while (*end && *end != ':')
			end++;
		*end = 0; /* terminate where colon was */
		while (*name == ' ')
			name++; /* skip over leading whitespace if any */

		str = PyString_FromString(name);
		PyList_Append(list, str);
		Py_DECREF(str);
	}
	fclose(fd);
	return list;
}

static PyObject *get_hwaddress(PyObject *self __unused, PyObject *args)
{
	struct ifreq ifr;
	int fd, err;
	const char *devname;
	char hwaddr[20];

	if (!PyArg_ParseTuple(args, "s", &devname))
		return NULL;

	/* Setup our request structure. */
	memset(&ifr, 0, sizeof(ifr));
	strncpy(&ifr.ifr_name[0], devname, IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;

	/* Open control socket. */
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		PyErr_SetString(PyExc_OSError, strerror(errno));
		return NULL;
	}

	/* Get current settings. */
	err = ioctl(fd, SIOCGIFHWADDR, &ifr);
	if (err < 0) {
		char buf[2048];
		int eno = errno;

		snprintf(buf, sizeof(buf), "[Errno %d] %s", eno, strerror(eno));
		PyErr_SetString(PyExc_IOError, buf);
		close(fd);
		return NULL;
	}

	close(fd);

	sprintf(hwaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
		(unsigned int)ifr.ifr_hwaddr.sa_data[0] % 256,
		(unsigned int)ifr.ifr_hwaddr.sa_data[1] % 256,
		(unsigned int)ifr.ifr_hwaddr.sa_data[2] % 256,
		(unsigned int)ifr.ifr_hwaddr.sa_data[3] % 256,
		(unsigned int)ifr.ifr_hwaddr.sa_data[4] % 256,
		(unsigned int)ifr.ifr_hwaddr.sa_data[5] % 256);

	return PyString_FromString(hwaddr);
}

static PyObject *get_ipaddress(PyObject *self __unused, PyObject *args)
{
	struct ifreq ifr;
	int fd, err;
	const char *devname;
	char ipaddr[20];

	if (!PyArg_ParseTuple(args, "s", &devname))
		return NULL;

	/* Setup our request structure. */
	memset(&ifr, 0, sizeof(ifr));
	strncpy(&ifr.ifr_name[0], devname, IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;

	/* Open control socket. */
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		PyErr_SetString(PyExc_OSError, strerror(errno));
		return NULL;
	}

	/* Get current settings. */
	err = ioctl(fd, SIOCGIFADDR, &ifr);
	if (err < 0) {
		char buf[2048];
		int eno = errno;
		snprintf(buf, sizeof(buf), "[Errno %d] %s", eno, strerror(eno));
		PyErr_SetString(PyExc_IOError, buf);
		close(fd);
		return NULL;
	}

	close(fd);

	sprintf(ipaddr, "%u.%u.%u.%u",
		(unsigned int)ifr.ifr_addr.sa_data[2] % 256,
		(unsigned int)ifr.ifr_addr.sa_data[3] % 256,
		(unsigned int)ifr.ifr_addr.sa_data[4] % 256,
		(unsigned int)ifr.ifr_addr.sa_data[5] % 256);

	return PyString_FromString(ipaddr);
}


/**
 * Retrieves the current information about all interfaces.  All interfaces will be
 * returned as a list of objects per interface.
 *
 * @param self Not used
 * @param args Python arguments
 *
 * @return Python list of objects on success, otherwise NULL.
 */
static PyObject *get_interfaces_info(PyObject *self __unused, PyObject *args) {
	PyObject *devlist = NULL, *ethinf_py = NULL;
	PyObject *inargs = NULL;
	char **fetch_devs = NULL;
	int i = 0, fetch_devs_len = 0;

	if (!PyArg_ParseTuple(args, "|O", &inargs)) {
		PyErr_SetString(PyExc_LookupError,
				"Argument must be either a string, list or a tuple");
		return NULL;
	}

	/* Parse input arguments if we got them */
	if( inargs != NULL ) {
		if( PyString_Check(inargs) ) { /* Input argument is just a string */
			fetch_devs_len = 1;
			fetch_devs = calloc(1, sizeof(char *));
			fetch_devs[0] = PyString_AsString(inargs);
		} else if( PyTuple_Check(inargs) ) { /* Input argument is a tuple list with devices */
			int j = 0;

			fetch_devs_len = PyTuple_Size(inargs);
			fetch_devs = calloc(fetch_devs_len+1, sizeof(char *));
			for( i = 0; i < fetch_devs_len; i++ ) {
				PyObject *elmt = PyTuple_GetItem(inargs, i);
				if( elmt && PyString_Check(elmt) ) {
					fetch_devs[j++] = PyString_AsString(elmt);
				}
			}
			fetch_devs_len = j;
		} else if( PyList_Check(inargs) ) { /* Input argument is a list with devices */
			int j = 0;

			fetch_devs_len = PyList_Size(inargs);
			fetch_devs = calloc(fetch_devs_len+1, sizeof(char *));
			for( i = 0; i < fetch_devs_len; i++ ) {
				PyObject *elmt = PyList_GetItem(inargs, i);
				if( elmt && PyString_Check(elmt) ) {
					fetch_devs[j++] = PyString_AsString(elmt);
				}
			}
			fetch_devs_len = j;
		} else {
			PyErr_SetString(PyExc_LookupError,
					"Argument must be either a string, list or a tuple");
			return NULL;
		}
	}

	devlist = PyList_New(0);
	for( i = 0; i < fetch_devs_len; i++ ) {
		struct etherinfo *ethinfo = NULL;

		/* Allocate memory for data structures for each interface */
		ethinfo = calloc(1, sizeof(struct etherinfo));
		if( !ethinfo ) {
			PyErr_SetString(PyExc_OSError, strerror(errno));
			free(fetch_devs);
			return NULL;
		}

		/* Store the device name and a reference to the NETLINK connection for
		 * objects to use when quering for device info
		 */
		ethinfo->device = PyString_FromString(fetch_devs[i]);
		ethinfo->index = -1;

		/* Instantiate a new etherinfo object with the device information */
		ethinf_py = PyCObject_FromVoidPtr(ethinfo, NULL);
		if( ethinf_py ) {
			/* Prepare the argument list for the object constructor */
			PyObject *args = PyTuple_New(1);
			PyTuple_SetItem(args, 0, ethinf_py);

			/* Create the object */
			PyObject *dev = PyObject_CallObject((PyObject *)&ethtool_etherinfoType, args);
			if( dev ) {
				PyList_Append(devlist, dev);
				Py_DECREF(dev);
			}
			Py_DECREF(args);
		}
	}
	free(fetch_devs);

	return devlist;
}


static PyObject *get_flags (PyObject *self __unused, PyObject *args)
{
	struct ifreq ifr;
	const char *devname;
	int fd, err;

	if (!PyArg_ParseTuple(args, "s", &devname))
		return NULL;

	/* Setup our request structure. */
	memset(&ifr, 0, sizeof(ifr));
	strncpy(&ifr.ifr_name[0], devname, IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;

	/* Open control socket. */
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		PyErr_SetString(PyExc_OSError, strerror(errno));
		return NULL;
	}
	err = ioctl(fd, SIOCGIFFLAGS, &ifr);
	if(err < 0) {
		char buf[2048];
		int eno = errno;
		snprintf(buf, sizeof(buf), "[Errno %d] %s", eno, strerror(eno));
		PyErr_SetString(PyExc_IOError, buf);
		close(fd);
		return NULL;
	}

	close(fd);

	return Py_BuildValue("h", ifr.ifr_flags);


}
static PyObject *get_netmask (PyObject *self __unused, PyObject *args)
{
	struct ifreq ifr;
	int fd, err;
	const char *devname;
	char netmask[20];

	if (!PyArg_ParseTuple(args, "s", &devname))
		return NULL;

	/* Setup our request structure. */
	memset(&ifr, 0, sizeof(ifr));
	strncpy(&ifr.ifr_name[0], devname, IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;

	/* Open control socket. */
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		PyErr_SetString(PyExc_OSError, strerror(errno));
		return NULL;
	}

	/* Get current settings. */
	err = ioctl(fd, SIOCGIFNETMASK, &ifr);
	if (err < 0) {
		char buf[2048];
		int eno = errno;
		snprintf(buf, sizeof(buf), "[Errno %d] %s", eno, strerror(eno));
		PyErr_SetString(PyExc_IOError, buf);
		close(fd);
		return NULL;
	}

	close(fd);

	sprintf(netmask, "%u.%u.%u.%u",
		(unsigned int)ifr.ifr_netmask.sa_data[2] % 256,
		(unsigned int)ifr.ifr_netmask.sa_data[3] % 256,
		(unsigned int)ifr.ifr_netmask.sa_data[4] % 256,
		(unsigned int)ifr.ifr_netmask.sa_data[5] % 256);

	return PyString_FromString(netmask);
}

static PyObject *get_broadcast(PyObject *self __unused, PyObject *args)
{
	struct ifreq ifr;
	int fd, err;
	const char *devname;
	char broadcast[20];

	if (!PyArg_ParseTuple(args, "s", &devname))
		return NULL;

	/* Setup our request structure. */
	memset(&ifr, 0, sizeof(ifr));
	strncpy(&ifr.ifr_name[0], devname, IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;

	/* Open control socket. */
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		PyErr_SetString(PyExc_OSError, strerror(errno));
		return NULL;
	}

	/* Get current settings. */
	err = ioctl(fd, SIOCGIFBRDADDR, &ifr);
	if (err < 0) {
		char buf[2048];
		int eno = errno;
		snprintf(buf, sizeof(buf), "[Errno %d] %s", eno, strerror(eno));
		PyErr_SetString(PyExc_IOError, buf);
		close(fd);
		return NULL;
	}

	close(fd);

	sprintf(broadcast, "%u.%u.%u.%u",
		(unsigned int)ifr.ifr_broadaddr.sa_data[2] % 256,
		(unsigned int)ifr.ifr_broadaddr.sa_data[3] % 256,
		(unsigned int)ifr.ifr_broadaddr.sa_data[4] % 256,
		(unsigned int)ifr.ifr_broadaddr.sa_data[5] % 256);

	return PyString_FromString(broadcast);
}

static PyObject *get_module(PyObject *self __unused, PyObject *args)
{
	struct ethtool_cmd ecmd;
	struct ifreq ifr;
	int fd, err;
	char buf[2048];
	const char *devname;

	if (!PyArg_ParseTuple(args, "s", &devname))
		return NULL;

	/* Setup our control structures. */
	memset(&ecmd, 0, sizeof(ecmd));
	memset(&ifr, 0, sizeof(ifr));
	strncpy(&ifr.ifr_name[0], devname, IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;
	ifr.ifr_data = (caddr_t) &buf;
	ecmd.cmd = ETHTOOL_GDRVINFO;
	memcpy(&buf, &ecmd, sizeof(ecmd));

	/* Open control socket. */
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		PyErr_SetString(PyExc_OSError, strerror(errno));
		return NULL;
	}

	/* Get current settings. */
	err = ioctl(fd, SIOCETHTOOL, &ifr);

	if (err < 0) {  /* failed? */
		int eno = errno;
		FILE *file;
		int found = 0;
		char driver[101], dev[101];
		close(fd);

		/* Before bailing, maybe it is a PCMCIA/PC Card? */
		file = fopen("/var/lib/pcmcia/stab", "r");
		if (file == NULL) {
			sprintf(buf, "[Errno %d] %s", eno, strerror(eno));
			PyErr_SetString(PyExc_IOError, buf);
			return NULL;
		}

		while (!feof(file)) {
			if (fgets(buf, 2048, file) == NULL)
				break;
			buf[2047] = '\0';
			if (strncmp(buf, "Socket", 6) != 0) {
				if (sscanf(buf, "%*d\t%*s\t%100s\t%*d\t%100s\n", driver, dev) > 0) {
					driver[99] = '\0';
					dev[99] = '\0';
					if (strcmp(devname, dev) == 0) {
						found = 1;
						break;
					}
				}
			}
		}
		fclose(file);
		if (!found) {
			sprintf(buf, "[Errno %d] %s", eno, strerror(eno));
			PyErr_SetString(PyExc_IOError, buf);
			return NULL;
		} else
			return PyString_FromString(driver);
	}

	close(fd);
	return PyString_FromString(((struct ethtool_drvinfo *)buf)->driver);
}

static PyObject *get_businfo(PyObject *self __unused, PyObject *args)
{
	struct ethtool_cmd ecmd;
	struct ifreq ifr;
	int fd, err;
	char buf[1024];
	const char *devname;

	if (!PyArg_ParseTuple(args, "s", &devname))
		return NULL;

	/* Setup our control structures. */
	memset(&ecmd, 0, sizeof(ecmd));
	memset(&ifr, 0, sizeof(ifr));
	strncpy(&ifr.ifr_name[0], devname, IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;
	ifr.ifr_data = (caddr_t) &buf;
	ecmd.cmd = ETHTOOL_GDRVINFO;
	memcpy(&buf, &ecmd, sizeof(ecmd));

	/* Open control socket. */
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	if (fd < 0) {
		PyErr_SetString(PyExc_OSError, strerror(errno));
		return NULL;
	}

	/* Get current settings. */
	err = ioctl(fd, SIOCETHTOOL, &ifr);

	if (err < 0) {  /* failed? */
		int eno = errno;
		close(fd);

		sprintf(buf, "[Errno %d] %s", eno, strerror(eno));
		PyErr_SetString(PyExc_IOError, buf);
		return NULL;
	}

	close(fd);
	return PyString_FromString(((struct ethtool_drvinfo *)buf)->bus_info);
}

static int send_command(int cmd, const char *devname, void *value)
{
	/* Setup our request structure. */
	int fd, err;
	struct ifreq ifr;
	struct ethtool_value *eval = value;

	memset(&ifr, 0, sizeof(ifr));
	strncpy(&ifr.ifr_name[0], devname, IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;
	ifr.ifr_data = (caddr_t)eval;
	eval->cmd = cmd;

	/* Open control socket. */
	fd = socket(AF_INET, SOCK_DGRAM, 0), err;
	if (fd < 0) {
		PyErr_SetString(PyExc_OSError, strerror(errno));
		return -1;
	}

	/* Get current settings. */
	err = ioctl(fd, SIOCETHTOOL, &ifr);
	if (err < 0) {
		char buf[2048];
		sprintf(buf, "[Errno %d] %s", errno, strerror(errno));
		PyErr_SetString(PyExc_IOError, buf);
	}

	close(fd);
	return err;
}

static int get_dev_value(int cmd, PyObject *args, void *value)
{
	const char *devname;
	int err = -1;

	if (PyArg_ParseTuple(args, "s", &devname))
		err = send_command(cmd, devname, value);

	return err;
}

static int get_dev_int_value(int cmd, PyObject *args, int *value)
{
	struct ethtool_value eval;
	int rc = get_dev_value(cmd, args, &eval);

	if (rc == 0)
		*value = *(int *)&eval.data;

	return rc;
}

static int dev_set_int_value(int cmd, PyObject *args)
{
	struct ethtool_value eval;
	const char *devname;

	if (!PyArg_ParseTuple(args, "si", &devname, &eval.data))
		return -1;

	return send_command(cmd, devname, &eval);
}

static PyObject *get_tso(PyObject *self __unused, PyObject *args)
{
	int value = 0;

	if (get_dev_int_value(ETHTOOL_GTSO, args, &value) < 0)
		return NULL;

	return Py_BuildValue("b", value);
}

static PyObject *set_tso(PyObject *self __unused, PyObject *args)
{
	if (dev_set_int_value(ETHTOOL_STSO, args) < 0)
		return NULL;

	Py_INCREF(Py_None);
	return Py_None;
}

static PyObject *get_ufo(PyObject *self __unused, PyObject *args)
{
	int value = 0;

	if (get_dev_int_value(ETHTOOL_GUFO, args, &value) < 0)
		return NULL;

	return Py_BuildValue("b", value);
}

static PyObject *get_gso(PyObject *self __unused, PyObject *args)
{
	int value = 0;

	if (get_dev_int_value(ETHTOOL_GGSO, args, &value) < 0)
		return NULL;

	return Py_BuildValue("b", value);
}

static PyObject *get_sg(PyObject *self __unused, PyObject *args)
{
	int value = 0;

	if (get_dev_int_value(ETHTOOL_GSG, args, &value) < 0)
		return NULL;

	return Py_BuildValue("b", value);
}

struct struct_desc {
	char	       *name;
	unsigned short offset;
	unsigned short size;
};

#define member_desc(type, member_name) { \
	.name = #member_name, \
	.offset = offsetof(type, member_name), \
	.size = sizeof(((type *)0)->member_name), }

struct struct_desc ethtool_coalesce_desc[] = {
	member_desc(struct ethtool_coalesce, rx_coalesce_usecs),
	member_desc(struct ethtool_coalesce, rx_max_coalesced_frames),
	member_desc(struct ethtool_coalesce, rx_coalesce_usecs_irq),
	member_desc(struct ethtool_coalesce, rx_max_coalesced_frames_irq),
	member_desc(struct ethtool_coalesce, tx_coalesce_usecs),
	member_desc(struct ethtool_coalesce, tx_max_coalesced_frames),
	member_desc(struct ethtool_coalesce, tx_coalesce_usecs_irq),
	member_desc(struct ethtool_coalesce, tx_max_coalesced_frames_irq),
	member_desc(struct ethtool_coalesce, stats_block_coalesce_usecs),
	member_desc(struct ethtool_coalesce, use_adaptive_rx_coalesce),
	member_desc(struct ethtool_coalesce, use_adaptive_tx_coalesce),
	member_desc(struct ethtool_coalesce, pkt_rate_low),
	member_desc(struct ethtool_coalesce, rx_coalesce_usecs_low),
	member_desc(struct ethtool_coalesce, rx_max_coalesced_frames_low),
	member_desc(struct ethtool_coalesce, tx_coalesce_usecs_low),
	member_desc(struct ethtool_coalesce, tx_max_coalesced_frames_low),
	member_desc(struct ethtool_coalesce, pkt_rate_high),
	member_desc(struct ethtool_coalesce, rx_coalesce_usecs_high),
	member_desc(struct ethtool_coalesce, rx_max_coalesced_frames_high),
	member_desc(struct ethtool_coalesce, tx_coalesce_usecs_high),
	member_desc(struct ethtool_coalesce, tx_max_coalesced_frames_high),
	member_desc(struct ethtool_coalesce, rate_sample_interval),
};

static PyObject *__struct_desc_create_dict(struct struct_desc *table,
					   int nr_entries, void *values)
{
	int i;
	PyObject *dict = PyDict_New();

	if (dict == NULL)
		goto out;

	for (i = 0; i < nr_entries; ++i) {
		struct struct_desc *d = &table[i];
		PyObject *objval = NULL;
		void *val = values + d->offset;

		switch (d->size) {
		case sizeof(uint32_t):
			objval = PyInt_FromLong(*(uint32_t *)val);
			break;
		}

		if (objval == NULL)
			goto free_dict;

		if (PyDict_SetItemString(dict, d->name, objval) != 0) {
			Py_DECREF(objval);
			goto free_dict;
		}
			
		Py_DECREF(objval);
	}
out:
	return dict;
free_dict:
	goto out;
	dict = NULL;
}

#define struct_desc_create_dict(table, values) \
	__struct_desc_create_dict(table, ARRAY_SIZE(table), values)

static int __struct_desc_from_dict(struct struct_desc *table,
				   int nr_entries, void *to, PyObject *dict)
{
	char buf[2048];
	int i;

	for (i = 0; i < nr_entries; ++i) {
		struct struct_desc *d = &table[i];
		void *val = to + d->offset;
		PyObject *obj;

		switch (d->size) {
		case sizeof(uint32_t):
			obj = PyDict_GetItemString(dict, d->name);
			if (obj == NULL) {
				snprintf(buf, sizeof(buf),
					"Missing dict entry for field %s",
					d->name);
				PyErr_SetString(PyExc_IOError, buf);
				return -1;
			}
			*(uint32_t *)val = PyInt_AsLong(obj);
			break;
		default:
			snprintf(buf, sizeof(buf),
				 "Invalid type size %d for field %s",
				 d->size, d->name);
			PyErr_SetString(PyExc_IOError, buf);
			return -1;
		}
	}

	return 0;
}

#define struct_desc_from_dict(table, to, dict) \
	__struct_desc_from_dict(table, ARRAY_SIZE(table), to, dict)

static PyObject *get_coalesce(PyObject *self __unused, PyObject *args)
{
	struct ethtool_coalesce coal;

	if (get_dev_value(ETHTOOL_GCOALESCE, args, &coal) < 0)
		return NULL;

	return struct_desc_create_dict(ethtool_coalesce_desc, &coal);
}

static PyObject *set_coalesce(PyObject *self __unused, PyObject *args)
{
	struct ethtool_coalesce coal;
	const char *devname;
	PyObject *dict;

	if (!PyArg_ParseTuple(args, "sO", &devname, &dict))
		return NULL;

	if (struct_desc_from_dict(ethtool_coalesce_desc, &coal, dict) != 0)
		return NULL;

	if (send_command(ETHTOOL_SCOALESCE, devname, &coal))
		return NULL;

	Py_INCREF(Py_None);
	return Py_None;
}

struct struct_desc ethtool_ringparam_desc[] = {
	member_desc(struct ethtool_ringparam, rx_max_pending),
	member_desc(struct ethtool_ringparam, rx_mini_max_pending),
	member_desc(struct ethtool_ringparam, rx_jumbo_max_pending),
	member_desc(struct ethtool_ringparam, tx_max_pending),
	member_desc(struct ethtool_ringparam, rx_pending),
	member_desc(struct ethtool_ringparam, rx_mini_pending),
	member_desc(struct ethtool_ringparam, rx_jumbo_pending),
	member_desc(struct ethtool_ringparam, tx_pending),
};

static PyObject *get_ringparam(PyObject *self __unused, PyObject *args)
{
	struct ethtool_ringparam ring;

	if (get_dev_value(ETHTOOL_GRINGPARAM, args, &ring) < 0)
		return NULL;

	return struct_desc_create_dict(ethtool_ringparam_desc, &ring);
}

static PyObject *set_ringparam(PyObject *self __unused, PyObject *args)
{
	struct ethtool_ringparam ring;
	const char *devname;
	PyObject *dict;

	if (!PyArg_ParseTuple(args, "sO", &devname, &dict))
		return NULL;

	if (struct_desc_from_dict(ethtool_ringparam_desc, &ring, dict) != 0)
		return NULL;

	if (send_command(ETHTOOL_SRINGPARAM, devname, &ring))
		return NULL;

	Py_INCREF(Py_None);
	return Py_None;
}

static struct PyMethodDef PyEthModuleMethods[] = {
	{
		.ml_name = "get_module",
		.ml_meth = (PyCFunction)get_module,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_businfo",
		.ml_meth = (PyCFunction)get_businfo,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_hwaddr",
		.ml_meth = (PyCFunction)get_hwaddress,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_ipaddr",
		.ml_meth = (PyCFunction)get_ipaddress,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_interfaces_info",
		.ml_meth = (PyCFunction)get_interfaces_info,
		.ml_flags = METH_VARARGS,
		.ml_doc = "Accepts a string, list or tupples of interface names. "
		"Returns a list of ethtool.etherinfo objets with device information."
	},
	{
		.ml_name = "get_netmask",
		.ml_meth = (PyCFunction)get_netmask,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_broadcast",
		.ml_meth = (PyCFunction)get_broadcast,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_coalesce",
		.ml_meth = (PyCFunction)get_coalesce,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "set_coalesce",
		.ml_meth = (PyCFunction)set_coalesce,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_devices",
		.ml_meth = (PyCFunction)get_devices,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_active_devices",
		.ml_meth = (PyCFunction)get_active_devices,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_ringparam",
		.ml_meth = (PyCFunction)get_ringparam,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "set_ringparam",
		.ml_meth = (PyCFunction)set_ringparam,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_tso",
		.ml_meth = (PyCFunction)get_tso,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "set_tso",
		.ml_meth = (PyCFunction)set_tso,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_ufo",
		.ml_meth = (PyCFunction)get_ufo,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_gso",
		.ml_meth = (PyCFunction)get_gso,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_sg",
		.ml_meth = (PyCFunction)get_sg,
		.ml_flags = METH_VARARGS,
	},
	{
		.ml_name = "get_flags",
		.ml_meth = (PyCFunction)get_flags,
		.ml_flags = METH_VARARGS,
	},
	{	.ml_name = NULL, },
};


PyMODINIT_FUNC initethtool(void)
{
	PyObject *m;
	m = Py_InitModule3("ethtool", PyEthModuleMethods, "Python ethtool module");

	// Prepare the ethtool.etherinfo class
	if (PyType_Ready(&ethtool_etherinfoType) < 0)
		return;
	Py_INCREF(&ethtool_etherinfoType);
	PyModule_AddObject(m, "etherinfo", (PyObject *)&ethtool_etherinfoType);

	// Prepare the ethtool IPv6 and IPv4 address types
	if (PyType_Ready(&ethtool_netlink_ip_address_Type))
		return;

	// Setup constants
	PyModule_AddIntConstant(m, "IFF_UP", IFF_UP);			/* Interface is up. */
	PyModule_AddIntConstant(m, "IFF_BROADCAST", IFF_BROADCAST);	/* Broadcast address valid. */
	PyModule_AddIntConstant(m, "IFF_DEBUG", IFF_DEBUG);		/* Turn on debugging. */
	PyModule_AddIntConstant(m, "IFF_LOOPBACK", IFF_LOOPBACK);	/* Is a loopback net */
	PyModule_AddIntConstant(m, "IFF_POINTOPOINT", IFF_POINTOPOINT); /* Is a point-to-point link */
	PyModule_AddIntConstant(m, "IFF_NOTRAILERS", IFF_NOTRAILERS);	/* Avoid use of trailers */
	PyModule_AddIntConstant(m, "IFF_RUNNING", IFF_RUNNING);		/* Resources allocated */
	PyModule_AddIntConstant(m, "IFF_NOARP", IFF_NOARP);		/* No address resolution protocol. */
	PyModule_AddIntConstant(m, "IFF_PROMISC", IFF_PROMISC);		/* Receive all packets. */
	PyModule_AddIntConstant(m, "IFF_ALLMULTI", IFF_ALLMULTI);	/* Receive all multicast packets. */
	PyModule_AddIntConstant(m, "IFF_MASTER", IFF_MASTER);		/* Master of a load balancer. */
	PyModule_AddIntConstant(m, "IFF_SLAVE", IFF_SLAVE);		/* Slave of a load balancer. */
	PyModule_AddIntConstant(m, "IFF_MULTICAST", IFF_MULTICAST);	/* Supports multicast. */
	PyModule_AddIntConstant(m, "IFF_PORTSEL", IFF_PORTSEL);		/* Can set media type. */
	PyModule_AddIntConstant(m, "IFF_AUTOMEDIA", IFF_AUTOMEDIA);	/* Auto media select active. */
	PyModule_AddIntConstant(m, "IFF_DYNAMIC", IFF_DYNAMIC);		/* Dialup device with changing addresses.  */
	PyModule_AddIntConstant(m, "AF_INET", AF_INET);                 /* IPv4 interface */
	PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);               /* IPv6 interface */
	PyModule_AddStringConstant(m, "version", "python-ethtool v" VERSION);
}