forked from sustrik/libmill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp.c
413 lines (368 loc) · 11.1 KB
/
tcp.c
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
/*
Copyright (c) 2015 Martin Sustrik
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.
*/
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include "libmill.h"
#include "utils.h"
#define MILL_TCP_LISTEN_BACKLOG 10
#define MILL_TCP_BUFLEN 1500
enum mill_tcptype {
MILL_TCPLISTENER,
MILL_TCPCONN
};
struct tcpsock {
enum mill_tcptype type;
};
struct tcplistener {
struct tcpsock sock;
int fd;
};
struct tcpconn {
struct tcpsock sock;
int fd;
int ifirst;
int ilen;
int olen;
int oerr;
char ibuf[MILL_TCP_BUFLEN];
char obuf[MILL_TCP_BUFLEN];
};
static struct tcpconn *tcpconn_create(int fd) {
struct tcpconn *conn = malloc(sizeof(struct tcpconn));
assert(conn);
conn->sock.type = MILL_TCPCONN;
conn->fd = fd;
conn->ifirst = 0;
conn->ilen = 0;
conn->olen = 0;
conn->oerr = 0;
return conn;
}
static int resolve_ip4_literal_addr(const char *addr,
struct sockaddr_in *addr_in) {
memset(addr_in, 0, sizeof(struct sockaddr_in));
addr_in->sin_family = AF_INET;
char *colon = strrchr(addr, ':');
/* Port. */
int port = 0;
if(colon) {
const char *pos = colon + 1;
while(*pos) {
if(*pos < '0' || *pos > '9') {
errno = EINVAL;
return -1;
}
port *= 10;
port += *pos - '0';
++pos;
}
if(port < 0 || port > 0xffff) {
errno = EINVAL;
return -1;
}
}
addr_in->sin_port = htons(port);
/* Get the IP address part of the string. */
const char *straddr;
char straddrbuf[256];
if(!colon)
straddr = addr;
else {
assert(colon - addr + 1 <= sizeof(straddrbuf));
memcpy(straddrbuf, addr, colon - addr);
straddrbuf[colon - addr] = 0;
straddr = straddrbuf;
}
/* Wildcard address. */
if(strcmp(straddr, "*") == 0) {
addr_in->sin_addr.s_addr = INADDR_ANY;
return 0;
}
/* IPv4 address. */
int rc = inet_pton(AF_INET, straddr, &addr_in->sin_addr);
if(rc != 1) {
errno = EINVAL;
return -1;
}
return 0;
}
tcpsock tcplisten(const char *addr) {
struct sockaddr_in addr_in;
int rc = resolve_ip4_literal_addr(addr, &addr_in);
if (rc != 0)
return NULL;
/* Open the listening socket. */
int s = socket(AF_INET, SOCK_STREAM, 0);
if(s == -1)
return NULL;
/* Make it non-blocking. */
int opt = fcntl(s, F_GETFL, 0);
if (opt == -1)
opt = 0;
rc = fcntl(s, F_SETFL, opt | O_NONBLOCK);
assert(rc != -1);
/* Start listening. */
rc = bind(s, (struct sockaddr*)&addr_in, sizeof(addr_in));
assert(rc != -1);
rc = listen(s, MILL_TCP_LISTEN_BACKLOG);
assert(rc != -1);
/* Create the object. */
struct tcplistener *l = malloc(sizeof(struct tcplistener));
assert(l);
l->sock.type = MILL_TCPLISTENER;
l->fd = s;
return &l->sock;
}
tcpsock tcpaccept(tcpsock s) {
if(s->type != MILL_TCPLISTENER)
mill_panic("trying to accept on a socket that isn't listening");
struct tcplistener *l = (struct tcplistener*)s;
while(1) {
/* Try to get new connection (non-blocking). */
int as = accept(l->fd, NULL, NULL);
if (as >= 0) {
/* Put the newly created connection into non-blocking mode. */
int opt = fcntl(as, F_GETFL, 0);
if (opt == -1)
opt = 0;
int rc = fcntl(as, F_SETFL, opt | O_NONBLOCK);
assert(rc != -1);
/* Create the object. */
return &tcpconn_create(as)->sock;
}
assert(as == -1);
if(errno != EAGAIN && errno != EWOULDBLOCK)
return NULL;
/* Wait till new connection is available. */
int rc = fdwait(l->fd, FDW_IN, -1);
assert(rc == FDW_IN);
}
}
tcpsock tcpconnect(const char *addr) {
struct sockaddr_in addr_in;
int rc = resolve_ip4_literal_addr(addr, &addr_in);
if (rc != 0)
return NULL;
/* Open a socket. */
int s = socket(AF_INET, SOCK_STREAM, 0);
if(s == -1)
return NULL;
/* Make it non-blocking. */
int opt = fcntl(s, F_GETFL, 0);
if (opt == -1)
opt = 0;
rc = fcntl(s, F_SETFL, opt | O_NONBLOCK);
assert(rc != -1);
/* Connect to the remote endpoint. */
rc = connect(s, (struct sockaddr*)&addr_in, sizeof(addr_in));
if(rc != 0) {
assert(rc == -1);
if(errno != EINPROGRESS)
return NULL;
rc = fdwait(s, FDW_OUT, -1);
assert(rc == FDW_OUT);
int err;
socklen_t errsz = sizeof(err);
rc = getsockopt(s, SOL_SOCKET, SO_ERROR, (void*)&err, &errsz);
if(rc != 0) {
err = errno;
close(s);
errno = err;
return NULL;
}
if(err != 0) {
close(s);
errno = err;
return NULL;
}
}
/* Create the object. */
return &tcpconn_create(s)->sock;
}
void tcpsend(tcpsock s, const void *buf, size_t len) {
if(s->type != MILL_TCPCONN)
mill_panic("trying to send to an unconnected socket");
struct tcpconn *conn = (struct tcpconn*)s;
/* If there was already an error don't even try again. */
if(conn->oerr)
return;
/* If it fits into the output buffer copy it there and be done. */
if(conn->olen + len <= MILL_TCP_BUFLEN) {
memcpy(&conn->obuf[conn->olen], buf, len);
conn->olen += len;
return;
}
/* Flush the output buffer. */
tcpflush(s);
/* Try to fit it into the buffer once again. */
if(conn->olen + len <= MILL_TCP_BUFLEN) {
memcpy(&conn->obuf[conn->olen], buf, len);
conn->olen += len;
return;
}
/* The data chunk to send is longer than the output buffer.
Let's do the sending in-place. */
char *pos = (char*)buf;
size_t remaining = len;
while(remaining) {
ssize_t sz = send(conn->fd, pos, remaining, 0);
if(sz == -1) {
if(errno != EAGAIN && errno != EWOULDBLOCK) {
conn->oerr = errno;
return;
}
int rc = fdwait(conn->fd, FDW_OUT, -1);
assert(rc == FDW_OUT);
continue;
}
pos += sz;
remaining -= sz;
}
}
int tcpflush(tcpsock s) {
if(s->type != MILL_TCPCONN)
mill_panic("trying to send to an unconnected socket");
struct tcpconn *conn = (struct tcpconn*)s;
if(conn->oerr) {
errno = conn->oerr;
conn->oerr = 0;
conn->olen = 0;
return -1;
}
if(!conn->olen)
return 0;
char *pos = conn->obuf;
size_t remaining = conn->olen;
while(remaining) {
ssize_t sz = send(conn->fd, pos, remaining, 0);
if(sz == -1) {
if(errno != EAGAIN && errno != EWOULDBLOCK)
return -1;
int rc = fdwait(conn->fd, FDW_OUT, -1);
assert(rc == FDW_OUT);
continue;
}
pos += sz;
remaining -= sz;
}
conn->olen = 0;
return 0;
}
ssize_t tcprecv(tcpsock s, void *buf, size_t len) {
if(s->type != MILL_TCPCONN)
mill_panic("trying to receive from an unconnected socket");
struct tcpconn *conn = (struct tcpconn*)s;
/* If there's enough data in the buffer it's easy. */
if(conn->ilen >= len) {
memcpy(buf, &conn->ibuf[conn->ifirst], len);
conn->ifirst += len;
conn->ilen -= len;
return 0;
}
/* Let's move all the data from the buffer first. */
char *pos = (char*)buf;
size_t remaining = len;
memcpy(pos, &conn->ibuf[conn->ifirst], conn->ilen);
pos += conn->ilen;
remaining -= conn->ilen;
conn->ifirst = 0;
conn->ilen = 0;
assert(remaining);
while(1) {
if(remaining > MILL_TCP_BUFLEN) {
/* If we still have a lot to read try to read it in one go directly
into the destination buffer. */
ssize_t sz = recv(conn->fd, pos, remaining, 0);
assert(sz != 0); // TODO
if(sz == -1) {
assert(errno == EAGAIN && errno == EWOULDBLOCK); // TODO
sz = 0;
}
if(sz == remaining)
return 0;
pos += sz;
remaining -= sz;
}
else {
/* If we have just a little to read try to read the full connection
buffer to minimise the number of system calls. */
ssize_t sz = recv(conn->fd, conn->ibuf, MILL_TCP_BUFLEN, 0);
assert(sz != 0); // TODO
if(sz == -1) {
assert(errno == EAGAIN && errno == EWOULDBLOCK); // TODO
sz = 0;
}
if(sz < remaining) {
memcpy(pos, conn->ibuf, sz);
pos += sz;
remaining -= sz;
conn->ifirst = 0;
conn->ilen = 0;
}
else {
memcpy(pos, conn->ibuf, remaining);
conn->ifirst = remaining;
conn->ilen = sz - remaining;
return 0;
}
}
/* Wait till there's more data to read. */
int res = fdwait(conn->fd, FDW_IN, -1);
assert(res == FDW_IN);
}
}
ssize_t tcprecvuntil(tcpsock s, void *buf, size_t len, char until) {
if(s->type != MILL_TCPCONN)
mill_panic("trying to receive from an unconnected socket");
char *pos = (char*)buf;
size_t i;
for(i = 0; i != len; ++i, ++pos) {
ssize_t res = tcprecv(s, pos, 1);
if (res != 0)
return -1;
if(*pos == until)
return i + 1;
}
return 0;
}
void tcpclose(tcpsock s) {
if(s->type == MILL_TCPLISTENER) {
struct tcplistener *l = (struct tcplistener*)s;
int rc = close(l->fd);
assert(rc == 0);
free(l);
return;
}
if(s->type == MILL_TCPCONN) {
struct tcpconn *c = (struct tcpconn*)s;
int rc = close(c->fd);
assert(rc == 0);
free(c);
return;
}
assert(0);
}