modsocket.c 21.8 KB
Newer Older
1
2
3
4
5
6
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
7
 * Copyright (c) 2014 Paul Sokolovsky
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

28
29
30
31
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
32
#include <fcntl.h>
xbe's avatar
xbe committed
33
34
#include <sys/stat.h>
#include <sys/types.h>
35
#include <sys/socket.h>
xbe's avatar
xbe committed
36
#include <netinet/in.h>
37
38
39
40
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

41
42
43
44
45
46
#include "py/nlr.h"
#include "py/objtuple.h"
#include "py/objstr.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "py/builtin.h"
47

48
49
50
/*
  The idea of this module is to implement reasonable minimum of
  socket-related functions to write typical clients and servers.
51
  The module named "usocket" on purpose, to allow to make
52
53
54
  Python-level module more (or fully) compatible with CPython
  "socket", e.g.:
  ---- socket.py ----
55
  from usocket import *
56
57
58
59
60
61
62
  from socket_more_funcs import *
  from socket_more_funcs2 import *
  -------------------
  I.e. this module should stay lean, and more functions (if needed)
  should be add to seperate modules (C or Python level).
 */

63
64
#define MICROPY_SOCKET_EXTRA (0)

65
66
// This type must "inherit" from mp_obj_fdfile_t, i.e. matching subset of
// fields should have the same layout.
67
68
69
70
71
typedef struct _mp_obj_socket_t {
    mp_obj_base_t base;
    int fd;
} mp_obj_socket_t;

72
const mp_obj_type_t mp_type_socket;
73
74
75
76

// Helper functions
#define RAISE_ERRNO(err_flag, error_val) \
    { if (err_flag == -1) \
77
        { nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(error_val))); } }
78

79
80
81
82
static inline mp_obj_t mp_obj_from_sockaddr(const struct sockaddr *addr, socklen_t len) {
    return mp_obj_new_bytes((const byte *)addr, len);
}

83
STATIC mp_obj_socket_t *socket_new(int fd) {
84
    mp_obj_socket_t *o = m_new_obj(mp_obj_socket_t);
85
    o->base.type = &mp_type_socket;
86
87
88
89
90
    o->fd = fd;
    return o;
}


91
STATIC void socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
92
    (void)kind;
93
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in);
94
    mp_printf(print, "<_socket %d>", self->fd);
95
96
}

97
STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
98
    mp_obj_socket_t *o = MP_OBJ_TO_PTR(o_in);
99
    mp_int_t r = read(o->fd, buf, size);
100
101
    if (r == -1) {
        *errcode = errno;
102
        return MP_STREAM_ERROR;
103
104
105
106
    }
    return r;
}

107
STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
108
    mp_obj_socket_t *o = MP_OBJ_TO_PTR(o_in);
109
    mp_int_t r = write(o->fd, buf, size);
110
111
    if (r == -1) {
        *errcode = errno;
112
        return MP_STREAM_ERROR;
113
114
115
116
    }
    return r;
}

117
STATIC mp_obj_t socket_close(mp_obj_t self_in) {
118
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in);
119
120
121
122
123
124
125
    // There's a POSIX drama regarding return value of close in general,
    // and EINTR error in particular. See e.g.
    // http://lwn.net/Articles/576478/
    // http://austingroupbugs.net/view.php?id=529
    // The rationale MicroPython follows is that close() just releases
    // file descriptor. If you're interested to catch I/O errors before
    // closing fd, fsync() it.
126
127
128
    close(self->fd);
    return mp_const_none;
}
129
STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_close_obj, socket_close);
130

131
STATIC mp_obj_t socket_fileno(mp_obj_t self_in) {
132
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in);
133
    return MP_OBJ_NEW_SMALL_INT(self->fd);
134
}
135
STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_fileno_obj, socket_fileno);
136

137
STATIC mp_obj_t socket_connect(mp_obj_t self_in, mp_obj_t addr_in) {
138
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in);
139
    mp_buffer_info_t bufinfo;
140
    mp_get_buffer_raise(addr_in, &bufinfo, MP_BUFFER_READ);
141
142
143
144
    int r = connect(self->fd, (const struct sockaddr *)bufinfo.buf, bufinfo.len);
    RAISE_ERRNO(r, errno);
    return mp_const_none;
}
145
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_connect_obj, socket_connect);
146

