modsocket.c 11.7 KB
Newer Older
1
2
3
4
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
xbe's avatar
xbe committed
5
6
#include <sys/stat.h>
#include <sys/types.h>
7
#include <sys/socket.h>
xbe's avatar
xbe committed
8
#include <netinet/in.h>
9
10
11
12
13
14
15
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

#include "nlr.h"
#include "misc.h"
#include "mpconfig.h"
16
#include "qstr.h"
17
18
19
20
21
22
23
24
25
26
27
28
29
#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;

30
STATIC const mp_obj_type_t microsocket_type;
31
32
33
34

// Helper functions
#define RAISE_ERRNO(err_flag, error_val) \
    { if (err_flag == -1) \
35
        { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "[Errno %d]", error_val)); } }
36

37
STATIC mp_obj_socket_t *socket_new(int fd) {
38
    mp_obj_socket_t *o = m_new_obj(mp_obj_socket_t);
39
    o->base.type = &microsocket_type;
40
41
42
43
44
    o->fd = fd;
    return o;
}


45
STATIC void socket_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
46
47
48
49
    mp_obj_socket_t *self = self_in;
    print(env, "<_socket %d>", self->fd);
}

50
STATIC machine_int_t socket_read(mp_obj_t o_in, void *buf, machine_uint_t size, int *errcode) {
51
52
53
54
55
56
57
58
    mp_obj_socket_t *o = o_in;
    machine_int_t r = read(o->fd, buf, size);
    if (r == -1) {
        *errcode = errno;
    }
    return r;
}

59
STATIC machine_int_t socket_write(mp_obj_t o_in, const void *buf, machine_uint_t size, int *errcode) {
60
61
62
63
64
65
66
67
    mp_obj_socket_t *o = o_in;
    machine_int_t r = write(o->fd, buf, size);
    if (r == -1) {
        *errcode = errno;
    }
    return r;
}

68
STATIC mp_obj_t socket_close(mp_obj_t self_in) {
69
70
71
72
    mp_obj_socket_t *self = self_in;
    close(self->fd);
    return mp_const_none;
}
73
STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_close_obj, socket_close);
74

75
STATIC mp_obj_t socket_fileno(mp_obj_t self_in) {
76
    mp_obj_socket_t *self = self_in;
77
    return MP_OBJ_NEW_SMALL_INT((machine_int_t)self->fd);
78
}
79
STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_fileno_obj, socket_fileno);
80

81
STATIC mp_obj_t socket_connect(mp_obj_t self_in, mp_obj_t addr_in) {
82
83
    mp_obj_socket_t *self = self_in;
    buffer_info_t bufinfo;
84
    mp_get_buffer_raise(addr_in, &bufinfo);
85
86
87
88
    int r = connect(self->fd, (const struct sockaddr *)bufinfo.buf, bufinfo.len);
    RAISE_ERRNO(r, errno);
    return mp_const_none;
}
89
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_connect_obj, socket_connect);
90

91
STATIC mp_obj_t socket_bind(mp_obj_t self_in, mp_obj_t addr_in) {
92
93
    mp_obj_socket_t *self = self_in;
    buffer_info_t bufinfo;
94
    mp_get_buffer_raise(addr_in, &bufinfo);
95
96
97
98
    int r = bind(self->fd, (const struct sockaddr *)bufinfo.buf, bufinfo.len);
    RAISE_ERRNO(r, errno);
    return mp_const_none;
}
99
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_bind_obj, socket_bind);
100

101
STATIC mp_obj_t socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) {
102
103
104
105
106
    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;
}
107
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_listen_obj, socket_listen);
108

109
STATIC mp_obj_t socket_accept(mp_obj_t self_in) {
110
111
112
113
114
115
116
117
118
119
120
121
    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;
}
122
STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_accept_obj, socket_accept);
123

124
STATIC mp_obj_t socket_recv(uint n_args, const mp_obj_t *args) {
125
126
127
128
129
130
131
132
    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]);
    }

133
    char *buf = m_new(char, sz);
