modsocket.c 14.5 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
#include "mpconfig.h"
42
43
#include "nlr.h"
#include "misc.h"
44
#include "qstr.h"
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "obj.h"
#include "objtuple.h"
#include "objarray.h"
#include "runtime.h"
#include "stream.h"

#define MICROPY_SOCKET_EXTRA (0)

typedef struct _mp_obj_socket_t {
    mp_obj_base_t base;
    int fd;
} mp_obj_socket_t;

58
STATIC const mp_obj_type_t microsocket_type;
59
60
61
62

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

65
STATIC mp_obj_socket_t *socket_new(int fd) {
66
    mp_obj_socket_t *o = m_new_obj(mp_obj_socket_t);
67
    o->base.type = &microsocket_type;
68
69
70
71
72
    o->fd = fd;
    return o;
}


73
STATIC void socket_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
74
75
76
77
    mp_obj_socket_t *self = self_in;
    print(env, "<_socket %d>", self->fd);
}

78
STATIC machine_int_t socket_read(mp_obj_t o_in, void *buf, machine_uint_t size, int *errcode) {
79
80
81
82
83
84
85
86
    mp_obj_socket_t *o = o_in;
    machine_int_t r = read(o->fd, buf, size);
    if (r == -1) {
        *errcode = errno;
    }
    return r;
}

87
STATIC machine_int_t socket_write(mp_obj_t o_in, const void *buf, machine_uint_t size, int *errcode) {
88
89
90
91
92
93
94
95
    mp_obj_socket_t *o = o_in;
    machine_int_t r = write(o->fd, buf, size);
    if (r == -1) {
        *errcode = errno;
    }
    return r;
}

96
STATIC mp_obj_t socket_close(mp_obj_t self_in) {
97
98
99
100
    mp_obj_socket_t *self = self_in;
    close(self->fd);
    return mp_const_none;
}
101
STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_close_obj, socket_close);
102

103
STATIC mp_obj_t socket_fileno(mp_obj_t self_in) {
104
    mp_obj_socket_t *self = self_in;
105
    return MP_OBJ_NEW_SMALL_INT((machine_int_t)self->fd);
106
}
107
STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_fileno_obj, socket_fileno);
108

109
STATIC mp_obj_t socket_connect(mp_obj_t self_in, mp_obj_t addr_in) {
110
    mp_obj_socket_t *self = self_in;
111
    mp_buffer_info_t bufinfo;
112
    mp_get_buffer_raise(addr_in, &bufinfo, MP_BUFFER_READ);
113
114
115
116
    int r = connect(self->fd, (const struct sockaddr *)bufinfo.buf, bufinfo.len);
    RAISE_ERRNO(r, errno);
    return mp_const_none;
}
117
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_connect_obj, socket_connect);
118

119
STATIC mp_obj_t socket_bind(mp_obj_t self_in, mp_obj_t addr_in) {
120
    mp_obj_socket_t *self = self_in;
121
    mp_buffer_info_t bufinfo;
122
    mp_get_buffer_raise(addr_in, &bufinfo, MP_BUFFER_READ);
123
124
125
126
    int r = bind(self->fd, (const struct sockaddr *)bufinfo.buf, bufinfo.len);
    RAISE_ERRNO(r, errno);
    return mp_const_none;
}
127
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_bind_obj, socket_bind);
128

129
STATIC mp_obj_t socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) {
130
131
132
133
134
    mp_obj_socket_t *self = self_in;
    int r = listen(self->fd, MP_OBJ_SMALL_INT_VALUE(backlog_in));
    RAISE_ERRNO(r, errno);
    return mp_const_none;
}
135
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_listen_obj, socket_listen);
136

137
STATIC mp_obj_t socket_accept(mp_obj_t self_in) {
138
139
140
141
142
143
144
145
146
147
148
149
    mp_obj_socket_t *self = self_in;
    struct sockaddr addr;
    socklen_t addr_len = sizeof(addr);
    int fd = accept(self->fd, &addr, &addr_len);
    RAISE_ERRNO(fd, errno);

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

    return t;
}
150
STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_accept_obj, socket_accept);
151

152
153
154
// Note: besides flag param, this differs from read() in that
// this does not swallow blocking errors (EAGAIN, EWOULDBLOCK) -
// these would be thrown as exceptions.
155
STATIC mp_obj_t socket_recv(uint n_args, const mp_obj_t *args) {
156
157
158
159
160
161
162
163
    mp_obj_socket_t *self = args[0];
    int sz = MP_OBJ_SMALL_INT_VALUE(args[1]);
    int flags = 0;

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

164
    char *buf = m_new(char, sz);
165
166
167
    int out_sz = recv(self->fd, buf, sz, flags);
    RAISE_ERRNO(out_sz, errno);

168
169
    buf = m_realloc(buf, sz, out_sz);
    return MP_OBJ_NEW_QSTR(qstr_from_strn_take(buf, out_sz, out_sz));
170
}
171
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_recv_obj, 2, 3, socket_recv);
172

