1 | /* |
2 | * This file is part of the MicroPython project, http://micropython.org/ |
3 | * |
4 | * The MIT License (MIT) |
5 | * |
6 | * Copyright (c) 2014-2018 Paul Sokolovsky |
7 | * Copyright (c) 2014-2019 Damien P. George |
8 | * |
9 | * Permission is hereby granted, free of charge, to any person obtaining a copy |
10 | * of this software and associated documentation files (the "Software"), to deal |
11 | * in the Software without restriction, including without limitation the rights |
12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
13 | * copies of the Software, and to permit persons to whom the Software is |
14 | * furnished to do so, subject to the following conditions: |
15 | * |
16 | * The above copyright notice and this permission notice shall be included in |
17 | * all copies or substantial portions of the Software. |
18 | * |
19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
25 | * THE SOFTWARE. |
26 | */ |
27 | |
28 | #include <stdio.h> |
29 | #include <assert.h> |
30 | #include <string.h> |
31 | #include <unistd.h> |
32 | #include <fcntl.h> |
33 | #include <sys/stat.h> |
34 | #include <sys/types.h> |
35 | #include <sys/socket.h> |
36 | #include <netinet/in.h> |
37 | #include <arpa/inet.h> |
38 | #include <netdb.h> |
39 | #include <errno.h> |
40 | #include <math.h> |
41 | |
42 | #include "py/objtuple.h" |
43 | #include "py/objstr.h" |
44 | #include "py/runtime.h" |
45 | #include "py/stream.h" |
46 | #include "py/builtin.h" |
47 | #include "py/mphal.h" |
48 | #include "py/mpthread.h" |
49 | |
50 | /* |
51 | The idea of this module is to implement reasonable minimum of |
52 | socket-related functions to write typical clients and servers. |
53 | The module named "usocket" on purpose, to allow to make |
54 | Python-level module more (or fully) compatible with CPython |
55 | "socket", e.g.: |
56 | ---- socket.py ---- |
57 | from usocket import * |
58 | from socket_more_funcs import * |
59 | from socket_more_funcs2 import * |
60 | ------------------- |
61 | I.e. this module should stay lean, and more functions (if needed) |
62 | should be add to separate modules (C or Python level). |
63 | */ |
64 | |
65 | // This type must "inherit" from mp_obj_fdfile_t, i.e. matching subset of |
66 | // fields should have the same layout. |
67 | typedef struct _mp_obj_socket_t { |
68 | mp_obj_base_t base; |
69 | int fd; |
70 | bool blocking; |
71 | } mp_obj_socket_t; |
72 | |
73 | const mp_obj_type_t mp_type_socket; |
74 | |
75 | // Helper functions |
76 | static inline mp_obj_t mp_obj_from_sockaddr(const struct sockaddr *addr, socklen_t len) { |
77 | return mp_obj_new_bytes((const byte *)addr, len); |
78 | } |
79 | |
80 | STATIC mp_obj_socket_t *socket_new(int fd) { |
81 | mp_obj_socket_t *o = m_new_obj(mp_obj_socket_t); |
82 | o->base.type = &mp_type_socket; |
83 | o->fd = fd; |
84 | o->blocking = true; |
85 | return o; |
86 | } |
87 | |
88 | |
89 | STATIC void socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { |
90 | (void)kind; |
91 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); |
92 | mp_printf(print, "<_socket %d>" , self->fd); |
93 | } |
94 | |
95 | STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) { |
96 | mp_obj_socket_t *o = MP_OBJ_TO_PTR(o_in); |
97 | ssize_t r; |
98 | MP_HAL_RETRY_SYSCALL(r, read(o->fd, buf, size), { |
99 | // On blocking socket, we get EAGAIN in case SO_RCVTIMEO/SO_SNDTIMEO |
100 | // timed out, and need to convert that to ETIMEDOUT. |
101 | if (err == EAGAIN && o->blocking) { |
102 | err = MP_ETIMEDOUT; |
103 | } |
104 | |
105 | *errcode = err; |
106 | return MP_STREAM_ERROR; |
107 | }); |
108 | return (mp_uint_t)r; |
109 | } |
110 | |
111 | STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) { |
112 | mp_obj_socket_t *o = MP_OBJ_TO_PTR(o_in); |
113 | ssize_t r; |
114 | MP_HAL_RETRY_SYSCALL(r, write(o->fd, buf, size), { |
115 | // On blocking socket, we get EAGAIN in case SO_RCVTIMEO/SO_SNDTIMEO |
116 | // timed out, and need to convert that to ETIMEDOUT. |
117 | if (err == EAGAIN && o->blocking) { |
118 | err = MP_ETIMEDOUT; |
119 | } |
120 | |
121 | *errcode = err; |
122 | return MP_STREAM_ERROR; |
123 | }); |
124 | return (mp_uint_t)r; |
125 | } |
126 | |
127 | STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { |
128 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(o_in); |
129 | (void)arg; |
130 | switch (request) { |
131 | case MP_STREAM_CLOSE: |
132 | // There's a POSIX drama regarding return value of close in general, |
133 | // and EINTR error in particular. See e.g. |
134 | // http://lwn.net/Articles/576478/ |
135 | // http://austingroupbugs.net/view.php?id=529 |
136 | // The rationale MicroPython follows is that close() just releases |
137 | // file descriptor. If you're interested to catch I/O errors before |
138 | // closing fd, fsync() it. |
139 | MP_THREAD_GIL_EXIT(); |
140 | close(self->fd); |
141 | MP_THREAD_GIL_ENTER(); |
142 | return 0; |
143 | |
144 | case MP_STREAM_GET_FILENO: |
145 | return self->fd; |
146 | |
147 | default: |
148 | *errcode = MP_EINVAL; |
149 | return MP_STREAM_ERROR; |
150 | } |
151 | } |
152 | |
153 | STATIC mp_obj_t socket_fileno(mp_obj_t self_in) { |
154 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); |
155 | return MP_OBJ_NEW_SMALL_INT(self->fd); |
156 | } |
157 | STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_fileno_obj, socket_fileno); |
158 | |
159 | STATIC mp_obj_t socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { |
160 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); |
161 | mp_buffer_info_t bufinfo; |
162 | mp_get_buffer_raise(addr_in, &bufinfo, MP_BUFFER_READ); |
163 | |
164 | // special case of PEP 475 to retry only if blocking so we can't use |
165 | // MP_HAL_RETRY_SYSCALL() here |
166 | for (;;) { |
167 | MP_THREAD_GIL_EXIT(); |
168 | int r = connect(self->fd, (const struct sockaddr *)bufinfo.buf, bufinfo.len); |
169 | MP_THREAD_GIL_ENTER(); |
170 | if (r == -1) { |
171 | int err = errno; |
172 | if (self->blocking) { |
173 | if (err == EINTR) { |
174 | mp_handle_pending(true); |
175 | continue; |
176 | } |
177 | // EINPROGRESS on a blocking socket means the operation timed out |
178 | if (err == EINPROGRESS) { |
179 | err = MP_ETIMEDOUT; |
180 | } |
181 | } |
182 | mp_raise_OSError(err); |
183 | } |
184 | return mp_const_none; |
185 | } |
186 | } |
187 | STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_connect_obj, socket_connect); |
188 | |
189 | STATIC mp_obj_t socket_bind(mp_obj_t self_in, mp_obj_t addr_in) { |
190 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); |
191 | mp_buffer_info_t bufinfo; |
192 | mp_get_buffer_raise(addr_in, &bufinfo, MP_BUFFER_READ); |
193 | MP_THREAD_GIL_EXIT(); |
194 | int r = bind(self->fd, (const struct sockaddr *)bufinfo.buf, bufinfo.len); |
195 | MP_THREAD_GIL_ENTER(); |
196 | RAISE_ERRNO(r, errno); |
197 | return mp_const_none; |
198 | } |
199 | STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_bind_obj, socket_bind); |
200 | |
201 | STATIC mp_obj_t socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) { |
202 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); |
203 | MP_THREAD_GIL_EXIT(); |
204 | int r = listen(self->fd, MP_OBJ_SMALL_INT_VALUE(backlog_in)); |
205 | MP_THREAD_GIL_ENTER(); |
206 | RAISE_ERRNO(r, errno); |
207 | return mp_const_none; |
208 | } |
209 | STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_listen_obj, socket_listen); |
210 | |
211 | STATIC mp_obj_t socket_accept(mp_obj_t self_in) { |
212 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); |
213 | // sockaddr_storage isn't stack-friendly (129 bytes or so) |
214 | // struct sockaddr_storage addr; |
215 | byte addr[32]; |
216 | socklen_t addr_len = sizeof(addr); |
217 | int fd; |
218 | MP_HAL_RETRY_SYSCALL(fd, accept(self->fd, (struct sockaddr *)&addr, &addr_len), { |
219 | // EAGAIN on a blocking socket means the operation timed out |
220 | if (self->blocking && err == EAGAIN) { |
221 | err = MP_ETIMEDOUT; |
222 | } |
223 | mp_raise_OSError(err); |
224 | }); |
225 | |
226 | mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); |
227 | t->items[0] = MP_OBJ_FROM_PTR(socket_new(fd)); |
228 | t->items[1] = mp_obj_new_bytearray(addr_len, &addr); |
229 | |
230 | return MP_OBJ_FROM_PTR(t); |
231 | } |
232 | STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_accept_obj, socket_accept); |
233 | |
234 | // Note: besides flag param, this differs from read() in that |
235 | // this does not swallow blocking errors (EAGAIN, EWOULDBLOCK) - |
236 | // these would be thrown as exceptions. |
237 | STATIC mp_obj_t socket_recv(size_t n_args, const mp_obj_t *args) { |
238 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]); |
239 | int sz = MP_OBJ_SMALL_INT_VALUE(args[1]); |
240 | int flags = 0; |
241 | |
242 | if (n_args > 2) { |
243 | flags = MP_OBJ_SMALL_INT_VALUE(args[2]); |
244 | } |
245 | |
246 | byte *buf = m_new(byte, sz); |
247 | ssize_t out_sz; |
248 | MP_HAL_RETRY_SYSCALL(out_sz, recv(self->fd, buf, sz, flags), mp_raise_OSError(err)); |
249 | mp_obj_t ret = mp_obj_new_str_of_type(&mp_type_bytes, buf, out_sz); |
250 | m_del(char, buf, sz); |
251 | return ret; |
252 | } |
253 | STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_recv_obj, 2, 3, socket_recv); |
254 | |
255 | STATIC mp_obj_t socket_recvfrom(size_t n_args, const mp_obj_t *args) { |
256 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]); |
257 | int sz = MP_OBJ_SMALL_INT_VALUE(args[1]); |
258 | int flags = 0; |
259 | |
260 | if (n_args > 2) { |
261 | flags = MP_OBJ_SMALL_INT_VALUE(args[2]); |
262 | } |
263 | |
264 | struct sockaddr_storage addr; |
265 | socklen_t addr_len = sizeof(addr); |
266 | |
267 | byte *buf = m_new(byte, sz); |
268 | ssize_t out_sz; |
269 | MP_HAL_RETRY_SYSCALL(out_sz, recvfrom(self->fd, buf, sz, flags, (struct sockaddr *)&addr, &addr_len), |
270 | mp_raise_OSError(err)); |
271 | mp_obj_t buf_o = mp_obj_new_str_of_type(&mp_type_bytes, buf, out_sz); |
272 | m_del(char, buf, sz); |
273 | |
274 | mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); |
275 | t->items[0] = buf_o; |
276 | t->items[1] = mp_obj_from_sockaddr((struct sockaddr *)&addr, addr_len); |
277 | |
278 | return MP_OBJ_FROM_PTR(t); |
279 | } |
280 | STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_recvfrom_obj, 2, 3, socket_recvfrom); |
281 | |
282 | // Note: besides flag param, this differs from write() in that |
283 | // this does not swallow blocking errors (EAGAIN, EWOULDBLOCK) - |
284 | // these would be thrown as exceptions. |
285 | STATIC mp_obj_t socket_send(size_t n_args, const mp_obj_t *args) { |
286 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]); |
287 | int flags = 0; |
288 | |
289 | if (n_args > 2) { |
290 | flags = MP_OBJ_SMALL_INT_VALUE(args[2]); |
291 | } |
292 | |
293 | mp_buffer_info_t bufinfo; |
294 | mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ); |
295 | ssize_t out_sz; |
296 | MP_HAL_RETRY_SYSCALL(out_sz, send(self->fd, bufinfo.buf, bufinfo.len, flags), |
297 | mp_raise_OSError(err)); |
298 | return MP_OBJ_NEW_SMALL_INT(out_sz); |
299 | } |
300 | STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_send_obj, 2, 3, socket_send); |
301 | |
302 | STATIC mp_obj_t socket_sendto(size_t n_args, const mp_obj_t *args) { |
303 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]); |
304 | int flags = 0; |
305 | |
306 | mp_obj_t dst_addr = args[2]; |
307 | if (n_args > 3) { |
308 | flags = MP_OBJ_SMALL_INT_VALUE(args[2]); |
309 | dst_addr = args[3]; |
310 | } |
311 | |
312 | mp_buffer_info_t bufinfo, addr_bi; |
313 | mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ); |
314 | mp_get_buffer_raise(dst_addr, &addr_bi, MP_BUFFER_READ); |
315 | ssize_t out_sz; |
316 | MP_HAL_RETRY_SYSCALL(out_sz, sendto(self->fd, bufinfo.buf, bufinfo.len, flags, |
317 | (struct sockaddr *)addr_bi.buf, addr_bi.len), mp_raise_OSError(err)); |
318 | return MP_OBJ_NEW_SMALL_INT(out_sz); |
319 | } |
320 | STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_sendto_obj, 3, 4, socket_sendto); |
321 | |
322 | STATIC mp_obj_t socket_setsockopt(size_t n_args, const mp_obj_t *args) { |
323 | (void)n_args; // always 4 |
324 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]); |
325 | int level = MP_OBJ_SMALL_INT_VALUE(args[1]); |
326 | int option = mp_obj_get_int(args[2]); |
327 | |
328 | const void *optval; |
329 | socklen_t optlen; |
330 | int val; |
331 | if (mp_obj_is_int(args[3])) { |
332 | val = mp_obj_int_get_truncated(args[3]); |
333 | optval = &val; |
334 | optlen = sizeof(val); |
335 | } else { |
336 | mp_buffer_info_t bufinfo; |
337 | mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ); |
338 | optval = bufinfo.buf; |
339 | optlen = bufinfo.len; |
340 | } |
341 | MP_THREAD_GIL_EXIT(); |
342 | int r = setsockopt(self->fd, level, option, optval, optlen); |
343 | MP_THREAD_GIL_ENTER(); |
344 | RAISE_ERRNO(r, errno); |
345 | return mp_const_none; |
346 | } |
347 | STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_setsockopt_obj, 4, 4, socket_setsockopt); |
348 | |
349 | STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { |
350 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); |
351 | int val = mp_obj_is_true(flag_in); |
352 | MP_THREAD_GIL_EXIT(); |
353 | int flags = fcntl(self->fd, F_GETFL, 0); |
354 | if (flags == -1) { |
355 | MP_THREAD_GIL_ENTER(); |
356 | RAISE_ERRNO(flags, errno); |
357 | } |
358 | if (val) { |
359 | flags &= ~O_NONBLOCK; |
360 | } else { |
361 | flags |= O_NONBLOCK; |
362 | } |
363 | flags = fcntl(self->fd, F_SETFL, flags); |
364 | MP_THREAD_GIL_ENTER(); |
365 | RAISE_ERRNO(flags, errno); |
366 | self->blocking = val; |
367 | return mp_const_none; |
368 | } |
369 | STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); |
370 | |
371 | STATIC mp_obj_t socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { |
372 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); |
373 | struct timeval tv = {0,}; |
374 | bool new_blocking = true; |
375 | |
376 | // Timeout of None means no timeout, which in POSIX is signified with 0 timeout, |
377 | // and that's how 'tv' is initialized above |
378 | if (timeout_in != mp_const_none) { |
379 | #if MICROPY_PY_BUILTINS_FLOAT |
380 | mp_float_t val = mp_obj_get_float(timeout_in); |
381 | mp_float_t ipart; |
382 | tv.tv_usec = (time_t)MICROPY_FLOAT_C_FUN(round)(MICROPY_FLOAT_C_FUN(modf)(val, &ipart) * MICROPY_FLOAT_CONST(1000000.)); |
383 | tv.tv_sec = (suseconds_t)ipart; |
384 | #else |
385 | tv.tv_sec = mp_obj_get_int(timeout_in); |
386 | #endif |
387 | |
388 | // For SO_RCVTIMEO/SO_SNDTIMEO, zero timeout means infinity, but |
389 | // for Python API it means non-blocking. |
390 | if (tv.tv_sec == 0 && tv.tv_usec == 0) { |
391 | new_blocking = false; |
392 | } |
393 | } |
394 | |
395 | if (new_blocking) { |
396 | int r; |
397 | MP_THREAD_GIL_EXIT(); |
398 | r = setsockopt(self->fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)); |
399 | if (r == -1) { |
400 | MP_THREAD_GIL_ENTER(); |
401 | RAISE_ERRNO(r, errno); |
402 | } |
403 | r = setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval)); |
404 | MP_THREAD_GIL_ENTER(); |
405 | RAISE_ERRNO(r, errno); |
406 | } |
407 | |
408 | if (self->blocking != new_blocking) { |
409 | socket_setblocking(self_in, mp_obj_new_bool(new_blocking)); |
410 | } |
411 | |
412 | return mp_const_none; |
413 | } |
414 | STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_settimeout_obj, socket_settimeout); |
415 | |
416 | STATIC mp_obj_t socket_makefile(size_t n_args, const mp_obj_t *args) { |
417 | // TODO: CPython explicitly says that closing returned object doesn't close |
418 | // the original socket (Python2 at all says that fd is dup()ed). But we |
419 | // save on the bloat. |
420 | mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]); |
421 | mp_obj_t *new_args = alloca(n_args * sizeof(mp_obj_t)); |
422 | memcpy(new_args + 1, args + 1, (n_args - 1) * sizeof(mp_obj_t)); |
423 | new_args[0] = MP_OBJ_NEW_SMALL_INT(self->fd); |
424 | return mp_builtin_open(n_args, new_args, (mp_map_t *)&mp_const_empty_map); |
425 | } |
426 | STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_makefile_obj, 1, 3, socket_makefile); |
427 | |
428 | STATIC mp_obj_t socket_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { |
429 | (void)type_in; |
430 | (void)n_kw; |
431 | |
432 | int family = AF_INET; |
433 | int type = SOCK_STREAM; |
434 | int proto = 0; |
435 | |
436 | if (n_args > 0) { |
437 | assert(mp_obj_is_small_int(args[0])); |
438 | family = MP_OBJ_SMALL_INT_VALUE(args[0]); |
439 | if (n_args > 1) { |
440 | assert(mp_obj_is_small_int(args[1])); |
441 | type = MP_OBJ_SMALL_INT_VALUE(args[1]); |
442 | if (n_args > 2) { |
443 | assert(mp_obj_is_small_int(args[2])); |
444 | proto = MP_OBJ_SMALL_INT_VALUE(args[2]); |
445 | } |
446 | } |
447 | } |
448 | |
449 | MP_THREAD_GIL_EXIT(); |
450 | int fd = socket(family, type, proto); |
451 | MP_THREAD_GIL_ENTER(); |
452 | RAISE_ERRNO(fd, errno); |
453 | return MP_OBJ_FROM_PTR(socket_new(fd)); |
454 | } |
455 | |
456 | STATIC const mp_rom_map_elem_t usocket_locals_dict_table[] = { |
457 | { MP_ROM_QSTR(MP_QSTR_fileno), MP_ROM_PTR(&socket_fileno_obj) }, |
458 | { MP_ROM_QSTR(MP_QSTR_makefile), MP_ROM_PTR(&socket_makefile_obj) }, |
459 | { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, |
460 | { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, |
461 | { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, |
462 | { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, |
463 | { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&socket_connect_obj) }, |
464 | { MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&socket_bind_obj) }, |
465 | { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&socket_listen_obj) }, |
466 | { MP_ROM_QSTR(MP_QSTR_accept), MP_ROM_PTR(&socket_accept_obj) }, |
467 | { MP_ROM_QSTR(MP_QSTR_recv), MP_ROM_PTR(&socket_recv_obj) }, |
468 | { MP_ROM_QSTR(MP_QSTR_recvfrom), MP_ROM_PTR(&socket_recvfrom_obj) }, |
469 | { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&socket_send_obj) }, |
470 | { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&socket_sendto_obj) }, |
471 | { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&socket_setsockopt_obj) }, |
472 | { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) }, |
473 | { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&socket_settimeout_obj) }, |
474 | { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, |
475 | }; |
476 | |
477 | STATIC MP_DEFINE_CONST_DICT(usocket_locals_dict, usocket_locals_dict_table); |
478 | |
479 | STATIC const mp_stream_p_t usocket_stream_p = { |
480 | .read = socket_read, |
481 | .write = socket_write, |
482 | .ioctl = socket_ioctl, |
483 | }; |
484 | |
485 | const mp_obj_type_t mp_type_socket = { |
486 | { &mp_type_type }, |
487 | .name = MP_QSTR_socket, |
488 | .print = socket_print, |
489 | .make_new = socket_make_new, |
490 | .getiter = NULL, |
491 | .iternext = NULL, |
492 | .protocol = &usocket_stream_p, |
493 | .locals_dict = (mp_obj_dict_t *)&usocket_locals_dict, |
494 | }; |
495 | |
496 | #define BINADDR_MAX_LEN sizeof(struct in6_addr) |
497 | STATIC mp_obj_t mod_socket_inet_pton(mp_obj_t family_in, mp_obj_t addr_in) { |
498 | int family = mp_obj_get_int(family_in); |
499 | byte binaddr[BINADDR_MAX_LEN]; |
500 | int r = inet_pton(family, mp_obj_str_get_str(addr_in), binaddr); |
501 | RAISE_ERRNO(r, errno); |
502 | if (r == 0) { |
503 | mp_raise_OSError(MP_EINVAL); |
504 | } |
505 | int binaddr_len = 0; |
506 | switch (family) { |
507 | case AF_INET: |
508 | binaddr_len = sizeof(struct in_addr); |
509 | break; |
510 | case AF_INET6: |
511 | binaddr_len = sizeof(struct in6_addr); |
512 | break; |
513 | } |
514 | return mp_obj_new_bytes(binaddr, binaddr_len); |
515 | } |
516 | STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_socket_inet_pton_obj, mod_socket_inet_pton); |
517 | |
518 | STATIC mp_obj_t mod_socket_inet_ntop(mp_obj_t family_in, mp_obj_t binaddr_in) { |
519 | int family = mp_obj_get_int(family_in); |
520 | mp_buffer_info_t bufinfo; |
521 | mp_get_buffer_raise(binaddr_in, &bufinfo, MP_BUFFER_READ); |
522 | vstr_t vstr; |
523 | vstr_init_len(&vstr, family == AF_INET ? INET_ADDRSTRLEN : INET6_ADDRSTRLEN); |
524 | if (inet_ntop(family, bufinfo.buf, vstr.buf, vstr.len) == NULL) { |
525 | mp_raise_OSError(errno); |
526 | } |
527 | vstr.len = strlen(vstr.buf); |
528 | return mp_obj_new_str_from_vstr(&mp_type_str, &vstr); |
529 | } |
530 | STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_socket_inet_ntop_obj, mod_socket_inet_ntop); |
531 | |
532 | STATIC mp_obj_t mod_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) { |
533 | // TODO: Implement 5th and 6th args |
534 | |
535 | const char *host = mp_obj_str_get_str(args[0]); |
536 | const char *serv = NULL; |
537 | struct addrinfo hints; |
538 | char buf[6]; |
539 | memset(&hints, 0, sizeof(hints)); |
540 | // getaddrinfo accepts port in string notation, so however |
541 | // it may seem stupid, we need to convert int to str |
542 | if (mp_obj_is_small_int(args[1])) { |
543 | unsigned port = (unsigned short)MP_OBJ_SMALL_INT_VALUE(args[1]); |
544 | snprintf(buf, sizeof(buf), "%u" , port); |
545 | serv = buf; |
546 | hints.ai_flags = AI_NUMERICSERV; |
547 | #ifdef __UCLIBC_MAJOR__ |
548 | #if __UCLIBC_MAJOR__ == 0 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ <= 32)) |
549 | // "warning" requires -Wno-cpp which is a relatively new gcc option, so we choose not to use it. |
550 | // #warning Working around uClibc bug with numeric service name |
551 | // Older versions og uClibc have bugs when numeric ports in service |
552 | // arg require also hints.ai_socktype (or hints.ai_protocol) != 0 |
553 | // This actually was fixed in 0.9.32.1, but uClibc doesn't allow to |
554 | // test for that. |
555 | // http://git.uclibc.org/uClibc/commit/libc/inet/getaddrinfo.c?id=bc3be18145e4d5 |
556 | // Note that this is crude workaround, precluding UDP socket addresses |
557 | // to be returned. TODO: set only if not set by Python args. |
558 | hints.ai_socktype = SOCK_STREAM; |
559 | #endif |
560 | #endif |
561 | } else { |
562 | serv = mp_obj_str_get_str(args[1]); |
563 | } |
564 | |
565 | if (n_args > 2) { |
566 | hints.ai_family = MP_OBJ_SMALL_INT_VALUE(args[2]); |
567 | if (n_args > 3) { |
568 | hints.ai_socktype = MP_OBJ_SMALL_INT_VALUE(args[3]); |
569 | } |
570 | } |
571 | |
572 | struct addrinfo *addr_list; |
573 | MP_THREAD_GIL_EXIT(); |
574 | int res = getaddrinfo(host, serv, &hints, &addr_list); |
575 | MP_THREAD_GIL_ENTER(); |
576 | |
577 | if (res != 0) { |
578 | // CPython: socket.gaierror |
579 | mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("[addrinfo error %d]" ), res); |
580 | } |
581 | assert(addr_list); |
582 | |
583 | mp_obj_t list = mp_obj_new_list(0, NULL); |
584 | for (struct addrinfo *addr = addr_list; addr; addr = addr->ai_next) { |
585 | mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(5, NULL)); |
586 | t->items[0] = MP_OBJ_NEW_SMALL_INT(addr->ai_family); |
587 | t->items[1] = MP_OBJ_NEW_SMALL_INT(addr->ai_socktype); |
588 | t->items[2] = MP_OBJ_NEW_SMALL_INT(addr->ai_protocol); |
589 | // "canonname will be a string representing the canonical name of the host |
590 | // if AI_CANONNAME is part of the flags argument; else canonname will be empty." ?? |
591 | if (addr->ai_canonname) { |
592 | t->items[3] = MP_OBJ_NEW_QSTR(qstr_from_str(addr->ai_canonname)); |
593 | } else { |
594 | t->items[3] = mp_const_none; |
595 | } |
596 | t->items[4] = mp_obj_new_bytearray(addr->ai_addrlen, addr->ai_addr); |
597 | mp_obj_list_append(list, MP_OBJ_FROM_PTR(t)); |
598 | } |
599 | freeaddrinfo(addr_list); |
600 | return list; |
601 | } |
602 | STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_socket_getaddrinfo_obj, 2, 4, mod_socket_getaddrinfo); |
603 | |
604 | STATIC mp_obj_t mod_socket_sockaddr(mp_obj_t sockaddr_in) { |
605 | mp_buffer_info_t bufinfo; |
606 | mp_get_buffer_raise(sockaddr_in, &bufinfo, MP_BUFFER_READ); |
607 | switch (((struct sockaddr *)bufinfo.buf)->sa_family) { |
608 | case AF_INET: { |
609 | struct sockaddr_in *sa = (struct sockaddr_in *)bufinfo.buf; |
610 | mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL)); |
611 | t->items[0] = MP_OBJ_NEW_SMALL_INT(AF_INET); |
612 | t->items[1] = mp_obj_new_bytes((byte *)&sa->sin_addr, sizeof(sa->sin_addr)); |
613 | t->items[2] = MP_OBJ_NEW_SMALL_INT(ntohs(sa->sin_port)); |
614 | return MP_OBJ_FROM_PTR(t); |
615 | } |
616 | case AF_INET6: { |
617 | struct sockaddr_in6 *sa = (struct sockaddr_in6 *)bufinfo.buf; |
618 | mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(5, NULL)); |
619 | t->items[0] = MP_OBJ_NEW_SMALL_INT(AF_INET6); |
620 | t->items[1] = mp_obj_new_bytes((byte *)&sa->sin6_addr, sizeof(sa->sin6_addr)); |
621 | t->items[2] = MP_OBJ_NEW_SMALL_INT(ntohs(sa->sin6_port)); |
622 | t->items[3] = MP_OBJ_NEW_SMALL_INT(ntohl(sa->sin6_flowinfo)); |
623 | t->items[4] = MP_OBJ_NEW_SMALL_INT(ntohl(sa->sin6_scope_id)); |
624 | return MP_OBJ_FROM_PTR(t); |
625 | } |
626 | default: { |
627 | struct sockaddr *sa = (struct sockaddr *)bufinfo.buf; |
628 | mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); |
629 | t->items[0] = MP_OBJ_NEW_SMALL_INT(sa->sa_family); |
630 | t->items[1] = mp_obj_new_bytes((byte *)sa->sa_data, bufinfo.len - offsetof(struct sockaddr, sa_data)); |
631 | return MP_OBJ_FROM_PTR(t); |
632 | } |
633 | } |
634 | return mp_const_none; |
635 | } |
636 | STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_socket_sockaddr_obj, mod_socket_sockaddr); |
637 | |
638 | STATIC const mp_rom_map_elem_t mp_module_socket_globals_table[] = { |
639 | { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_usocket) }, |
640 | { MP_ROM_QSTR(MP_QSTR_socket), MP_ROM_PTR(&mp_type_socket) }, |
641 | { MP_ROM_QSTR(MP_QSTR_getaddrinfo), MP_ROM_PTR(&mod_socket_getaddrinfo_obj) }, |
642 | { MP_ROM_QSTR(MP_QSTR_inet_pton), MP_ROM_PTR(&mod_socket_inet_pton_obj) }, |
643 | { MP_ROM_QSTR(MP_QSTR_inet_ntop), MP_ROM_PTR(&mod_socket_inet_ntop_obj) }, |
644 | { MP_ROM_QSTR(MP_QSTR_sockaddr), MP_ROM_PTR(&mod_socket_sockaddr_obj) }, |
645 | |
646 | #define C(name) { MP_ROM_QSTR(MP_QSTR_##name), MP_ROM_INT(name) } |
647 | C(AF_UNIX), |
648 | C(AF_INET), |
649 | C(AF_INET6), |
650 | C(SOCK_STREAM), |
651 | C(SOCK_DGRAM), |
652 | C(SOCK_RAW), |
653 | |
654 | C(MSG_DONTROUTE), |
655 | C(MSG_DONTWAIT), |
656 | |
657 | C(SOL_SOCKET), |
658 | C(SO_BROADCAST), |
659 | C(SO_ERROR), |
660 | C(SO_KEEPALIVE), |
661 | C(SO_LINGER), |
662 | C(SO_REUSEADDR), |
663 | #undef C |
664 | }; |
665 | |
666 | STATIC MP_DEFINE_CONST_DICT(mp_module_socket_globals, mp_module_socket_globals_table); |
667 | |
668 | const mp_obj_module_t mp_module_socket = { |
669 | .base = { &mp_type_module }, |
670 | .globals = (mp_obj_dict_t *)&mp_module_socket_globals, |
671 | }; |
672 | |