aboutsummaryrefslogtreecommitdiff
path: root/src/server.c
blob: afa217217ab78692f0eb1c6fae19e2ce605d120a (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/epoll.h>
#include <pthread.h>
#include <assert.h>

#include "server.h"
#include "socket.h"
#include "utils.h"
#include "log.h"

typedef struct client_thread_args {
    pthread_t self;
    psocket client_psock;
    char host_buf[NI_MAXHOST], service_buf[NI_MAXSERV];
    const server_ctx *server_ctx;
} client_thread_args;

typedef enum connection_state {
    CON_OK, CON_IN_TERMINATED, CON_OUT_TERMINATED,
    CON_IN_ERROR, CON_OUT_ERROR
} connection_state;

static int server_accept_client(server_ctx *ctx[],
                                size_t siz, struct epoll_event *event);
static void *
client_mainloop_epoll(void *arg);
static connection_state
client_io_epoll(struct epoll_event *ev, int dest_fd);
static int
server_mainloop_epoll(int epoll_fd, server_ctx *ctx[], size_t siz);


void server_init_ctx(server_ctx **ctx, forward_ctx *fwd_ctx)
{
    assert(ctx && fwd_ctx);
    if (!*ctx)
        *ctx = (server_ctx *) malloc(sizeof(**ctx));
    assert(*ctx);

    memset(*ctx, 0, sizeof(**ctx));
    (*ctx)->fwd_ctx = fwd_ctx;
}

int server_setup(server_ctx *ctx,
                 const char *listen_addr, const char *listen_port)
{
    int s;
    struct addrinfo *srv_addr = NULL;

    assert(ctx);
    assert(listen_addr || listen_port);

    D2("Try to listen on %s:%s",
       (listen_addr ? listen_addr : "*"), listen_port);
    s = socket_init_in(listen_addr, listen_port, &srv_addr);
    if (s) {
        E_GAIERR(s, "Could not initialise server socket");
        return 1;
    }
    if (socket_bind_in(&ctx->sock, &srv_addr)) {
        E_STRERR("Could not bind server socket");
        return 1;
    }
    if (socket_listen_in(&ctx->sock)) {
        E_STRERR("Could not listen on server socket");
        return 1;
    }

    return 0;
}

int server_validate_ctx(const server_ctx *ctx)
{
    assert(ctx && ctx->fwd_ctx);
    assert(ctx->sock.fd >= 0 && ctx->sock.addr_len > 0);

    return 0;
}

int server_setup_epoll(server_ctx *ctx[], size_t siz)
{
    int s, fd = epoll_create1(0); /* flags == 0 -> obsolete size arg is dropped */
    struct epoll_event ev;

    assert(ctx);
    assert(siz > 0 && siz < POTD_MAXFD);
    if (fd < 0)
        return -1;

    for (size_t i = 0; i < siz; ++i) {
        memset(&ev, 0, sizeof(ev));
        ev.data.fd = ctx[i]->sock.fd;
        ev.events = EPOLLIN | EPOLLET;

        s = socket_addrtostr_in(&ctx[i]->sock,
                                ctx[i]->host_buf, ctx[i]->service_buf);
        if (s) {
            E_GAIERR(s, "Convert socket address to string");
            return -2;
        }
        N("Redirector service listening on %s:%s: %d",
          ctx[i]->host_buf, ctx[i]->service_buf, ev.data.fd);

        s = epoll_ctl(fd, EPOLL_CTL_ADD, ctx[i]->sock.fd, &ev);
        if (s) {
            close(fd);
            return -3;
        }
    }

    return fd;
}

pid_t server_daemonize(int epoll_fd, server_ctx *ctx[], size_t siz)
{
    pid_t p;
    int s;
    size_t i;

    assert(ctx);
    assert(siz > 0); 

    for (i = 0; i < siz; ++i) {
        assert(ctx[i]);
        s = socket_addrtostr_in(&ctx[i]->sock,
                                ctx[i]->host_buf, ctx[i]->service_buf);
        if (s) {
            E_GAIERR(s, "Could not initialise server daemon socket");
            return 1;
        }
    }

    p = fork();
    switch (p) {
        case -1:
            W_STRERR("Server daemonsize");
            return -1;
        case 0:
            N("%s", "Server daemon mainloop");
            server_mainloop_epoll(epoll_fd, ctx, siz);
            break;
    }
    D2("Server daemon pid: %d", p);

    return p;
}

static int server_mainloop_epoll(int epoll_fd, server_ctx *ctx[], size_t siz)
{
    static struct epoll_event *events = NULL;
    sigset_t eset;

    if (!events)
        events = (struct epoll_event *) calloc(POTD_MAXEVENTS, sizeof(*events));

    assert(events);
    assert(ctx);
    assert(siz > 0 && siz < POTD_MAXFD);

    set_procname("[potd] server");
    assert( set_child_sighandler() == 0 );
    sigemptyset(&eset);

    while (1) {
        int n, i;

        n = epoll_pwait(epoll_fd, events, POTD_MAXEVENTS, -1, &eset);
        if (n < 0)
            goto error;

        for (i = 0; i < n; ++i) {
            if ((events[i].events & EPOLLERR) ||
                (events[i].events & EPOLLHUP) ||
                (!(events[i].events & EPOLLIN)))
            {
                E("Epoll for descriptor %d failed", events[i].data.fd);
                E_STRERR("epoll_wait");
                close(events[i].data.fd);
                continue;
            } else {
                if (server_accept_client(ctx, siz, &events[i])) {
                    /* new client connection, accept succeeded */
                    continue;
                }
                W2("Server accept client failed: [fd: %d , npoll: %d]", events[i].data.fd, n);
            }
        }
    }

    return 0;
error:
    return 1;
}

static int server_accept_client(server_ctx *ctx[],
                                size_t siz, struct epoll_event *event)
{
    size_t i;
    int s;
    client_thread_args *args;

    for (i = 0; i < siz; ++i) {
        if (ctx[i]->sock.fd == event->data.fd) {
            args = (client_thread_args *) calloc(1, sizeof(*args));
            assert(args);

            if (socket_accept_in(&ctx[i]->sock, &args->client_psock)) {
                E_STRERR("Could not accept client connection");
                goto error;
            }

            args->server_ctx = ctx[i];
            s = socket_addrtostr_in(&args->client_psock,
                                    args->host_buf, args->service_buf);
            if (s) {
                E_GAIERR(s, "Convert socket address to string");
                goto error;
            }
            N2("New connection from %s:%s to %s:%s: %d",
                args->host_buf, args->service_buf,
                ctx[i]->host_buf, ctx[i]->service_buf,
                args->client_psock.fd);

            if (pthread_create(&args->self, NULL,
                               client_mainloop_epoll, args))
            {
                E_STRERR("Thread creation");
                goto error;
            }

            return 1;
error:
            socket_close(&args->client_psock);
            free(args);
            return 0;
        }
    }

    return 0;
}

static void *
client_mainloop_epoll(void *arg)
{
    client_thread_args *args;
    int s, epoll_fd, dest_fd, active = 1;
    struct epoll_event event = {0,{0}};
    struct epoll_event *events;
    sigset_t eset;
    connection_state cs;
    psocket fwd;

    assert(arg);
    args = (client_thread_args *) arg;
    pthread_detach(args->self);
    events = (struct epoll_event *) calloc(POTD_MAXEVENTS, sizeof(*events));
    assert(events);

    epoll_fd = epoll_create1(0);
    if (epoll_fd < 0) {
        E_STRERR("Client epoll_create1");
        goto finish;
    }

    if (fwd_connect(args->server_ctx->fwd_ctx, &fwd)) {
        E("Forward connection to %s:%s failed",
            args->server_ctx->fwd_ctx->host_buf,
            args->server_ctx->fwd_ctx->service_buf);
        E_STRERR("Forward connect");
        goto finish;
    }
    N("Forwarding connection to %s:%s: %d", args->server_ctx->fwd_ctx->host_buf,
        args->server_ctx->fwd_ctx->service_buf, fwd.fd);

    event.data.fd = fwd.fd;
    event.events = EPOLLIN | EPOLLET;
    s = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fwd.fd, &event);
    if (s) {
        E_STRERR("Forward epoll_ctl");
        goto finish;
    }

    /*
     * We got the client socket from our main thread, so fd flags like
     * O_NONBLOCK are not inherited!
     */
    s = socket_nonblock(&args->client_psock);
    if (s) {
        E_STRERR("socket_nonblock");
        goto finish;
    }
    event.data.fd = args->client_psock.fd;
    event.events = EPOLLIN | EPOLLET;
    s = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, args->client_psock.fd, &event);
    if (s) {
        E_STRERR("Client epoll_ctl");
        goto finish;
    }

    sigemptyset(&eset);
    while (active) {
        int n, i;

        n = epoll_pwait(epoll_fd, events, POTD_MAXEVENTS, -1, &eset);
        if (n < 0)
            break;

        for (i = 0; i < n; ++i) {
            if ((events[i].events & EPOLLERR) ||
                (events[i].events & EPOLLHUP) ||
                (!(events[i].events & EPOLLIN)))
            {
                E("Epoll for descriptor %d failed", events[i].data.fd);
                E_STRERR("epoll_pwait");
                active = 0;
                break;
            } else {
                if (events[i].data.fd == fwd.fd) {
                    dest_fd = args->client_psock.fd;
                } else if (events[i].data.fd == args->client_psock.fd) {
                    dest_fd = fwd.fd;
                } else continue;

                cs = client_io_epoll(&events[i], dest_fd);
                if (cs == CON_OK)
                    continue;

                switch (cs) {
                    case CON_OK:
                        break;
                    case CON_IN_ERROR:
                        N("Lost connection to %s:%s: %d",
                            args->host_buf, args->service_buf,
                            args->client_psock.fd);
                        active = 0;
                        break;
                    case CON_IN_TERMINATED:
                        N("Connection terminated: %s:%s: %d",
                           args->host_buf, args->service_buf,
                           args->client_psock.fd);
                        active = 0;
                        break;
                    case CON_OUT_ERROR:
                        N("Lost forward connection to %s:%s: %d",
                            args->server_ctx->fwd_ctx->host_buf,
                            args->server_ctx->fwd_ctx->service_buf,
                            fwd.fd);
                        active = 0;
                        break;
                    case CON_OUT_TERMINATED:
                        N("Forward connection terminated: %s:%s: %d",
                           args->server_ctx->fwd_ctx->host_buf,
                           args->server_ctx->fwd_ctx->service_buf,
                           fwd.fd);
                        active = 0;
                        break;
                }
                if (!active)
                    break;
            }
            W2("I/O forwarder failed: [fd: %d , npoll: %d]", events[i].data.fd, n);
        }
    }