173
174
175
// Note: besides flag param, this differs from write() in that
// this does not swallow blocking errors (EAGAIN, EWOULDBLOCK) -
// these would be thrown as exceptions.
176
STATIC mp_obj_t socket_send(uint n_args, const mp_obj_t *args) {
177
178
179
180
181
182
183
    mp_obj_socket_t *self = args[0];
    int flags = 0;

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

184
185
186
    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);
187
188
    RAISE_ERRNO(out_sz, errno);

189
    return MP_OBJ_NEW_SMALL_INT((machine_int_t)out_sz);
190
}
191
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_send_obj, 2, 3, socket_send);
192

193
STATIC mp_obj_t socket_setsockopt(uint n_args, const mp_obj_t *args) {
194
195
196
197
198
199
200
201
202
203
204
    mp_obj_socket_t *self = args[0];
    int level = MP_OBJ_SMALL_INT_VALUE(args[1]);
    int option = mp_obj_get_int(args[2]);

    const void *optval;
    socklen_t optlen;
    if (MP_OBJ_IS_INT(args[3])) {
        int val = mp_obj_int_get(args[3]);
        optval = &val;
        optlen = sizeof(val);
    } else {
205
        mp_buffer_info_t bufinfo;
206
        mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ);
207
208
209
210
211
212
213
        optval = bufinfo.buf;
        optlen = bufinfo.len;
    }
    int r = setsockopt(self->fd, level, option, optval, optlen);
    RAISE_ERRNO(r, errno);
    return mp_const_none;
}
214
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_setsockopt_obj, 4, 4, socket_setsockopt);
215

216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
    mp_obj_socket_t *self = self_in;
    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);

232
STATIC mp_obj_t socket_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    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);
    return socket_new(fd);
}

255
STATIC const mp_map_elem_t microsocket_locals_dict_table[] = {
256
257
258
259
260
261
262
263
264
265
266
267
268
    { MP_OBJ_NEW_QSTR(MP_QSTR_fileno), (mp_obj_t)&socket_fileno_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_makefile), (mp_obj_t)&mp_identity_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_stream_read_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_readall), (mp_obj_t)&mp_stream_readall_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_readline), (mp_obj_t)&mp_stream_unbuffered_readline_obj},
    { MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_stream_write_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_connect), (mp_obj_t)&socket_connect_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_bind), (mp_obj_t)&socket_bind_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_listen), (mp_obj_t)&socket_listen_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_accept), (mp_obj_t)&socket_accept_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_recv), (mp_obj_t)&socket_recv_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_send), (mp_obj_t)&socket_send_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_setsockopt), (mp_obj_t)&socket_setsockopt_obj },
269
    { MP_OBJ_NEW_QSTR(MP_QSTR_setblocking), (mp_obj_t)&socket_setblocking_obj },
270
    { MP_OBJ_NEW_QSTR(MP_QSTR_close), (mp_obj_t)&socket_close_obj },
271
#if MICROPY_SOCKET_EXTRA
272
273
    { MP_OBJ_NEW_QSTR(MP_QSTR_recv), (mp_obj_t)&mp_stream_read_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_send), (mp_obj_t)&mp_stream_write_obj },
274
275
276
#endif
};

277
278
STATIC MP_DEFINE_CONST_DICT(microsocket_locals_dict, microsocket_locals_dict_table);

279
280
281
282
283
STATIC const mp_stream_p_t microsocket_stream_p = {
    .read = socket_read,
    .write = socket_write,
};

284
STATIC const mp_obj_type_t microsocket_type = {
285
    { &mp_type_type },
286
    .name = MP_QSTR_socket,
287
288
289
290
    .print = socket_print,
    .make_new = socket_make_new,
    .getiter = NULL,
    .iternext = NULL,
291
    .stream_p = &microsocket_stream_p,
292
    .locals_dict = (mp_obj_t)&microsocket_locals_dict,
293
294
};

295
#if MICROPY_SOCKET_EXTRA
296
STATIC mp_obj_t mod_socket_htons(mp_obj_t arg) {
297
    return MP_OBJ_NEW_SMALL_INT((machine_int_t)htons(MP_OBJ_SMALL_INT_VALUE(arg)));
298
}
299
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_socket_htons_obj, mod_socket_htons);
300

301
STATIC mp_obj_t mod_socket_inet_aton(mp_obj_t arg) {
302
    assert(MP_OBJ_IS_TYPE(arg, &mp_type_str));
303
    const char *s = mp_obj_str_get_str(arg);
304
305
    struct in_addr addr;
    if (!inet_aton(s, &addr)) {
306
        nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(EINVAL)));
307
308
309
310
    }

    return mp_obj_new_int(addr.s_addr);
}
311
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_socket_inet_aton_obj, mod_socket_inet_aton);
312

313
STATIC mp_obj_t mod_socket_gethostbyname(mp_obj_t arg) {
314
    assert(MP_OBJ_IS_TYPE(arg, &mp_type_str));
315
    const char *s = mp_obj_str_get_str(arg);
316
317
    struct hostent *h = gethostbyname(s);
    if (h == NULL) {
318
        // CPython: socket.herror
319
        nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT((machine_int_t)h_errno)));
