summaryrefslogtreecommitdiffstats
path: root/nserver/src/nserve.c
blob: 3d27c1962803fb02c60125aef1746f874b1d56f8 (plain) (blame)
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
#include <nserve.h>

int slurpsock(char *buf, size_t buf_sz, int sock)
{
    ssize_t bytes;

    bytes = recv(sock, buf, buf_sz, 0);
    check(bytes >= 0, "Failed to read from socket: %d", sock);

    return bytes;

 error:
    return -1;
}

int barfsock(char *buf, size_t buf_sz, int sock)
{
    ssize_t bytes = 0;

    bytes = send(sock, buf, buf_sz, 0);
    check(bytes >= 0, "barfsock: send failed");

    return bytes;
 error:
    return -1;
}

void nserve(int sock)
{
    size_t buf_sz = 200;
    char *buf = calloc(sizeof(char), buf_sz);
    check_mem(buf);

    // Read command from socket.
    ssize_t bytes = slurpsock(buf, buf_sz, sock);
    check(bytes >= 0, "nserve: slurpsock failed");

    // Write response to socket.
    int rc = barfsock(buf, bytes, sock);
    check(rc != -1, "nserve: echo failed");

    // Close socket.
    rc = close(sock);
    check(rc == 0, "nserve: close failed");

    // Cleanup.
    free(buf)

    exit(0);
 error:
    rc = close(sock);
    check(rc == 0, "nserve: close failed");

    // Cleanup if needed.
    if (buf)
        free(buf);

    exit(1);
}