134
135
136
    int out_sz = recv(self->fd, buf, sz, flags);
    RAISE_ERRNO(out_sz, errno);

137
138
    buf = m_realloc(buf, sz, out_sz);
    return MP_OBJ_NEW_QSTR(qstr_from_strn_take(buf, out_sz, out_sz));
139
}
140
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_recv_obj, 2, 3, socket_recv);
141

142
STATIC mp_obj_t socket_send(uint n_args, const mp_obj_t *args) {
143
144
145
146
147
148
149
    mp_obj_socket_t *self = args[0];
    int flags = 0;

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

150
    uint sz;
151
    const char *buf = mp_obj_str_get_data(args[1], &sz);
152
153
154
    int out_sz = send(self->fd, buf, sz, flags);
    RAISE_ERRNO(out_sz, errno);

155
    return MP_OBJ_NEW_SMALL_INT((machine_int_t)out_sz);
156
}
157
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_send_obj, 2, 3, socket_send);
158

159
STATIC mp_obj_t socket_setsockopt(uint n_args, const mp_obj_t *args) {
160
161
162
163
164
165
166
167
168
169
170
171
    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 {
        buffer_info_t bufinfo;
172
        mp_get_buffer_raise(args[3], &bufinfo);
173
174
175
176
177
178
179
        optval = bufinfo.buf;
        optlen = bufinfo.len;
    }
    int r = setsockopt(self->fd, level, option, optval, optlen);
    RAISE_ERRNO(r, errno);
    return mp_const_none;
}
180
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_setsockopt_obj, 4, 4, socket_setsockopt);
181

182
STATIC mp_obj_t socket_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
    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);
}

205
STATIC const mp_map_elem_t microsocket_locals_dict_table[] = {
206
207
208
209
210
211
212
213
214
215
216
217
218
219
    { 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 },
    { MP_OBJ_NEW_QSTR(MP_QSTR_close), (mp_obj_t)&socket_close_obj },
220
#if MICROPY_SOCKET_EXTRA
221
222
    { 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 },
223
224
225
#endif
};

226
227
STATIC MP_DEFINE_CONST_DICT(microsocket_locals_dict, microsocket_locals_dict_table);

228
229
230
231
232
STATIC const mp_stream_p_t microsocket_stream_p = {
    .read = socket_read,
    .write = socket_write,
};

233
STATIC const mp_obj_type_t microsocket_type = {
234
    { &mp_type_type },
235
    .name = MP_QSTR_socket,
236
237
238
239
    .print = socket_print,
    .make_new = socket_make_new,
    .getiter = NULL,
    .iternext = NULL,
240
    .stream_p = &microsocket_stream_p,
241
    .locals_dict = (mp_obj_t)&microsocket_locals_dict,
242
243
};

244
STATIC mp_obj_t mod_socket_htons(mp_obj_t arg) {
245
    return MP_OBJ_NEW_SMALL_INT((machine_int_t)htons(MP_OBJ_SMALL_INT_VALUE(arg)));
246
}
247
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_socket_htons_obj, mod_socket_htons);
248

249
STATIC mp_obj_t mod_socket_inet_aton(mp_obj_t arg) {
250
    assert(MP_OBJ_IS_TYPE(arg, &mp_type_str));
251
    const char *s = mp_obj_str_get_str(arg);
252
253
    struct in_addr addr;
    if (!inet_aton(s, &addr)) {
254
        nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Invalid IP address"));
255
256
257
258
    }

    return mp_obj_new_int(addr.s_addr);
}
259
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_socket_inet_aton_obj, mod_socket_inet_aton);
260
261

#if MICROPY_SOCKET_EXTRA
262
STATIC mp_obj_t mod_socket_gethostbyname(mp_obj_t arg) {
263
    assert(MP_OBJ_IS_TYPE(arg, &mp_type_str));
264
    const char *s = mp_obj_str_get_str(arg);
265
266
    struct hostent *h = gethostbyname(s);
    if (h == NULL) {
267
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "[Errno %d]", errno));
268
269
270
271
    }
    assert(h->h_length == 4);
    return mp_obj_new_int(*(int*)*h->h_addr_list);
}
272
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_socket_gethostbyname_obj, mod_socket_gethostbyname);
273
274
#endif

