summaryrefslogtreecommitdiff
path: root/client.c
blob: f9e97abf1c256e70be1211e71ea82847483589a1 (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
/* SPDX-License-Identifier: Unlicense */

#include "debug.h"
#include "proto.h"
#include "proto_io.h"

#include "timespec/timespec.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
#define OPTPARSE_IMPLEMENTATION
#define OPTPARSE_API static
#include "optparse/optparse.h"
#pragma GCC diagnostic pop

#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>

struct connection {
    int fd;
    uint16_t port;
    uint32_t addr;
    bool connected;
    uint32_t connection_id;
    struct timespec last_syn;
    uint32_t server_roundtrip_prev;
    uint32_t client_roundtrip_prev;
};

static volatile bool g_should_exit = false;
struct connection g_conn = { .fd = -1, };

static inline bool IsDigit(char c) { return c >= '0' && c <= '9'; }

static void HandleFrame(
        struct connection *self,
        struct frame const *frame,
        struct timespec now)
{
    if (frame->type == FT_HANDSHAKE_RESP) {
        self->connection_id = frame->connection_id;
        self->connected = true;
    } else if (frame->type == FT_SYN && self->connected) {
        if (g_log_level >= LOG_LEVEL_DEBUG) {
            fprintf(stderr, "client_rt %5" PRIu32 "\n", self->client_roundtrip_prev);
        }
        struct frame outgoing = *frame;
        outgoing.type = FT_SYNACK,
        outgoing.syn = (struct frame_data_syn){
            .tick = frame->syn.tick,
            .roundtrip_prev = self->client_roundtrip_prev,
            .prev_is_lost = false,
        };
        SendFrame(self->fd, &outgoing);
        self->last_syn = now;
        self->server_roundtrip_prev = frame->syn.roundtrip_prev;
    } else if (frame->type == FT_ACK && self->connected) {
        long const ms = timespec_to_ms(timespec_sub(now, self->last_syn));
        assert(ms >= 0);
        self->client_roundtrip_prev = ms;
    } else if (frame->type == FT_RST) {
        // TODO
    }
}

static uint32_t ParseAddress(char const *str, FILE *log_stream)
{
    uint32_t addr = 0;
    unsigned byte_counter = 0, byte = 0, digits_counter = 0;
    for (size_t i = 0;; i++) {
        char const c = str[i];
        if (c == '\0') {
            if (byte_counter != 3) {
                fprintf(log_stream, "Invalid address specified: %u bytes of 4 expected are specified\n", byte_counter + 1);
                return INADDR_NONE;
            }
            if (digits_counter == 0) {
                fprintf(log_stream, "Invalid address specified: no digits on byte %u\n", byte_counter + 1);
                return INADDR_NONE;
            }
            addr |= byte << (8 * (3 - byte_counter));
            break;
        } else if (IsDigit(c)) {
            digits_counter++;
            if (digits_counter > 3) {
                fprintf(log_stream, "Invalid address specified: too many digits for byte %u\n", byte_counter + 1);
                return INADDR_NONE;
            }
            byte = byte * 10 + (c - '0');
            if (byte > UINT8_MAX) {
                fprintf(log_stream, "Invalid address specified: too big number for byte %u\n", byte_counter + 1);
                return INADDR_NONE;
            }
        } else if (c == '.') {
            if (digits_counter == 0) {
                fprintf(log_stream, "Invalid address specified: no digits on byte %u\n", byte_counter + 1);
                return INADDR_NONE;
            }
            digits_counter = 0;
            addr |= byte << (8 * (3 - byte_counter));
            byte = 0;
            byte_counter++;
            if (byte_counter > 3) {
                fprintf(log_stream, "Invalid address specified: unexpected dot after 4th byte\n");
                return INADDR_NONE;
            }
        } else {
            fprintf(log_stream, "Invalid address specified: char '%c' (0x%02x) is not allowed\n", c, c);
            return INADDR_NONE;
        }
    }
    if (addr == INADDR_NONE) {
        fprintf(log_stream, "Invalid address specified\n");
    }
    return addr;
}

static void sigintHandler(int a)
{
    (void) a;
}

static void PrintUsage(FILE *s, const char *argv0)
{
    // Please, keep all lines in 80 columns range when printed.
    fprintf(s,
    "Usage: %s [options] <address> <port>\n"
    "Options:\n"
    "  -h, --help,           Show this message.\n"
    "  -d, --debug-level=<level>,\n"
    "                        Set id of debug log level: 0 means no logs, \n"
    "                        1 means info, 2 means some debug,\n"
    "                        3 is for maximum trace\n"
    , argv0);
}

int main(int argc, char *argv[])
{
    (void) argc;
    struct optparse_long longopts[] = {
        {"help", 'h', OPTPARSE_NONE},
        {"debug-level", 'd', OPTPARSE_REQUIRED},
        {0},
    };
    struct optparse options;
    optparse_init(&options, argv);
    // Parse opts
    int option;
    while ((option = optparse_long(&options, longopts, NULL)) != -1) {
        switch (option) {
        case 'h':
            PrintUsage(stdout, argv[0]);
            return EXIT_SUCCESS;
            break;
        case 'd':
            g_log_level = atoi(options.optarg);
            break;
        case '?':
            fprintf(stderr, "main: optparse_long: Error: \"%s\"\n", options.errmsg);
            return EXIT_FAILURE;
        }
    }
    char const *const addr_arg = optparse_arg(&options);
    char const *const port_arg = optparse_arg(&options);
    if (addr_arg == NULL || port_arg == NULL) {
        PrintUsage(stdout, argv[0]);
        return EXIT_SUCCESS;
    }
    unsigned const addr = ParseAddress(addr_arg, stderr);
    if (addr == INADDR_NONE) {
        return 1;
    }
    int const port = atoi(port_arg);
    if (port <= 0 || port > UINT16_MAX) {
        fprintf(stderr, "Invalid port specified\n");
        return 1;
    }
    int const fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0) {
        perror("socket failed");
        return 1;
    }
    fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
    g_conn.addr = addr;
    g_conn.port = port;
    g_conn.fd = fd;
    struct frame const handshake = {
        .addr = addr,
        .port = port,
        .type = FT_HANDSHAKE,
        .handshake = {
            .tick_period = 200,
        },
    };
    SendFrame(fd, &handshake);
    struct sigaction sa = { .sa_handler = sigintHandler, };
    sigaction(SIGINT, &sa, NULL);
    struct pollfd fds[1] = { { .fd = fd, .events = POLLIN, }, };
    while (!g_should_exit) {
        int const pollret = poll(fds, sizeof(fds)/sizeof(*fds), -1);
        int const poll_err = errno;
        struct timespec start;
        if (-1 == clock_gettime(CLOCK_MONOTONIC, &start)) {
            int const err = errno;
            fprintf(stderr,
                    "clock_gettime(CLOCK_MONOTONIC, &start) failed (%d): \"%s\"",
                    err, strerror(err));
        }
        if (pollret > 0) {
            if (fds[0].revents & POLLIN) {
                while (1) {
                    struct frame frame = { .type = FT_NONE, };
                    int const ret = ReceiveFrame(fds[0].fd, &frame);
                    if (ret) {
                        break;
                    }
                    HandleFrame(&g_conn, &frame, start);
                }
            }
            if (fds[0].revents & POLLRDNORM) {
                fprintf(stderr, "POLLRDNORM, ignoring...\n");
            }
            if (fds[0].revents & POLLRDBAND) {
                fprintf(stderr, "POLLRDBAND, ignoring...\n");
            }
            if (fds[0].revents & POLLPRI) {
                fprintf(stderr, "POLLPRI, ignoring...\n");
            }
            if (fds[0].revents & POLLPRI) {
                fprintf(stderr, "POLLPRI, ignoring...\n");
            }
            if (fds[0].revents & POLLHUP) {
                fprintf(stderr, "POLLHUP, ignoring...\n");
            }
            if (fds[0].revents & POLLERR) {
                fprintf(stderr, "POLLERR, ignoring...\n");
            }
            if (fds[0].revents & POLLNVAL) {
                fprintf(stderr, "POLLNVAL, exiting...\n");
                return 1;
            }
        } else if (pollret < 0) {
            if (poll_err == EINTR) {
                fprintf(stderr, "SIGINT received\n");
                if (g_conn.connected) {
                    struct frame const rst = {
                        .addr = g_conn.addr,
                        .port = g_conn.port,
                        .type = FT_RST,
                    };
                    SendFrame(g_conn.fd, &rst);
                }
                break;
            }
            fprintf(stderr,
                    "poll() failed (%d): \"%s\"",
                    poll_err, strerror(poll_err));
        }
    }
    close(fd);
}