147
STATIC mp_obj_t socket_bind(mp_obj_t self_in, mp_obj_t addr_in) {
148
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in);
149
    mp_buffer_info_t bufinfo;
150
    mp_get_buffer_raise(addr_in, &bufinfo, MP_BUFFER_READ);
151
152
153
154
    int r = bind(self->fd, (const struct sockaddr *)bufinfo.buf, bufinfo.len);
    RAISE_ERRNO(r, errno);
    return mp_const_none;
}
155
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_bind_obj, socket_bind);
156

157
STATIC mp_obj_t socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) {
158
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in);
159
160
161
162
    int r = listen(self->fd, MP_OBJ_SMALL_INT_VALUE(backlog_in));
    RAISE_ERRNO(r, errno);
    return mp_const_none;
}
163
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_listen_obj, socket_listen);
164

165
STATIC mp_obj_t socket_accept(mp_obj_t self_in) {
166
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in);
167
168
169
    // sockaddr_storage isn't stack-friendly (129 bytes or so)
    //struct sockaddr_storage addr;
    byte addr[32];
170
    socklen_t addr_len = sizeof(addr);
171
    int fd = accept(self->fd, (struct sockaddr*)&addr, &addr_len);
172
173
    RAISE_ERRNO(fd, errno);

174
175
    mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL));
    t->items[0] = MP_OBJ_FROM_PTR(socket_new(fd));
176
177
    t->items[1] = mp_obj_new_bytearray(addr_len, &addr);

178
    return MP_OBJ_FROM_PTR(t);
179
}
180
STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_accept_obj, socket_accept);
181

182
183
184
// Note: besides flag param, this differs from read() in that
// this does not swallow blocking errors (EAGAIN, EWOULDBLOCK) -
// these would be thrown as exceptions.
185
STATIC mp_obj_t socket_recv(size_t n_args, const mp_obj_t *args) {
186
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]);
187
188
189
190
191
192
193
    int sz = MP_OBJ_SMALL_INT_VALUE(args[1]);
    int flags = 0;

    if (n_args > 2) {
        flags = MP_OBJ_SMALL_INT_VALUE(args[2]);
    }

194
    byte *buf = m_new(byte, sz);
195
196
197
    int out_sz = recv(self->fd, buf, sz, flags);
    RAISE_ERRNO(out_sz, errno);

198
    mp_obj_t ret = mp_obj_new_str_of_type(&mp_type_bytes, buf, out_sz);
199
200
    m_del(char, buf, sz);
    return ret;
201
}
202
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_recv_obj, 2, 3, socket_recv);
203

204
STATIC mp_obj_t socket_recvfrom(size_t n_args, const mp_obj_t *args) {
205
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]);
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
    int sz = MP_OBJ_SMALL_INT_VALUE(args[1]);
    int flags = 0;

    if (n_args > 2) {
        flags = MP_OBJ_SMALL_INT_VALUE(args[2]);
    }

    struct sockaddr_storage addr;
    socklen_t addr_len = sizeof(addr);

    byte *buf = m_new(byte, sz);
    int out_sz = recvfrom(self->fd, buf, sz, flags, (struct sockaddr*)&addr, &addr_len);
    RAISE_ERRNO(out_sz, errno);

    mp_obj_t buf_o = mp_obj_new_str_of_type(&mp_type_bytes, buf, out_sz);
    m_del(char, buf, sz);

223
    mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL));
224
225
226
    t->items[0] = buf_o;
    t->items[1] = mp_obj_from_sockaddr((struct sockaddr*)&addr, addr_len);

227
    return MP_OBJ_FROM_PTR(t);
228
229
230
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_recvfrom_obj, 2, 3, socket_recvfrom);

231
232
233
// Note: besides flag param, this differs from write() in that
// this does not swallow blocking errors (EAGAIN, EWOULDBLOCK) -
// these would be thrown as exceptions.
234
STATIC mp_obj_t socket_send(size_t n_args, const mp_obj_t *args) {
235
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]);
236
237
238
239
240
241
    int flags = 0;

    if (n_args > 2) {
        flags = MP_OBJ_SMALL_INT_VALUE(args[2]);
    }