finish:
    close(epoll_fd);
    socket_close(&fwd);
    socket_close(&args->client_psock);
    free(events);
    free(args);
    return NULL;
}

static connection_state
client_io_epoll(struct epoll_event *ev, int dest_fd)
{
    int data_avail = 1;
    int has_input;
    int saved_errno;
    connection_state rc = CON_OK;
    ssize_t siz;
    char buf[BUFSIZ+sizeof(long)];

    while (data_avail) {
        has_input = 0;
        saved_errno = 0;
        siz = -1;

        if (ev->events & EPOLLIN) {
            has_input = 1;
            errno = 0;
            siz = read(ev->data.fd, &buf[0], BUFSIZ);
            saved_errno = errno;
        } else break;
        if (saved_errno == EAGAIN)
            break;

        switch (siz) {
            case -1:
                E_STRERR("Client read");
                rc = CON_IN_ERROR;
                break;
            case 0:
                rc = CON_IN_TERMINATED;
                break;
            default:
                buf[siz] = 0;
                D2("Read %lu bytes from fd %d", siz, ev->data.fd);
                break;
        }

        if (rc != CON_OK)
            break;

        if (has_input) {
            siz = write(dest_fd, &buf[0], siz);

            switch (siz) {
                case -1:
                    rc = CON_OUT_ERROR;
                    break;
                case 0:
                    rc = CON_OUT_TERMINATED;
                    break;
                default:
                    D2("Written %lu bytes from fd %d to fd %d",
                        siz, ev->data.fd, dest_fd);
                    break;
            }
        }

        if (rc != CON_OK)
            break;
    }

    D2("Connection state: %d", rc);
    return rc;
}