aboutsummaryrefslogtreecommitdiff
path: root/src/server.c
blob: 6c0a7a225ea23c8022ddc4b7ba8b3dcfdce3acd8 (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
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/epoll.h>
#include <assert.h>

#include "server.h"


server_ctx *
server_init_ctx(server_ctx *ctx, init_cb init_fn)
{
    if (!ctx)
        ctx = (server_ctx *) malloc(sizeof(*ctx));
    assert(ctx);

    memset(ctx, 0, sizeof(*ctx));
    if (!init_fn(ctx))
        return NULL;

    return ctx;
}

int server_validate_ctx(const server_ctx *ctx)
{
    assert(ctx);
    assert(ctx->server_cbs.on_connect && ctx->server_cbs.on_disconnect
        && ctx->server_cbs.mainloop);
    assert(ctx->server_cbs.on_free && ctx->server_cbs.on_listen
        && ctx->server_cbs.on_shutdown);
    return 0;
}

int server_setup_epoll(const server_ctx *ctx[], size_t siz)
{
    int s;
    int 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 (int i = 0; i < siz; ++i) {
        memset(&ev, 0, sizeof(ev));
        ev.data.fd = ctx[i]->sock.fd;
        ev.events = EPOLLIN | EPOLLET;

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

    return fd;
}

int server_mainloop_epoll(int epoll_fd, const server_ctx *ctx[], size_t siz)
{
    struct epoll_event *events = calloc(POTD_MAXEVENTS, sizeof(*events));

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

    while (1) {
        int n;

        n = epoll_wait(epoll_fd, events, POTD_MAXEVENTS, -1);
    }

    free(events);
    return 0;
}