242
243
244
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ);
    int out_sz = send(self->fd, bufinfo.buf, bufinfo.len, flags);
245
246
    RAISE_ERRNO(out_sz, errno);

247
    return MP_OBJ_NEW_SMALL_INT(out_sz);
248
}
249
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_send_obj, 2, 3, socket_send);
250

251
STATIC mp_obj_t socket_sendto(size_t n_args, const mp_obj_t *args) {
252
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]);
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    int flags = 0;

    mp_obj_t dst_addr = args[2];
    if (n_args > 3) {
        flags = MP_OBJ_SMALL_INT_VALUE(args[2]);
        dst_addr = args[3];
    }

    mp_buffer_info_t bufinfo, addr_bi;
    mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ);
    mp_get_buffer_raise(dst_addr, &addr_bi, MP_BUFFER_READ);
    int out_sz = sendto(self->fd, bufinfo.buf, bufinfo.len, flags,
                        (struct sockaddr *)addr_bi.buf, addr_bi.len);
    RAISE_ERRNO(out_sz, errno);

    return MP_OBJ_NEW_SMALL_INT(out_sz);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_sendto_obj, 3, 4, socket_sendto);

272
STATIC mp_obj_t socket_setsockopt(size_t n_args, const mp_obj_t *args) {
273
    (void)n_args; // always 4
274
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]);
275
276
277
278
279
    int level = MP_OBJ_SMALL_INT_VALUE(args[1]);
    int option = mp_obj_get_int(args[2]);

    const void *optval;
    socklen_t optlen;
280
    int val;
281
    if (MP_OBJ_IS_INT(args[3])) {
282
        val = mp_obj_int_get_truncated(args[3]);
283
284
285
        optval = &val;
        optlen = sizeof(val);
    } else {
286
        mp_buffer_info_t bufinfo;
287
        mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ);
288
289
290
291
292
293
294
        optval = bufinfo.buf;
        optlen = bufinfo.len;
    }
    int r = setsockopt(self->fd, level, option, optval, optlen);
    RAISE_ERRNO(r, errno);
    return mp_const_none;
}
295
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_setsockopt_obj, 4, 4, socket_setsockopt);
296

297
STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
298
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in);
299
300
301
302
303
304
305
306
307
308
309
310
311
312
    int val = mp_obj_is_true(flag_in);
    int flags = fcntl(self->fd, F_GETFL, 0);
    RAISE_ERRNO(flags, errno);
    if (val) {
        flags &= ~O_NONBLOCK;
    } else {
        flags |= O_NONBLOCK;
    }
    flags = fcntl(self->fd, F_SETFL, flags);
    RAISE_ERRNO(flags, errno);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);

313
STATIC mp_obj_t socket_makefile(size_t n_args, const mp_obj_t *args) {
314
315
316
    // TODO: CPython explicitly says that closing returned object doesn't close
    // the original socket (Python2 at all says that fd is dup()ed). But we
    // save on the bloat.
317
    mp_obj_socket_t *self = MP_OBJ_TO_PTR(args[0]);
318
319
    mp_obj_t *new_args = alloca(n_args * sizeof(mp_obj_t));
    memcpy(new_args + 1, args + 1, (n_args - 1) * sizeof(mp_obj_t));
320
    new_args[0] = MP_OBJ_NEW_SMALL_INT(self->fd);
321
    return mp_builtin_open(n_args, new_args, (mp_map_t*)&mp_const_empty_map);
322
323
324
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_makefile_obj, 1, 3, socket_makefile);

325
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) {
326
327
328
    (void)type_in;
    (void)n_kw;

329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
    int family = AF_INET;
    int type = SOCK_STREAM;
    int proto = 0;

    if (n_args > 0) {
        assert(MP_OBJ_IS_SMALL_INT(args[0]));
        family = MP_OBJ_SMALL_INT_VALUE(args[0]);
        if (n_args > 1) {
            assert(MP_OBJ_IS_SMALL_INT(args[1]));
            type = MP_OBJ_SMALL_INT_VALUE(args[1]);
            if (n_args > 2) {
                assert(MP_OBJ_IS_SMALL_INT(args[2]));
                proto = MP_OBJ_SMALL_INT_VALUE(args[2]);
            }
        }
    }

    int fd = socket(family, type, proto);
    RAISE_ERRNO(fd, errno);
348
    return MP_OBJ_FROM_PTR(socket_new(fd));
349
350
}

