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
|
/*
* Copyright (c)2013-2021 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
/**
* @file
*
* ZeroTier Socket API (Python)
*
* This code derives from the Python standard library:
*
* Lib/socket.py
* Modules/socketmodule.c
* Modules/fcntlmodule.c
* Modules/clinic/fcntlmodule.c.h
* Modules/clinic/selectmodule.c.h
*
* Copyright and license text can be found in pypi packaging directory.
*
*/
#include "ZeroTierSockets.h"
#ifdef ZTS_ENABLE_PYTHON
#include "Python.h"
#include "PythonSockets.h"
#include "lwip/inet.h"
#include "lwip/sockets.h"
#include "structmember.h" // PyMemberDef
#include <string.h>
#include <sys/time.h>
PyObject* set_error(void)
{
return NULL; // PyErr_SetFromErrno(zts_errno);
}
static int zts_py_tuple_to_sockaddr(int family, PyObject* addr_obj, struct zts_sockaddr* dst_addr, int* addrlen)
{
if (family == AF_INET) {
struct zts_sockaddr_in* addr;
char* host_str;
int result, port;
if (! PyTuple_Check(addr_obj)) {
return ZTS_ERR_ARG;
}
if (! PyArg_ParseTuple(addr_obj, "eti:zts_py_tuple_to_sockaddr", "idna", &host_str, &port)) {
return ZTS_ERR_ARG;
}
addr = (struct zts_sockaddr_in*)dst_addr;
result = zts_inet_pton(ZTS_AF_INET, host_str, &(addr->sin_addr.s_addr));
PyMem_Free(host_str);
if (port < 0 || port > 0xFFFF) {
return ZTS_ERR_ARG;
}
if (result < 0) {
return ZTS_ERR_ARG;
}
addr->sin_family = AF_INET;
addr->sin_port = lwip_htons((short)port);
*addrlen = sizeof *addr;
return ZTS_ERR_OK;
}
if (family == AF_INET6) {
// TODO
}
return ZTS_ERR_ARG;
}
PyObject* zts_py_accept(int fd)
{
struct zts_sockaddr_in addrbuf = { 0 };
socklen_t addrlen = sizeof(addrbuf);
int err = ZTS_ERR_OK;
Py_BEGIN_ALLOW_THREADS;
err = zts_bsd_accept(fd, (struct zts_sockaddr*)&addrbuf, &addrlen);
Py_END_ALLOW_THREADS;
char ipstr[ZTS_INET_ADDRSTRLEN] = { 0 };
zts_inet_ntop(ZTS_AF_INET, &(addrbuf.sin_addr), ipstr, ZTS_INET_ADDRSTRLEN);
PyObject* t;
t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyLong_FromLong(err)); // New file descriptor
PyTuple_SetItem(t, 1, PyUnicode_FromString(ipstr));
PyTuple_SetItem(t, 2, PyLong_FromLong(lwip_ntohs(addrbuf.sin_port)));
Py_INCREF(t);
return t;
}
int zts_py_bind(int fd, int family, int type, PyObject* addr_obj)
{
struct zts_sockaddr_storage addrbuf;
int addrlen;
int err;
if (zts_py_tuple_to_sockaddr(family, addr_obj, (struct zts_sockaddr*)&addrbuf, &addrlen) != ZTS_ERR_OK) {
return ZTS_ERR_ARG;
}
Py_BEGIN_ALLOW_THREADS;
err = zts_bsd_bind(fd, (struct zts_sockaddr*)&addrbuf, addrlen);
Py_END_ALLOW_THREADS;
return err;
}
int zts_py_connect(int fd, int family, int type, PyObject* addr_obj)
{
struct zts_sockaddr_storage addrbuf;
int addrlen;
int err;
if (zts_py_tuple_to_sockaddr(family, addr_obj, (struct zts_sockaddr*)&addrbuf, &addrlen) != ZTS_ERR_OK) {
return ZTS_ERR_ARG;
}
Py_BEGIN_ALLOW_THREADS;
err = zts_bsd_connect(fd, (struct zts_sockaddr*)&addrbuf, addrlen);
Py_END_ALLOW_THREADS;
return err;
}
PyObject* zts_py_recv(int fd, int len, int flags)
{
PyObject *t, *buf;
int bytes_read;
buf = PyBytes_FromStringAndSize((char*)0, len);
if (buf == NULL) {
return NULL;
}
Py_BEGIN_ALLOW_THREADS;
bytes_read = zts_bsd_recv(fd, PyBytes_AS_STRING(buf), len, flags);
Py_END_ALLOW_THREADS;
t = PyTuple_New(2);
PyTuple_SetItem(t, 0, PyLong_FromLong(bytes_read));
if (bytes_read < 0) {
Py_DECREF(buf);
Py_INCREF(Py_None);
PyTuple_SetItem(t, 1, Py_None);
Py_INCREF(t);
return t;
}
if (bytes_read != len) {
_PyBytes_Resize(&buf, bytes_read);
}
PyTuple_SetItem(t, 1, buf);
Py_INCREF(t);
return t;
}
int zts_py_send(int fd, PyObject* buf, int flags)
{
Py_buffer output;
int bytes_sent;
if (PyObject_GetBuffer(buf, &output, PyBUF_SIMPLE) != 0) {
return 0;
}
Py_BEGIN_ALLOW_THREADS;
bytes_sent = zts_bsd_send(fd, output.buf, output.len, flags);
Py_END_ALLOW_THREADS;
PyBuffer_Release(&output);
return bytes_sent;
}
int zts_py_close(int fd)
{
int err;
Py_BEGIN_ALLOW_THREADS;
err = zts_bsd_close(fd);
Py_END_ALLOW_THREADS;
return err;
}
PyObject* zts_py_addr_get_str(uint64_t net_id, int family)
{
char addr_str[ZTS_IP_MAX_STR_LEN] = { 0 };
if (zts_addr_get_str(net_id, family, addr_str, ZTS_IP_MAX_STR_LEN) < 0) {
PyErr_SetString(PyExc_Warning, "No address of the given type has been assigned by the network");
return NULL;
}
PyObject* t = PyUnicode_FromString(addr_str);
return t;
}
/* list of Python objects and their file descriptor */
typedef struct {
PyObject* obj; /* owned reference */
int fd;
int sentinel; /* -1 == sentinel */
} pylist;
void reap_obj(pylist fd2obj[ZTS_FD_SETSIZE + 1])
{
unsigned int i;
for (i = 0; i < (unsigned int)ZTS_FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
Py_CLEAR(fd2obj[i].obj);
}
fd2obj[0].sentinel = -1;
}
/* returns NULL and sets the Python exception if an error occurred */
PyObject* set2list(zts_fd_set* set, pylist fd2obj[ZTS_FD_SETSIZE + 1])
{
int i, j, count = 0;
PyObject *list, *o;
int fd;
for (j = 0; fd2obj[j].sentinel >= 0; j++) {
if (ZTS_FD_ISSET(fd2obj[j].fd, set)) {
count++;
}
}
list = PyList_New(count);
if (! list) {
return NULL;
}
i = 0;
for (j = 0; fd2obj[j].sentinel >= 0; j++) {
fd = fd2obj[j].fd;
if (ZTS_FD_ISSET(fd, set)) {
o = fd2obj[j].obj;
fd2obj[j].obj = NULL;
/* transfer ownership */
if (PyList_SetItem(list, i, o) < 0) {
goto finally;
}
i++;
}
}
return list;
finally:
Py_DECREF(list);
return NULL;
}
/* returns -1 and sets the Python exception if an error occurred, otherwise
returns a number >= 0
*/
int seq2set(PyObject* seq, zts_fd_set* set, pylist fd2obj[FD_SETSIZE + 1])
{
int max = -1;
unsigned int index = 0;
Py_ssize_t i;
PyObject* fast_seq = NULL;
PyObject* o = NULL;
fd2obj[0].obj = (PyObject*)0; /* set list to zero size */
ZTS_FD_ZERO(set);
fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");
if (! fast_seq) {
return -1;
}
for (i = 0; i < PySequence_Fast_GET_SIZE(fast_seq); i++) {
int v;
/* any intervening fileno() calls could decr this refcnt */
if (! (o = PySequence_Fast_GET_ITEM(fast_seq, i))) {
goto finally;
}
Py_INCREF(o);
v = PyObject_AsFileDescriptor(o);
if (v == -1) {
goto finally;
}
#if defined(_MSC_VER)
max = 0; /* not used for Win32 */
#else /* !_MSC_VER */
if (! _PyIsSelectable_fd(v)) {
PyErr_SetString(PyExc_ValueError, "filedescriptor out of range in select()");
goto finally;
}
if (v > max) {
max = v;
}
#endif /* _MSC_VER */
ZTS_FD_SET(v, set);
/* add object and its file descriptor to the list */
if (index >= (unsigned int)FD_SETSIZE) {
PyErr_SetString(PyExc_ValueError, "too many file descriptors in select()");
goto finally;
}
fd2obj[index].obj = o;
fd2obj[index].fd = v;
fd2obj[index].sentinel = 0;
fd2obj[++index].sentinel = -1;
}
Py_DECREF(fast_seq);
return max + 1;
finally:
Py_XDECREF(o);
Py_DECREF(fast_seq);
return -1;
}
PyObject* zts_py_select(PyObject* module, PyObject* rlist, PyObject* wlist, PyObject* xlist, PyObject* timeout_obj)
{
pylist rfd2obj[FD_SETSIZE + 1];
pylist wfd2obj[FD_SETSIZE + 1];
pylist efd2obj[FD_SETSIZE + 1];
PyObject* ret = NULL;
zts_fd_set ifdset, ofdset, efdset;
struct timeval tv, *tvp;
int imax, omax, emax, max;
int n;
_PyTime_t timeout, deadline = 0;
if (timeout_obj == Py_None) {
tvp = (struct timeval*)NULL;
}
else {
if (_PyTime_FromSecondsObject(&timeout, timeout_obj, _PyTime_ROUND_UP) < 0) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_SetString(PyExc_TypeError, "timeout must be a float or None");
}
return NULL;
}
if (_PyTime_AsTimeval(timeout, &tv, _PyTime_ROUND_UP) == -1) {
return NULL;
}
if (tv.tv_sec < 0) {
PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
return NULL;
}
tvp = &tv;
}
/* Convert iterables to zts_fd_sets, and get maximum fd number
* propagates the Python exception set in seq2set()
*/
rfd2obj[0].sentinel = -1;
wfd2obj[0].sentinel = -1;
efd2obj[0].sentinel = -1;
if ((imax = seq2set(rlist, &ifdset, rfd2obj)) < 0) {
goto finally;
}
if ((omax = seq2set(wlist, &ofdset, wfd2obj)) < 0) {
goto finally;
}
if ((emax = seq2set(xlist, &efdset, efd2obj)) < 0) {
goto finally;
}
max = imax;
if (omax > max) {
max = omax;
}
if (emax > max) {
max = emax;
}
if (tvp) {
deadline = _PyTime_GetMonotonicClock() + timeout;
}
do {
Py_BEGIN_ALLOW_THREADS;
errno = 0;
// struct zts_timeval zts_tvp;
// zts_tvp.tv_sec = tvp.tv_sec;
// zts_tvp.tv_sec = tvp.tv_sec;
n = zts_bsd_select(max, &ifdset, &ofdset, &efdset, (struct zts_timeval*)tvp);
Py_END_ALLOW_THREADS;
if (errno != EINTR) {
break;
}
/* select() was interrupted by a signal */
if (PyErr_CheckSignals()) {
goto finally;
}
if (tvp) {
timeout = deadline - _PyTime_GetMonotonicClock();
if (timeout < 0) {
/* bpo-35310: lists were unmodified -- clear them explicitly */
ZTS_FD_ZERO(&ifdset);
ZTS_FD_ZERO(&ofdset);
ZTS_FD_ZERO(&efdset);
n = 0;
break;
}
_PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
/* retry select() with the recomputed timeout */
}
} while (1);
#ifdef MS_WINDOWS
if (n == SOCKET_ERROR) {
PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
}
#else
if (n < 0) {
PyErr_SetFromErrno(PyExc_OSError);
}
#endif
else {
/* any of these three calls can raise an exception. it's more
convenient to test for this after all three calls... but
is that acceptable?
*/
rlist = set2list(&ifdset, rfd2obj);
wlist = set2list(&ofdset, wfd2obj);
xlist = set2list(&efdset, efd2obj);
if (PyErr_Occurred()) {
ret = NULL;
}
else {
ret = PyTuple_Pack(3, rlist, wlist, xlist);
}
Py_XDECREF(rlist);
Py_XDECREF(wlist);
Py_XDECREF(xlist);
}
finally:
reap_obj(rfd2obj);
reap_obj(wfd2obj);
reap_obj(efd2obj);
return ret;
}
int zts_py_setsockopt(int fd, PyObject* args)
{
int level;
int optname;
int res;
Py_buffer optval;
int flag;
unsigned int optlen;
PyObject* none;
// setsockopt(level, opt, flag)
if (PyArg_ParseTuple(args, "iii:setsockopt", &level, &optname, &flag)) {
res = zts_bsd_setsockopt(fd, level, optname, (char*)&flag, sizeof flag);
goto done;
}
PyErr_Clear();
// setsockopt(level, opt, None, flag)
if (PyArg_ParseTuple(args, "iiO!I:setsockopt", &level, &optname, Py_TYPE(Py_None), &none, &optlen)) {
assert(sizeof(socklen_t) >= sizeof(unsigned int));
res = zts_bsd_setsockopt(fd, level, optname, NULL, (socklen_t)optlen);
goto done;
}
PyErr_Clear();
// setsockopt(level, opt, buffer)
if (! PyArg_ParseTuple(args, "iiy*:setsockopt", &level, &optname, &optval)) {
return (int)NULL;
}
#ifdef MS_WINDOWS
if (optval.len > INT_MAX) {
PyBuffer_Release(&optval);
PyErr_Format(PyExc_OverflowError, "socket option is larger than %i bytes", INT_MAX);
return (int)NULL;
}
res = zts_bsd_setsockopt(fd, level, optname, optval.buf, (int)optval.len);
#else
res = zts_bsd_setsockopt(fd, level, optname, optval.buf, optval.len);
#endif
PyBuffer_Release(&optval);
done:
return res;
}
PyObject* zts_py_getsockopt(int fd, PyObject* args)
{
int level;
int optname;
int res;
PyObject* buf;
socklen_t buflen = 0;
int flag = 0;
socklen_t flagsize;
if (! PyArg_ParseTuple(args, "ii|i:getsockopt", &level, &optname, &buflen)) {
return NULL;
}
if (buflen == 0) {
flagsize = sizeof flag;
res = zts_bsd_getsockopt(fd, level, optname, (void*)&flag, &flagsize);
if (res < 0) {
return set_error();
}
return PyLong_FromLong(flag);
}
if (buflen <= 0 || buflen > 1024) {
PyErr_SetString(PyExc_OSError, "getsockopt buflen out of range");
return NULL;
}
buf = PyBytes_FromStringAndSize((char*)NULL, buflen);
if (buf == NULL) {
return NULL;
}
res = zts_bsd_getsockopt(fd, level, optname, (void*)PyBytes_AS_STRING(buf), &buflen);
if (res < 0) {
Py_DECREF(buf);
return set_error();
}
_PyBytes_Resize(&buf, buflen);
return buf;
}
PyObject* zts_py_fcntl(int fd, int code, PyObject* arg)
{
unsigned int int_arg = 0;
int ret;
if (arg != NULL) {
int parse_result;
PyErr_Clear();
parse_result = PyArg_Parse(
arg,
"I;fcntl requires a file or file descriptor,"
" an integer and optionally a third integer",
&int_arg);
if (! parse_result) {
return NULL;
}
}
do {
Py_BEGIN_ALLOW_THREADS;
ret = zts_bsd_fcntl(fd, code, (int)int_arg);
Py_END_ALLOW_THREADS;
} while (ret == -1 && zts_errno == ZTS_EINTR);
if (ret < 0) {
return set_error();
}
return PyLong_FromLong((long)ret);
}
PyObject* zts_py_ioctl(int fd, unsigned int code, PyObject* ob_arg, int mutate_arg)
{
#define IOCTL_BUFSZ 1024
int arg = 0;
int ret;
Py_buffer pstr;
char* str;
Py_ssize_t len;
char buf[IOCTL_BUFSZ + 1]; /* argument plus NUL byte */
if (ob_arg != NULL) {
if (PyArg_Parse(ob_arg, "w*:ioctl", &pstr)) {
char* arg;
str = (char*)pstr.buf;
len = pstr.len;
if (mutate_arg) {
if (len <= IOCTL_BUFSZ) {
memcpy(buf, str, len);
buf[len] = '\0';
arg = buf;
}
else {
arg = str;
}
}
else {
if (len > IOCTL_BUFSZ) {
PyBuffer_Release(&pstr);
PyErr_SetString(PyExc_ValueError, "ioctl string arg too long");
return NULL;
}
else {
memcpy(buf, str, len);
buf[len] = '\0';
arg = buf;
}
}
if (buf == arg) {
Py_BEGIN_ALLOW_THREADS;
/* think array.resize() */
ret = zts_bsd_ioctl(fd, code, arg);
Py_END_ALLOW_THREADS;
}
else {
ret = zts_bsd_ioctl(fd, code, arg);
}
if (mutate_arg && (len <= IOCTL_BUFSZ)) {
memcpy(str, buf, len);
}
PyBuffer_Release(&pstr); /* No further access to str below this point */
if (ret < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if (mutate_arg) {
return PyLong_FromLong(ret);
}
else {
return PyBytes_FromStringAndSize(buf, len);
}
}
PyErr_Clear();
if (PyArg_Parse(ob_arg, "s*:ioctl", &pstr)) {
str = (char*)pstr.buf;
len = pstr.len;
if (len > IOCTL_BUFSZ) {
PyBuffer_Release(&pstr);
PyErr_SetString(PyExc_ValueError, "ioctl string arg too long");
return NULL;
}
memcpy(buf, str, len);
buf[len] = '\0';
Py_BEGIN_ALLOW_THREADS;
ret = zts_bsd_ioctl(fd, code, buf);
Py_END_ALLOW_THREADS;
if (ret < 0) {
PyBuffer_Release(&pstr);
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
PyBuffer_Release(&pstr);
return PyBytes_FromStringAndSize(buf, len);
}
PyErr_Clear();
if (! PyArg_Parse(
ob_arg,
"i;ioctl requires a file or file descriptor,"
" an integer and optionally an integer or buffer argument",
&arg)) {
return NULL;
}
// Fall-through to outside the 'if' statement.
}
// TODO: Double check that &arg is correct
Py_BEGIN_ALLOW_THREADS;
ret = zts_bsd_ioctl(fd, code, &arg);
Py_END_ALLOW_THREADS;
if (ret < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return PyLong_FromLong((long)ret);
#undef IOCTL_BUFSZ
}
#endif // ZTS_ENABLE_PYTHON
|