275
STATIC mp_obj_t mod_socket_getaddrinfo(uint n_args, const mp_obj_t *args) {
276
277
    // TODO: Implement all args
    assert(n_args == 2);
278
    assert(MP_OBJ_IS_STR(args[0]));
279

280
    const char *host = mp_obj_str_get_str(args[0]);
281
282
283
284
    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])) {
285
286
        int port = (short)MP_OBJ_SMALL_INT_VALUE(args[1]);
        char buf[6];
287
288
289
        sprintf(buf, "%d", port);
        serv = buf;
    } else {
290
        serv = mp_obj_str_get_str(args[1]);
291
292
293
294
295
296
297
298
    }

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

    if (res != 0) {
299
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "[addrinfo error %d]", res));
300
301
302
    }
    assert(addr);

303
    mp_obj_t list = mp_obj_new_list(0, NULL);
304
305
    for (; addr; addr = addr->ai_next) {
        mp_obj_tuple_t *t = mp_obj_new_tuple(5, NULL);
306
307
308
        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);
309
310
311
        // "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) {
312
            t->items[3] = MP_OBJ_NEW_QSTR(qstr_from_str(addr->ai_canonname));
313
314
315
316
        } else {
            t->items[3] = mp_const_none;
        }
        t->items[4] = mp_obj_new_bytearray(addr->ai_addrlen, addr->ai_addr);
317
        mp_obj_list_append(list, t);
318
319
320
    }
    return list;
}
321
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_socket_getaddrinfo_obj, 2, 6, mod_socket_getaddrinfo);
322
323
324

extern mp_obj_type_t sockaddr_in_type;

325
326
#define C(name) { #name, name }

327
STATIC const struct sym_entry {
328
329
330
331
332
333
334
335
336
    const char *sym;
    int val;
} constants[] = {
    C(AF_UNIX),
    C(AF_INET),
    C(AF_INET6),
    C(SOCK_STREAM),
    C(SOCK_DGRAM),
    C(SOCK_RAW),
337
338
339
340
341
342
343
344
345
346
347
348

    C(MSG_DONTROUTE),
    C(MSG_DONTWAIT),

    C(SOL_SOCKET),
    C(SO_BROADCAST),
    C(SO_ERROR),
    C(SO_KEEPALIVE),
    C(SO_LINGER),
    C(SO_REUSEADDR),

    {NULL}
349
350
351
};

#undef C
352

353
354
void microsocket_init() {
    mp_obj_t m = mp_obj_new_module(MP_QSTR_microsocket);
Damien George's avatar
Damien George committed
355
    mp_store_attr(m, MP_QSTR_socket, (mp_obj_t)&microsocket_type);
356
#if MICROPY_SOCKET_EXTRA
Damien George's avatar
Damien George committed
357
358
359
360
    mp_store_attr(m, MP_QSTR_sockaddr_in, (mp_obj_t)&sockaddr_in_type);
    mp_store_attr(m, MP_QSTR_htons, (mp_obj_t)&mod_socket_htons_obj);
    mp_store_attr(m, MP_QSTR_inet_aton, (mp_obj_t)&mod_socket_inet_aton_obj);
    mp_store_attr(m, MP_QSTR_gethostbyname, (mp_obj_t)&mod_socket_gethostbyname_obj);
361
#endif
Damien George's avatar
Damien George committed
362
    mp_store_attr(m, MP_QSTR_getaddrinfo, (mp_obj_t)&mod_socket_getaddrinfo_obj);
363
    for (const struct sym_entry *p = constants; p->sym != NULL; p++) {
Damien George's avatar
Damien George committed
364
        mp_store_attr(m, QSTR_FROM_STR_STATIC(p->sym), MP_OBJ_NEW_SMALL_INT((machine_int_t)p->val));
365
    }
366
}