351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
STATIC const mp_rom_map_elem_t usocket_locals_dict_table[] = {
    { MP_ROM_QSTR(MP_QSTR_fileno), MP_ROM_PTR(&socket_fileno_obj) },
    { MP_ROM_QSTR(MP_QSTR_makefile), MP_ROM_PTR(&socket_makefile_obj) },
    { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
    { MP_ROM_QSTR(MP_QSTR_readall), MP_ROM_PTR(&mp_stream_readall_obj) },
    { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
    { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
    { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
    { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&socket_connect_obj) },
    { MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&socket_bind_obj) },
    { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&socket_listen_obj) },
    { MP_ROM_QSTR(MP_QSTR_accept), MP_ROM_PTR(&socket_accept_obj) },
    { MP_ROM_QSTR(MP_QSTR_recv), MP_ROM_PTR(&socket_recv_obj) },
    { MP_ROM_QSTR(MP_QSTR_recvfrom), MP_ROM_PTR(&socket_recvfrom_obj) },
    { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&socket_send_obj) },
    { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&socket_sendto_obj) },
    { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&socket_setsockopt_obj) },
    { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) },
    { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&socket_close_obj) },
370
371
};

372
STATIC MP_DEFINE_CONST_DICT(usocket_locals_dict, usocket_locals_dict_table);
373

374
STATIC const mp_stream_p_t usocket_stream_p = {
375
376
377
378
    .read = socket_read,
    .write = socket_write,
};

379
const mp_obj_type_t mp_type_socket = {
380
    { &mp_type_type },
381
    .name = MP_QSTR_socket,
382
383
384
385
    .print = socket_print,
    .make_new = socket_make_new,
    .getiter = NULL,
    .iternext = NULL,
386
    .protocol = &usocket_stream_p,
387
    .locals_dict = (mp_obj_dict_t*)&usocket_locals_dict,
388
389
};

390
#if MICROPY_SOCKET_EXTRA
391
STATIC mp_obj_t mod_socket_htons(mp_obj_t arg) {
392
    return MP_OBJ_NEW_SMALL_INT(htons(MP_OBJ_SMALL_INT_VALUE(arg)));
393
}
394
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_socket_htons_obj, mod_socket_htons);
395
396


397
STATIC mp_obj_t mod_socket_gethostbyname(mp_obj_t arg) {
398
    assert(MP_OBJ_IS_TYPE(arg, &mp_type_str));
399
    const char *s = mp_obj_str_get_str(arg);
400
401
    struct hostent *h = gethostbyname(s);
    if (h == NULL) {
402
        // CPython: socket.herror
403
        nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(h_errno)));
404
405
406
407
    }
    assert(h->h_length == 4);
    return mp_obj_new_int(*(int*)*h->h_addr_list);
}
408
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_socket_gethostbyname_obj, mod_socket_gethostbyname);
409
#endif // MICROPY_SOCKET_EXTRA
410

411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#define BINADDR_MAX_LEN sizeof(struct in6_addr)
STATIC mp_obj_t mod_socket_inet_pton(mp_obj_t family_in, mp_obj_t addr_in) {
    int family = mp_obj_get_int(family_in);
    byte binaddr[BINADDR_MAX_LEN];
    int r = inet_pton(family, mp_obj_str_get_str(addr_in), binaddr);
    RAISE_ERRNO(r, errno);
    if (r == 0) {
        nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(EINVAL)));
    }
    int binaddr_len = 0;
    switch (family) {
        case AF_INET:
            binaddr_len = sizeof(struct in_addr);
            break;
        case AF_INET6:
            binaddr_len = sizeof(struct in6_addr);
            break;
    }
    return mp_obj_new_bytes(binaddr, binaddr_len);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_socket_inet_pton_obj, mod_socket_inet_pton);

433
434
435
436
437
438
439
440
441
442
443
444
445
446
STATIC mp_obj_t mod_socket_inet_ntop(mp_obj_t family_in, mp_obj_t binaddr_in) {
    int family = mp_obj_get_int(family_in);
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(binaddr_in, &bufinfo, MP_BUFFER_READ);
    vstr_t vstr;
    vstr_init_len(&vstr, family == AF_INET ? INET_ADDRSTRLEN : INET6_ADDRSTRLEN);
    if (inet_ntop(family, bufinfo.buf, vstr.buf, vstr.len) == NULL) {
        nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(errno)));
    }
    vstr.len = strlen(vstr.buf);
    return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_socket_inet_ntop_obj, mod_socket_inet_ntop);

