summaryrefslogtreecommitdiff
path: root/server.c
blob: 2ace5b55e459898d0bd76010db075538a8e7dd3c (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
#define _GNU_SOURCE  // usleep, getline
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/select.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include "icmpd.h"
#include "util.h"


int main(void) {
	struct icmpd *server = icmpd_create_server(-1, 0);
	struct icmpd *conn = NULL;

	int server_fd = icmpd_get_select_fd(server);
	int conn_fd = -1;

	while (true) {
		fd_set inset;
		FD_ZERO(&inset);
		FD_SET(0, &inset);
		FD_SET(server_fd, &inset);
		if (conn) FD_SET(conn_fd, &inset);
		int nfds = maxi(0, maxi(server_fd, conn_fd)) + 1;

		int ret = select(nfds, &inset, NULL, NULL, NULL);
		if (ret < 0) {
			if (errno == EINTR) continue;
			perror("select");
			return 1;
		}

		if (ret == 0) continue;  // timeout

		if (FD_ISSET(0, &inset)) {
			char *line = NULL;
			size_t linelen = 0;
			errno = 0;
			ssize_t nr = getline(&line, &linelen, stdin);
			if (nr < 0) {
				if (errno == 0) break;  // EOF
				perror("getline");
				exit(1);
			}
			if (nr > 0) nr--;
			icmpd_send(conn, line, nr);
			free(line);
		}

		if (FD_ISSET(server_fd, &inset) && icmpd_peek(server)) {
			struct icmpd_received msg = icmpd_recv(server);
			printf("Server recv: %zu\n", msg.length);
			xxd(stdout, msg.data, msg.length);

			if (conn) {
				printf("Message received while already connected\n");
				struct icmpd *d = icmpd_create_server(msg.id, msg.source_addr);
				icmpd_server_set_outstanding(d, msg.seqnum);
				icmpd_send(d, msg.data, msg.length);
				icmpd_destroy(d);
			} else {
				conn = icmpd_create_server(msg.id, msg.source_addr);
				icmpd_server_set_outstanding(conn, msg.seqnum);
				conn_fd = icmpd_get_select_fd(conn);

				// icmpd_send(conn, "dankje", 6);
				// icmpd_destroy(conn);
			}

			free(msg.data);
		}

		if (conn && FD_ISSET(conn_fd, &inset) && icmpd_peek(conn)) {
			struct icmpd_received msg = icmpd_recv(conn);
			printf("Connection recv: %zu\n", msg.length);
			xxd(stdout, msg.data, msg.length);
			free(msg.data);
		}
	}
}