320
321
322
323
    }
    assert(h->h_length == 4);
    return mp_obj_new_int(*(int*)*h->h_addr_list);
}
324
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_socket_gethostbyname_obj, mod_socket_gethostbyname);
325
#endif // MICROPY_SOCKET_EXTRA
326

327
STATIC mp_obj_t mod_socket_getaddrinfo(uint n_args, const mp_obj_t *args) {
328
329
    // TODO: Implement all args
    assert(n_args == 2);
330
    assert(MP_OBJ_IS_STR(args[0]));
331

332
    const char *host = mp_obj_str_get_str(args[0]);
333
334
335
336
    const char *serv = NULL;
    // 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])) {
337
338
        int port = (short)MP_OBJ_SMALL_INT_VALUE(args[1]);
        char buf[6];
339
340
341
        sprintf(buf, "%d", port);
        serv = buf;
    } else {
342
        serv = mp_obj_str_get_str(args[1]);
343
344
345
346
347
348
349
350
    }

    struct addrinfo hints;
    struct addrinfo *addr;
    memset(&hints, 0, sizeof(hints));
    int res = getaddrinfo(host, serv, NULL/*&hints*/, &addr);

    if (res != 0) {
351
        // CPython: socket.gaierror
352
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "[addrinfo error %d]", res));
353
354
355
    }
    assert(addr);

356
    mp_obj_t list = mp_obj_new_list(0, NULL);
357
358
    for (; addr; addr = addr->ai_next) {
        mp_obj_tuple_t *t = mp_obj_new_tuple(5, NULL);
359
360
361
        t->items[0] = MP_OBJ_NEW_SMALL_INT((machine_int_t)addr->ai_family);
        t->items[1] = MP_OBJ_NEW_SMALL_INT((machine_int_t)addr->ai_socktype);
        t->items[2] = MP_OBJ_NEW_SMALL_INT((machine_int_t)addr->ai_protocol);
362
363
364
        // "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) {
365
            t->items[3] = MP_OBJ_NEW_QSTR(qstr_from_str(addr->ai_canonname));
366
367
368
369
        } else {
            t->items[3] = mp_const_none;
        }
        t->items[4] = mp_obj_new_bytearray(addr->ai_addrlen, addr->ai_addr);
370
        mp_obj_list_append(list, t);
371
372
373
    }
    return list;
}
374
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_socket_getaddrinfo_obj, 2, 6, mod_socket_getaddrinfo);
375
376
377

extern mp_obj_type_t sockaddr_in_type;

378
379
380
381
382
383
384
385
386
387
STATIC const mp_map_elem_t mp_module_socket_globals_table[] = {
    { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_microsocket) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_socket), (mp_obj_t)&microsocket_type },
    { MP_OBJ_NEW_QSTR(MP_QSTR_getaddrinfo), (mp_obj_t)&mod_socket_getaddrinfo_obj },
#if MICROPY_SOCKET_EXTRA
    { MP_OBJ_NEW_QSTR(MP_QSTR_sockaddr_in), (mp_obj_t)&sockaddr_in_type },
    { MP_OBJ_NEW_QSTR(MP_QSTR_htons), (mp_obj_t)&mod_socket_htons_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_inet_aton), (mp_obj_t)&mod_socket_inet_aton_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_gethostbyname), (mp_obj_t)&mod_socket_gethostbyname_obj },
#endif
388

389
#define C(name) { MP_OBJ_NEW_QSTR(MP_QSTR_ ## name), MP_OBJ_NEW_SMALL_INT(name) }
390
391
392
393
394
395
    C(AF_UNIX),
    C(AF_INET),
    C(AF_INET6),
    C(SOCK_STREAM),
    C(SOCK_DGRAM),
    C(SOCK_RAW),
396
397
398
399
400
401
402
403
404
405

    C(MSG_DONTROUTE),
    C(MSG_DONTWAIT),

    C(SOL_SOCKET),
    C(SO_BROADCAST),
    C(SO_ERROR),
    C(SO_KEEPALIVE),
    C(SO_LINGER),
    C(SO_REUSEADDR),
406
#undef C
407
408
};

409
410
411
412
413
STATIC const mp_obj_dict_t mp_module_socket_globals = {
    .base = {&mp_type_dict},
    .map = {
        .all_keys_are_qstrs = 1,
        .table_is_fixed_array = 1,
414
415
        .used = ARRAY_SIZE(mp_module_socket_globals_table),
        .alloc = ARRAY_SIZE(mp_module_socket_globals_table),
416
417
418
        .table = (mp_map_elem_t*)mp_module_socket_globals_table,
    },
};
419

420
421
422
423
424
const mp_obj_module_t mp_module_socket = {
    .base = { &mp_type_module },
    .name = MP_QSTR_microsocket,
    .globals = (mp_obj_dict_t*)&mp_module_socket_globals,
};