447
STATIC mp_obj_t mod_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) {
448
    // TODO: Implement all args
449
    assert(n_args >= 2 && n_args <= 4);
450
    assert(MP_OBJ_IS_STR(args[0]));
451

452
    const char *host = mp_obj_str_get_str(args[0]);
453
    const char *serv = NULL;
454
    struct addrinfo hints;
455
    char buf[6];
456
    memset(&hints, 0, sizeof(hints));
457
458
459
    // getaddrinfo accepts port in string notation, so however
    // it may seem stupid, we need to convert int to str
    if (MP_OBJ_IS_SMALL_INT(args[1])) {
460
        unsigned port = (unsigned short)MP_OBJ_SMALL_INT_VALUE(args[1]);
461
        snprintf(buf, sizeof(buf), "%u", port);
462
        serv = buf;
463
        hints.ai_flags = AI_NUMERICSERV;
464
#ifdef __UCLIBC_MAJOR__
465
#if __UCLIBC_MAJOR__ == 0 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ <= 32))
466
467
// "warning" requires -Wno-cpp which is a relatively new gcc option, so we choose not to use it.
//#warning Working around uClibc bug with numeric service name
468
469
470
471
472
473
474
475
        // Older versions og uClibc have bugs when numeric ports in service
        // arg require also hints.ai_socktype (or hints.ai_protocol) != 0
        // This actually was fixed in 0.9.32.1, but uClibc doesn't allow to
        // test for that.
        // http://git.uclibc.org/uClibc/commit/libc/inet/getaddrinfo.c?id=bc3be18145e4d5
        // Note that this is crude workaround, precluding UDP socket addresses
        // to be returned. TODO: set only if not set by Python args.
        hints.ai_socktype = SOCK_STREAM;
476
#endif
477
#endif
478
    } else {
479
        serv = mp_obj_str_get_str(args[1]);
480
481
    }

482
483
484
485
486
487
488
    if (n_args > 2) {
        hints.ai_family = MP_OBJ_SMALL_INT_VALUE(args[2]);
        if (n_args > 3) {
            hints.ai_socktype = MP_OBJ_SMALL_INT_VALUE(args[3]);
        }
    }

489
    struct addrinfo *addr_list;
490
    int res = getaddrinfo(host, serv, &hints, &addr_list);
491
492

    if (res != 0) {
493
        // CPython: socket.gaierror
494
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "[addrinfo error %d]", res));
495
    }
496
    assert(addr_list);
497

498
    mp_obj_t list = mp_obj_new_list(0, NULL);
499
    for (struct addrinfo *addr = addr_list; addr; addr = addr->ai_next) {
500
        mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(5, NULL));
501
502
503
        t->items[0] = MP_OBJ_NEW_SMALL_INT(addr->ai_family);
        t->items[1] = MP_OBJ_NEW_SMALL_INT(addr->ai_socktype);
        t->items[2] = MP_OBJ_NEW_SMALL_INT(addr->ai_protocol);
504
505
506
        // "canonname will be a string representing the canonical name of the host
        // if AI_CANONNAME is part of the flags argument; else canonname will be empty." ??
        if (addr->ai_canonname) {
507
            t->items[3] = MP_OBJ_NEW_QSTR(qstr_from_str(addr->ai_canonname));
508
509
510
511
        } else {
            t->items[3] = mp_const_none;
        }
        t->items[4] = mp_obj_new_bytearray(addr->ai_addrlen, addr->ai_addr);
512
        mp_obj_list_append(list, MP_OBJ_FROM_PTR(t));
513
    }
514
    freeaddrinfo(addr_list);
515
516
    return list;
}
517
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_socket_getaddrinfo_obj, 2, 6, mod_socket_getaddrinfo);
518

