forked from grundprinzip/libebb
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathebb.c
500 lines (420 loc) · 13.6 KB
/
ebb.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/* This file is part of libebb.
*
* Copyright (c) 2008 Ryan Dahl ([email protected])
* All rights reserved.
*
* 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 <assert.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h> /* TCP_NODELAY */
#include <netinet/in.h> /* inet_ntoa */
#include <arpa/inet.h> /* inet_ntoa */
#include <unistd.h>
#include <stdio.h> /* perror */
#include <errno.h> /* perror */
#include <stdlib.h> /* for the default methods */
#include <ev.h>
#include "ebb.h"
#include "ebb_request_parser.h"
#ifndef TRUE
# define TRUE 1
#endif
#ifndef FALSE
# define FALSE 0
#endif
#ifndef MIN
# define MIN(a,b) (a < b ? a : b)
#endif
#define error(FORMAT, ...) fprintf(stderr, "error: " FORMAT "\n", ##__VA_ARGS__)
#define CONNECTION_HAS_SOMETHING_TO_WRITE (connection->to_write != NULL)
static void
set_nonblock (int fd)
{
int flags = fcntl(fd, F_GETFL, 0);
int r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
assert(0 <= r && "Setting socket non-block failed!");
}
static ssize_t
nosigpipe_push(void *data, const void *buf, size_t len)
{
int fd = (int)(long)data;
int flags = 0;
#ifdef MSG_NOSIGNAL
flags = MSG_NOSIGNAL;
#endif
return send(fd, buf, len, flags);
}
static void
close_connection(ebb_connection *connection)
{
ev_io_stop(connection->server->loop, &connection->read_watcher);
ev_io_stop(connection->server->loop, &connection->write_watcher);
ev_timer_stop(connection->server->loop, &connection->timeout_watcher);
if(0 > close(connection->fd))
error("problem closing connection fd");
connection->open = FALSE;
if(connection->on_close)
connection->on_close(connection);
/* No access to the connection past this point!
* The user is allowed to free in the callback
*/
}
/* Internal callback
* called by connection->timeout_watcher
*/
static void
on_timeout(struct ev_loop *loop, ev_timer *watcher, int revents)
{
ebb_connection *connection = watcher->data;
assert(watcher == &connection->timeout_watcher);
//printf("on_timeout\n");
/* if on_timeout returns true, we don't time out */
if(connection->on_timeout) {
int r = connection->on_timeout(connection);
if(r == EBB_AGAIN) {
ebb_connection_reset_timeout(connection);
return;
}
}
ebb_connection_schedule_close(connection);
}
/* Internal callback
* called by connection->read_watcher
*/
static void
on_readable(struct ev_loop *loop, ev_io *watcher, int revents)
{
ebb_connection *connection = watcher->data;
size_t offset = connection->buffered_data;
int left = EBB_READ_BUFFER - offset;
char* recv_buffer = connection->read_buffer + offset;
ssize_t recved;
//printf("on_readable\n");
// TODO -- why is this broken?
//assert(ev_is_active(&connection->timeout_watcher));
assert(watcher == &connection->read_watcher);
// No more buffer space.
if(left == 0) goto error;
if(EV_ERROR & revents) {
error("on_readable() got error event, closing connection.");
goto error;
}
recved = recv(connection->fd, recv_buffer, left, 0);
if(recved <= 0) goto error;
connection->buffered_data += recved;
ebb_connection_reset_timeout(connection);
ebb_request_parser_execute(&connection->parser, connection->read_buffer,
recved, offset);
if(ebb_request_parser_is_finished(&connection->parser)) {
connection->buffered_data = 0;
}
/* parse error? just drop the client. screw the 400 response */
if(ebb_request_parser_has_error(&connection->parser)) goto error;
return;
error:
ebb_connection_schedule_close(connection);
}
/* Internal callback
* called by connection->write_watcher
*/
static void
on_writable(struct ev_loop *loop, ev_io *watcher, int revents)
{
ebb_connection *connection = watcher->data;
ssize_t sent;
//printf("on_writable\n");
assert(CONNECTION_HAS_SOMETHING_TO_WRITE);
assert(connection->written <= connection->to_write_len);
// TODO -- why is this broken?
//assert(ev_is_active(&connection->timeout_watcher));
assert(watcher == &connection->write_watcher);
if(connection->to_write == 0)
goto stop_writing;
sent = nosigpipe_push( (void*)(long)connection->fd
, connection->to_write + connection->written
, connection->to_write_len - connection->written
);
if(sent < 0) goto error;
if(sent == 0) return;
ebb_connection_reset_timeout(connection);
connection->written += sent;
if(connection->written == connection->to_write_len) {
goto stop_writing;
}
return;
stop_writing:
ev_io_stop(loop, watcher);
connection->to_write = NULL;
if(connection->after_write_cb)
connection->after_write_cb(connection);
return;
error:
error("close connection on write.");
ebb_connection_schedule_close(connection);
}
static void
on_goodbye(struct ev_loop *loop, ev_timer *watcher, int revents)
{
ebb_connection *connection = watcher->data;
assert(watcher == &connection->goodbye_watcher);
close_connection(connection);
}
static ebb_request*
new_request_wrapper(void *data)
{
ebb_connection *connection = data;
if(connection->new_request)
return connection->new_request(connection);
return NULL;
}
/* Internal callback
* Called by server->connection_watcher.
*/
static void
on_connection(struct ev_loop *loop, ev_io *watcher, int revents)
{
ebb_server *server = watcher->data;
//printf("on connection!\n");
assert(server->listening);
assert(server->loop == loop);
assert(&server->connection_watcher == watcher);
if(EV_ERROR & revents) {
error("on_connection() got error event, closing server.");
ebb_server_unlisten(server);
return;
}
struct sockaddr_in addr; // connector's address information
socklen_t addr_len = sizeof(addr);
int fd = accept( server->fd
, (struct sockaddr*) & addr
, & addr_len
);
if(fd < 0) {
if(errno != EAGAIN && errno != EWOULDBLOCK) {
perror("accept()");
}
return;
}
ebb_connection *connection = NULL;
if(server->new_connection)
connection = server->new_connection(server, &addr);
if(connection == NULL) {
close(fd);
return;
}
set_nonblock(fd);
connection->fd = fd;
connection->open = TRUE;
connection->server = server;
memcpy(&connection->sockaddr, &addr, addr_len);
if(server->port[0] != '\0')
connection->ip = inet_ntoa(connection->sockaddr.sin_addr);
#ifdef SO_NOSIGPIPE
int arg = 1;
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &arg, sizeof(int));
#endif
/* Note: not starting the write watcher until there is data to be written */
ev_io_set(&connection->write_watcher, connection->fd, EV_WRITE);
ev_io_set(&connection->read_watcher, connection->fd, EV_READ);
/* XXX: seperate error watcher? */
ev_timer_again(loop, &connection->timeout_watcher);
ev_io_start(loop, &connection->read_watcher);
}
/**
* Begin the server listening on a file descriptor. This DOES NOT start the
* event loop. Start the event loop after making this call.
*/
int
ebb_server_listen_on_fd(ebb_server *server, const int fd)
{
assert(server->listening == FALSE);
if (listen(fd, EBB_MAX_CONNECTIONS) < 0) {
perror("listen()");
return -1;
}
set_nonblock(fd); /* XXX superfluous? */
server->fd = fd;
server->listening = TRUE;
ev_io_set (&server->connection_watcher, server->fd, EV_READ);
ev_io_start (server->loop, &server->connection_watcher);
return server->fd;
}
/**
* Begin the server listening on a file descriptor This DOES NOT start the
* event loop. Start the event loop after making this call.
*/
int
ebb_server_listen_on_port(ebb_server *server, const int port)
{
int fd = -1;
struct linger ling = {0, 0};
struct sockaddr_in addr;
int flags = 1;
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket()");
goto error;
}
flags = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
setsockopt(fd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
/* XXX: Sending single byte chunks in a response body? Perhaps there is a
* need to enable the Nagel algorithm dynamically. For now disabling.
*/
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags));
/* the memset call clears nonstandard fields in some impementations that
* otherwise mess things up.
*/
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind()");
goto error;
}
int ret = ebb_server_listen_on_fd(server, fd);
if (ret >= 0) {
socklen_t len = sizeof(addr);
if (getsockname(fd, (struct sockaddr *)&addr, &len) == -1) {
perror("getsockname");
goto error;
}
sprintf(server->port, "%d", ntohs(addr.sin_port));
}
return ret;
error:
if(fd > 0) close(fd);
return -1;
}
/**
* Stops the server. Will not accept new connections. Does not drop
* existing connections.
*/
void
ebb_server_unlisten(ebb_server *server)
{
if(server->listening) {
ev_io_stop(server->loop, &server->connection_watcher);
close(server->fd);
server->port[0] = '\0';
server->listening = FALSE;
}
}
/**
* Initialize an ebb_server structure. After calling ebb_server_init set
* the callback server->new_connection and, optionally, callback data
* server->data. The new connection MUST be initialized with
* ebb_connection_init before returning it to the server.
*
* @param server the server to initialize
* @param loop a libev loop
*/
void
ebb_server_init(ebb_server *server, struct ev_loop *loop)
{
server->loop = loop;
server->listening = FALSE;
server->port[0] = '\0';
server->fd = -1;
server->connection_watcher.data = server;
ev_init (&server->connection_watcher, on_connection);
server->secure = FALSE;
server->new_connection = NULL;
server->data = NULL;
}
/**
* Initialize an ebb_connection structure. After calling this function you
* must setup callbacks for the different actions the server can take. See
* server.h for which callbacks are availible.
*
* This should be called immediately after allocating space for a new
* ebb_connection structure. Most likely, this will only be called within
* the ebb_server->new_connection callback which you supply.
*
* To provide a better means of storing SSL session caches. libebb provides
* only a simple default implementation.
*
* @param connection the connection to initialize
* @param timeout the timeout in seconds
*/
void
ebb_connection_init(ebb_connection *connection)
{
connection->fd = -1;
connection->server = NULL;
connection->ip = NULL;
connection->open = FALSE;
connection->buffered_data = 0;
ebb_request_parser_init( &connection->parser );
connection->parser.data = connection;
connection->parser.new_request = new_request_wrapper;
ev_init (&connection->write_watcher, on_writable);
connection->write_watcher.data = connection;
connection->to_write = NULL;
ev_init(&connection->read_watcher, on_readable);
connection->read_watcher.data = connection;
ev_timer_init(&connection->goodbye_watcher, on_goodbye, 0., 0.);
connection->goodbye_watcher.data = connection;
ev_timer_init(&connection->timeout_watcher, on_timeout, 0., EBB_DEFAULT_TIMEOUT);
connection->timeout_watcher.data = connection;
connection->new_request = NULL;
connection->on_timeout = NULL;
connection->on_close = NULL;
connection->data = NULL;
}
void
ebb_connection_schedule_close (ebb_connection *connection)
{
ev_timer_start(connection->server->loop, &connection->goodbye_watcher);
}
/*
* Resets the timeout to stay alive for another connection->timeout seconds
*/
void
ebb_connection_reset_timeout(ebb_connection *connection)
{
ev_timer_again(connection->server->loop, &connection->timeout_watcher);
}
/**
* Writes a string to the socket. This is actually sets a watcher
* which may take multiple iterations to write the entire string.
*
* This can only be called once at a time. If you call it again
* while the connection is writing another buffer the ebb_connection_write
* will return FALSE and ignore the request.
*/
int
ebb_connection_write (ebb_connection *connection, const char *buf, size_t len, ebb_after_write_cb cb)
{
if(ev_is_active(&connection->write_watcher))
return FALSE;
assert(!CONNECTION_HAS_SOMETHING_TO_WRITE);
connection->to_write = buf;
connection->to_write_len = len;
connection->written = 0;
connection->after_write_cb = cb;
ev_io_start(connection->server->loop, &connection->write_watcher);
return TRUE;
}