519
520
521
522
523
524
STATIC mp_obj_t mod_socket_sockaddr(mp_obj_t sockaddr_in) {
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(sockaddr_in, &bufinfo, MP_BUFFER_READ);
    switch (((struct sockaddr*)bufinfo.buf)->sa_family) {
        case AF_INET: {
            struct sockaddr_in *sa = (struct sockaddr_in*)bufinfo.buf;
525
            mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL));
526
527
528
            t->items[0] = MP_OBJ_NEW_SMALL_INT(AF_INET);
            t->items[1] = mp_obj_new_bytes((byte*)&sa->sin_addr, sizeof(sa->sin_addr));
            t->items[2] = MP_OBJ_NEW_SMALL_INT(ntohs(sa->sin_port));
529
            return MP_OBJ_FROM_PTR(t);
530
        }
531
532
533
534
535
536
537
538
539
540
        case AF_INET6: {
            struct sockaddr_in6 *sa = (struct sockaddr_in6*)bufinfo.buf;
            mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(5, NULL));
            t->items[0] = MP_OBJ_NEW_SMALL_INT(AF_INET6);
            t->items[1] = mp_obj_new_bytes((byte*)&sa->sin6_addr, sizeof(sa->sin6_addr));
            t->items[2] = MP_OBJ_NEW_SMALL_INT(ntohs(sa->sin6_port));
            t->items[3] = MP_OBJ_NEW_SMALL_INT(ntohl(sa->sin6_flowinfo));
            t->items[4] = MP_OBJ_NEW_SMALL_INT(ntohl(sa->sin6_scope_id));
            return MP_OBJ_FROM_PTR(t);
        }
541
542
        default: {
            struct sockaddr *sa = (struct sockaddr*)bufinfo.buf;
543
            mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL));
544
545
            t->items[0] = MP_OBJ_NEW_SMALL_INT(sa->sa_family);
            t->items[1] = mp_obj_new_bytes((byte*)sa->sa_data, bufinfo.len - offsetof(struct sockaddr, sa_data));
546
            return MP_OBJ_FROM_PTR(t);
547
548
549
550
551
552
        }
    }
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_socket_sockaddr_obj, mod_socket_sockaddr);

553
554
STATIC const mp_rom_map_elem_t mp_module_socket_globals_table[] = {
    { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_usocket) },
555
    { MP_ROM_QSTR(MP_QSTR_socket), MP_ROM_PTR(&mp_type_socket) },
556
557
    { MP_ROM_QSTR(MP_QSTR_getaddrinfo), MP_ROM_PTR(&mod_socket_getaddrinfo_obj) },
    { MP_ROM_QSTR(MP_QSTR_inet_pton), MP_ROM_PTR(&mod_socket_inet_pton_obj) },
558
    { MP_ROM_QSTR(MP_QSTR_inet_ntop), MP_ROM_PTR(&mod_socket_inet_ntop_obj) },
559
    { MP_ROM_QSTR(MP_QSTR_sockaddr), MP_ROM_PTR(&mod_socket_sockaddr_obj) },
560
#if MICROPY_SOCKET_EXTRA
561
562
    { MP_ROM_QSTR(MP_QSTR_htons), MP_ROM_PTR(&mod_socket_htons_obj) },
    { MP_ROM_QSTR(MP_QSTR_gethostbyname), MP_ROM_PTR(&mod_socket_gethostbyname_obj) },
563
#endif
564

565
#define C(name) { MP_ROM_QSTR(MP_QSTR_ ## name), MP_ROM_INT(name) }
566
567
568
569
570
571
    C(AF_UNIX),
    C(AF_INET),
    C(AF_INET6),
    C(SOCK_STREAM),
    C(SOCK_DGRAM),
    C(SOCK_RAW),
572
573
574
575
576
577
578
579
580
581

    C(MSG_DONTROUTE),
    C(MSG_DONTWAIT),

    C(SOL_SOCKET),
    C(SO_BROADCAST),
    C(SO_ERROR),
    C(SO_KEEPALIVE),
    C(SO_LINGER),
    C(SO_REUSEADDR),
582
#undef C
583
584
};

585
STATIC MP_DEFINE_CONST_DICT(mp_module_socket_globals, mp_module_socket_globals_table);
586

587
588
589
590
const mp_obj_module_t mp_module_socket = {
    .base = { &mp_type_module },
    .globals = (mp_obj_dict_t*)&mp_module_socket_globals,
};