summaryrefslogtreecommitdiffstats
path: root/src/fastd.c
blob: 6ce10fcb09060ed3df312c68fc684be84a331773 (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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
/*
  Copyright (c) 2012-2013, Matthias Schiffer <mschiffer@universe-factory.net>
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#include "fastd.h"
#include "crypto.h"
#include "handshake.h"
#include "peer.h"

#include <fcntl.h>
#include <grp.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <syslog.h>
#include <sys/resource.h>


static volatile bool sighup = false;
static volatile bool terminate = false;
static volatile bool dump = false;


static void on_sighup(int signo UNUSED) {
	sighup = true;
}

static void on_terminate(int signo UNUSED) {
	terminate = true;
}

static void on_sigusr1(int signo UNUSED) {
	dump = true;
}

static void init_signals(fastd_context_t *ctx) {
	struct sigaction action;

	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);

	action.sa_handler = on_sighup;
	if(sigaction(SIGHUP, &action, NULL))
		exit_errno(ctx, "sigaction");

	action.sa_handler = on_terminate;
	if(sigaction(SIGTERM, &action, NULL))
		exit_errno(ctx, "sigaction");
	if(sigaction(SIGQUIT, &action, NULL))
		exit_errno(ctx, "sigaction");
	if(sigaction(SIGINT, &action, NULL))
		exit_errno(ctx, "sigaction");

	action.sa_handler = on_sigusr1;
	if(sigaction(SIGUSR1, &action, NULL))
		exit_errno(ctx, "sigaction");

	action.sa_handler = SIG_IGN;
	if(sigaction(SIGPIPE, &action, NULL))
		exit_errno(ctx, "sigaction");
}

static void init_pipes(fastd_context_t *ctx) {
	int pipefd[2];

	if (pipe(pipefd))
		exit_errno(ctx, "pipe");

	fastd_setfd(ctx, pipefd[0], FD_CLOEXEC, 0);
	fastd_setfd(ctx, pipefd[1], FD_CLOEXEC, 0);

	ctx->resolverfd = pipefd[0];
	ctx->resolvewfd = pipefd[1];
}

static void init_log(fastd_context_t *ctx) {
	uid_t uid = geteuid();
	gid_t gid = getegid();

	if (ctx->conf->user || ctx->conf->group) {
		if (setegid(ctx->conf->gid) < 0)
			pr_debug_errno(ctx, "setegid");
		if (seteuid(ctx->conf->uid) < 0)
			pr_debug_errno(ctx, "seteuid");
	}

	if (ctx->conf->log_syslog_level > LL_UNSPEC)
		openlog(ctx->conf->log_syslog_ident, LOG_PID, LOG_DAEMON);

	fastd_log_file_t *config;
	for (config = ctx->conf->log_files; config; config = config->next) {
		fastd_log_fd_t *file = malloc(sizeof(fastd_log_fd_t));

		file->config = config;
		file->fd = open(config->filename, O_WRONLY|O_APPEND|O_CREAT, 0600);

		file->next = ctx->log_files;
		ctx->log_files = file;
	}

	if (seteuid(uid) < 0)
		pr_debug_errno(ctx, "seteuid");
	if (setegid(gid) < 0)
		pr_debug_errno(ctx, "setegid");
}

static void close_log(fastd_context_t *ctx) {
	while (ctx->log_files) {
		fastd_log_fd_t *next = ctx->log_files->next;

		close(ctx->log_files->fd);
		free(ctx->log_files);

		ctx->log_files = next;
	}

	closelog();
}

static void crypto_init(fastd_context_t *ctx UNUSED) {
#ifdef USE_CRYPTO_AES128CTR
	ctx->crypto_aes128ctr = ctx->conf->crypto_aes128ctr->init(ctx);
	if (!ctx->crypto_aes128ctr)
		exit_error(ctx, "Unable to initialize AES128-CTR implementation");
#endif

#ifdef USE_CRYPTO_GHASH
	ctx->crypto_ghash = ctx->conf->crypto_ghash->init(ctx);
	if (!ctx->crypto_ghash)
		exit_error(ctx, "Unable to initialize GHASH implementation");
#endif
}

static void crypto_free(fastd_context_t *ctx UNUSED) {
#ifdef USE_CRYPTO_AES128CTR
	ctx->conf->crypto_aes128ctr->free(ctx, ctx->crypto_aes128ctr);
	ctx->crypto_aes128ctr = NULL;
#endif

#ifdef USE_CRYPTO_GHASH
	ctx->conf->crypto_ghash->free(ctx, ctx->crypto_ghash);
	ctx->crypto_ghash = NULL;
#endif
}


static void init_sockets(fastd_context_t *ctx) {
	ctx->socks = malloc(ctx->conf->n_bind_addrs * sizeof(fastd_socket_t));

	unsigned i;
	fastd_bind_address_t *addr = ctx->conf->bind_addrs;
	for (i = 0; i < ctx->conf->n_bind_addrs; i++) {
		ctx->socks[i] = (fastd_socket_t){ .fd = -2, .addr = addr };

		if (addr == ctx->conf->bind_addr_default_v4)
			ctx->sock_default_v4 = &ctx->socks[i];

		if (addr == ctx->conf->bind_addr_default_v6)
			ctx->sock_default_v6 = &ctx->socks[i];

		addr = addr->next;
	}

	ctx->n_socks = ctx->conf->n_bind_addrs;
}


void fastd_setfd(const fastd_context_t *ctx, int fd, int set, int unset) {
	int flags = fcntl(fd, F_GETFD);
	if (flags < 0)
		exit_errno(ctx, "Getting file descriptor flags failed: fcntl");

	if (fcntl(fd, F_SETFD, (flags|set) & (~unset)) < 0)
		exit_errno(ctx, "Setting file descriptor flags failed: fcntl");
}

void fastd_setfl(const fastd_context_t *ctx, int fd, int set, int unset) {
	int flags = fcntl(fd, F_GETFL);
	if (flags < 0)
		exit_errno(ctx, "Getting file status flags failed: fcntl");

	if (fcntl(fd, F_SETFL, (flags|set) & (~unset)) < 0)
		exit_errno(ctx, "Setting file status flags failed: fcntl");
}

static void close_sockets(fastd_context_t *ctx) {
	unsigned i;
	for (i = 0; i < ctx->n_socks; i++)
		fastd_socket_close(ctx, &ctx->socks[i]);

	free(ctx->socks);
}

static inline void handle_forward(fastd_context_t *ctx, fastd_peer_t *source_peer, fastd_buffer_t buffer) {
	const fastd_eth_addr_t *dest_addr = fastd_get_dest_address(ctx, buffer);

	if (fastd_eth_addr_is_unicast(dest_addr)) {
		fastd_peer_t *dest_peer = fastd_peer_find_by_eth_addr(ctx, dest_addr);

		if (!dest_peer || dest_peer == source_peer || !fastd_peer_is_established(dest_peer)) {
			fastd_buffer_free(buffer);
			return;
		}

		ctx->conf->protocol->send(ctx, dest_peer, buffer);
	}
	else {
		fastd_send_all(ctx, source_peer, buffer);
	}
}

void fastd_handle_receive(fastd_context_t *ctx, fastd_peer_t *peer, fastd_buffer_t buffer) {
	if (ctx->conf->mode == MODE_TAP) {
		if (buffer.len < ETH_HLEN) {
			pr_debug(ctx, "received truncated packet");
			fastd_buffer_free(buffer);
			return;
		}

		const fastd_eth_addr_t *src_addr = fastd_get_source_address(ctx, buffer);

		if (fastd_eth_addr_is_unicast(src_addr))
			fastd_peer_eth_addr_add(ctx, peer, src_addr);
	}

	fastd_tuntap_write(ctx, buffer);

	if (ctx->conf->mode == MODE_TAP && ctx->conf->forward) {
		handle_forward(ctx, peer, buffer);
		return;
	}

	fastd_buffer_free(buffer);
}

static inline void on_pre_up(fastd_context_t *ctx) {
	if (!ctx->conf->on_pre_up)
		return;

	fastd_shell_exec(ctx, ctx->conf->on_pre_up, ctx->conf->on_pre_up_dir, NULL, NULL, NULL, NULL);
}

static inline void on_up(fastd_context_t *ctx) {
	if (!ctx->conf->on_up)
		return;

	fastd_shell_exec(ctx, ctx->conf->on_up, ctx->conf->on_up_dir, NULL, NULL, NULL, NULL);
}

static inline void on_down(fastd_context_t *ctx) {
	if (!ctx->conf->on_down)
		return;

	fastd_shell_exec(ctx, ctx->conf->on_down, ctx->conf->on_down_dir, NULL, NULL, NULL, NULL);
}

static inline void on_post_down(fastd_context_t *ctx) {
	if (!ctx->conf->on_post_down)
		return;

	fastd_shell_exec(ctx, ctx->conf->on_post_down, ctx->conf->on_post_down_dir, NULL, NULL, NULL, NULL);
}

static fastd_peer_group_t* init_peer_group(const fastd_peer_group_config_t *config, fastd_peer_group_t *parent) {
	fastd_peer_group_t *ret = calloc(1, sizeof(fastd_peer_group_t));

	ret->conf = config;
	ret->parent = parent;

	fastd_peer_group_t **children = &ret->children;
	fastd_peer_group_config_t *child_config;

	for (child_config = config->children; child_config; child_config = child_config->next) {
		*children = init_peer_group(child_config, ret);
		children = &(*children)->next;
	}

	return ret;
}

static void init_peer_groups(fastd_context_t *ctx) {
	ctx->peer_group = init_peer_group(ctx->conf->peer_group, NULL);
}

static void free_peer_group(fastd_peer_group_t *group) {
	while (group->children) {
		fastd_peer_group_t *child = group->children;
		group->children = group->children->next;

		free_peer_group(child);
	}

	free(group);
}

static void delete_peer_groups(fastd_context_t *ctx) {
	free_peer_group(ctx->peer_group);
}

static void init_peers(fastd_context_t *ctx) {
	fastd_peer_config_t *peer_conf;
	for (peer_conf = ctx->conf->peers; peer_conf; peer_conf = peer_conf->next)
		ctx->conf->protocol->peer_configure(ctx, peer_conf);

	for (peer_conf = ctx->conf->peers; peer_conf; peer_conf = peer_conf->next) {
		bool enable = ctx->conf->protocol->peer_check(ctx, peer_conf);

		if (enable && !peer_conf->enabled)
			fastd_peer_add(ctx, peer_conf);

		peer_conf->enabled = enable;
	}

	fastd_peer_t *peer, *next;
	for (peer = ctx->peers; peer; peer = next) {
		next = peer->next;

		if (peer->config) {
			if (!peer->config->enabled) {
				pr_info(ctx, "previously enabled peer %P disabled, deleting.", peer);
				fastd_peer_delete(ctx, peer);
			}
		}
		else {
			if (!ctx->conf->protocol->peer_check_temporary(ctx, peer))
				fastd_peer_delete(ctx, peer);
		}
	}
}

static void delete_peers(fastd_context_t *ctx) {
	fastd_peer_t *peer, *next;
	for (peer = ctx->peers; peer; peer = next) {
		next = peer->next;

		fastd_peer_delete(ctx, peer);
	}
}

static void dump_peers(fastd_context_t *ctx) {
	pr_info(ctx, "dumping peers...");

	fastd_peer_t *peer;
	for (peer = ctx->peers; peer; peer = peer->next) {
		if (!fastd_peer_is_established(peer)) {
			pr_info(ctx, "peer %P not connected, address: %I", peer, &peer->address);
			continue;
		}

		if (ctx->conf->mode == MODE_TAP) {
			unsigned int eth_addresses = 0;
			size_t i;
			for (i = 0; i < ctx->n_eth_addr; i++) {
				if (ctx->eth_addr[i].peer == peer)
					eth_addresses++;
			}

			pr_info(ctx, "peer %P connected, address: %I, associated MAC addresses: %u", peer, &peer->address, eth_addresses);
		}
		else {
			pr_info(ctx, "peer %P connected, address: %I", peer, &peer->address);
		}
	}

	pr_info(ctx, "peer dump finished.");
}

static inline void update_time(fastd_context_t *ctx) {
	clock_gettime(CLOCK_MONOTONIC, &ctx->now);
}

static void send_handshake(fastd_context_t *ctx, fastd_peer_t *peer) {
	if (!fastd_peer_is_established(peer)) {
		if (!peer->next_remote)
			exit_bug(ctx, "send_handshake: no remote");

		fastd_peer_claim_address(ctx, peer, NULL, NULL, &peer->next_remote->address);
		fastd_peer_reset_socket(ctx, peer);
	}

	if (!peer->sock)
		return;

	if (peer->address.sa.sa_family == AF_UNSPEC) {
		pr_debug(ctx, "not sending a handshake to %P (no valid address resolved)", peer);
		return;
	}

	if (timespec_diff(&ctx->now, &peer->last_handshake) < (int)ctx->conf->min_handshake_interval*1000
	    && fastd_peer_address_equal(&peer->address, &peer->last_handshake_address)) {
		pr_debug(ctx, "not sending a handshake to %P as we sent one a short time ago", peer);
		return;
	}

	pr_debug(ctx, "sending handshake to %P[%I]...", peer, &peer->address);
	peer->last_handshake = ctx->now;
	peer->last_handshake_address = peer->address;
	ctx->conf->protocol->handshake_init(ctx, peer->sock, &peer->local_address, &peer->address, peer);
}

static void handle_handshake_queue(fastd_context_t *ctx) {
	if (!ctx->handshake_queue.next)
		return;

	fastd_peer_t *peer = container_of(ctx->handshake_queue.next, fastd_peer_t, handshake_entry);
	if (timespec_after(&peer->next_handshake, &ctx->now))
		return;

	fastd_peer_schedule_handshake_default(ctx, peer);

	if (!fastd_peer_may_connect(ctx, peer)) {
		peer->next_remote = peer->remotes;
		return;
	}

	send_handshake(ctx, peer);

	if (fastd_peer_is_established(peer))
		return;

	peer->next_remote = peer->next_remote->next;
	if (!peer->next_remote)
		peer->next_remote = peer->remotes;

	if (fastd_remote_is_dynamic(peer->next_remote))
		fastd_resolve_peer(ctx, peer, peer->next_remote);
}

static inline bool handle_tun_tap(fastd_context_t *ctx, fastd_buffer_t buffer) {
	if (ctx->conf->mode != MODE_TAP)
		return false;

	if (buffer.len < ETH_HLEN) {
		pr_debug(ctx, "truncated packet on tap interface");
		fastd_buffer_free(buffer);
		return true;
	}

	const fastd_eth_addr_t *dest_addr = fastd_get_dest_address(ctx, buffer);
	if (!fastd_eth_addr_is_unicast(dest_addr))
		return false;

	fastd_peer_t *peer = fastd_peer_find_by_eth_addr(ctx, dest_addr);

	if (!peer || !fastd_peer_is_established(peer)) {
		fastd_buffer_free(buffer);
		return true;
	}

	ctx->conf->protocol->send(ctx, peer, buffer);
	return true;
}

static void handle_tun(fastd_context_t *ctx) {
	fastd_buffer_t buffer = fastd_tuntap_read(ctx);
	if (!buffer.len)
		return;

	if (handle_tun_tap(ctx, buffer))
		return;

	/* TUN mode or multicast packet */
	fastd_send_all(ctx, NULL, buffer);
}

static void handle_resolve_returns(fastd_context_t *ctx) {
	fastd_resolve_return_t resolve_return;

	while (read(ctx->resolverfd, &resolve_return, sizeof(resolve_return)) < 0) {
		if (errno != EINTR)
			exit_errno(ctx, "handle_resolve_return: read");
	}

	fastd_peer_t *peer;
	for (peer = ctx->peers; peer; peer = peer->next) {
		if (!peer->config)
			continue;

		fastd_remote_t *remote;
		for (remote = peer->remotes; remote; remote = remote->next) {
			if (remote == resolve_return.remote)
				break;
		}

		if (!remote)
			continue;

		fastd_peer_handle_resolve(ctx, peer, remote, &resolve_return.addr);

		break;
	}

	fastd_remote_unref(resolve_return.remote);
}

static inline int handshake_timeout(fastd_context_t *ctx) {
	if (!ctx->handshake_queue.next)
		return -1;

       fastd_peer_t *peer = container_of(ctx->handshake_queue.next, fastd_peer_t, handshake_entry);

       int diff_msec = timespec_diff(&peer->next_handshake, &ctx->now);
       if (diff_msec < 0)
	       return 0;
       else
	       return diff_msec;
}

static void handle_input(fastd_context_t *ctx) {
	const size_t n_fds = 2 + ctx->n_socks + ctx->n_peers;
	struct pollfd fds[n_fds];
	fds[0].fd = ctx->tunfd;
	fds[0].events = POLLIN;
	fds[1].fd = ctx->resolverfd;
	fds[1].events = POLLIN;

	unsigned i;
	for (i = 2; i < ctx->n_socks+2; i++) {
		fds[i].fd = ctx->socks[i-2].fd;
		fds[i].events = POLLIN;
	}

	fastd_peer_t *peer;
	for (peer = ctx->peers; peer; peer = peer->next) {
		if (peer->sock && fastd_peer_is_socket_dynamic(peer))
			fds[i].fd = peer->sock->fd;
		else
			fds[i].fd = -1;

		fds[i].events = POLLIN;

		i++;
	}

	if (i != n_fds)
		exit_bug(ctx, "fd count mismatch");

	int keepalive_timeout = timespec_diff(&ctx->next_keepalives, &ctx->now);

	if (keepalive_timeout < 0)
		keepalive_timeout = 0;

	int timeout = handshake_timeout(ctx);
	if (timeout < 0 || timeout > keepalive_timeout)
		timeout = keepalive_timeout;

	int ret = poll(fds, n_fds, timeout);
	if (ret < 0) {
		if (errno == EINTR)
			return;

		exit_errno(ctx, "poll");
	}

	update_time(ctx);

	if (fds[0].revents & POLLIN)
		handle_tun(ctx);
	if (fds[1].revents & POLLIN)
		handle_resolve_returns(ctx);

	for (i = 2; i < ctx->n_socks+2; i++) {
		if (fds[i].revents & (POLLERR|POLLHUP|POLLNVAL))
			fastd_socket_error(ctx, &ctx->socks[i-2]);
		else if (fds[i].revents & POLLIN)
			fastd_receive(ctx, &ctx->socks[i-2]);
	}

	for (peer = ctx->peers; peer; peer = peer->next) {
		if (fds[i].revents & (POLLERR|POLLHUP|POLLNVAL))
			fastd_peer_reset_socket(ctx, peer);
		else if (fds[i].revents & POLLIN)
			fastd_receive(ctx, peer->sock);

		i++;
	}

	if (i != n_fds)
		exit_bug(ctx, "fd count mismatch");
}

static void cleanup_peers(fastd_context_t *ctx) {
	fastd_peer_t *peer, *next;

	for (peer = ctx->peers; peer; peer = next) {
		next = peer->next;

		if (fastd_peer_is_temporary(peer) || fastd_peer_is_established(peer)) {
			if (timespec_diff(&ctx->now, &peer->seen) > (int)ctx->conf->peer_stale_time*1000) {
				if (fastd_peer_is_temporary(peer)) {
					fastd_peer_delete(ctx, peer);
				}
				else {
					fastd_peer_reset(ctx, peer);
				}
			}
		}
	}
}

static void maintenance(fastd_context_t *ctx) {
	while (ctx->peers_temp) {
		fastd_peer_t *peer = ctx->peers_temp;
		ctx->peers_temp = ctx->peers_temp->next;

		fastd_peer_enable_temporary(ctx, peer);
	}

	cleanup_peers(ctx);
	fastd_peer_eth_addr_cleanup(ctx);

	fastd_socket_handle_binds(ctx);

	if (timespec_after(&ctx->now, &ctx->next_keepalives)) {
		fastd_peer_t *peer;
		for (peer = ctx->peers; peer; peer = peer->next) {
			if (!fastd_peer_is_established(peer))
				continue;

			if (timespec_diff(&ctx->now, &peer->last_send) < (int)ctx->conf->keepalive_timeout*1000)
				continue;

			pr_debug2(ctx, "sending keepalive to %P", peer);
			ctx->conf->protocol->send(ctx, peer, fastd_buffer_alloc(ctx, 0, ctx->conf->min_encrypt_head_space, ctx->conf->min_encrypt_tail_space));
		}

		ctx->next_keepalives.tv_sec += ctx->conf->keepalive_interval;
	}
}


static void close_fds(fastd_context_t *ctx) {
	struct rlimit rl;
	int fd, maxfd;

	if (getrlimit(RLIMIT_NOFILE, &rl) > 0)
		maxfd = (int)rl.rlim_max;
	else
		maxfd = sysconf(_SC_OPEN_MAX);

	for (fd = 3; fd < maxfd; fd++) {
		if (close(fd) < 0) {
			if (errno == EINTR) {
				fd--;
				continue;
			}

			if (errno != EBADF)
				pr_error_errno(ctx, "close");
		}
	}
}

static void write_pid(fastd_context_t *ctx, pid_t pid) {
	if (!ctx->conf->pid_file)
		return;

	uid_t uid = geteuid();
	gid_t gid = getegid();

	if (ctx->conf->user || ctx->conf->group) {
		if (setegid(ctx->conf->gid) < 0)
			pr_debug_errno(ctx, "setegid");
		if (seteuid(ctx->conf->uid) < 0)
			pr_debug_errno(ctx, "seteuid");
	}

	int fd = open(ctx->conf->pid_file, O_WRONLY|O_CREAT|O_TRUNC, 0666);
	if (fd < 0) {
		pr_error_errno(ctx, "can't write PID file: open");
		goto end;
	}

	if (dprintf(fd, "%i", pid) < 0)
		pr_error_errno(ctx, "can't write PID file: dprintf");

	if (close(fd) < 0)
		pr_warn_errno(ctx, "close");

 end:
	if (seteuid(uid) < 0)
		pr_debug_errno(ctx, "seteuid");
	if (setegid(gid) < 0)
		pr_debug_errno(ctx, "setegid");
}

static void set_user(fastd_context_t *ctx) {
	if (ctx->conf->user || ctx->conf->group) {
		if (setgid(ctx->conf->gid) < 0)
			exit_errno(ctx, "setgid");

		if (setuid(ctx->conf->uid) < 0)
			exit_errno(ctx, "setuid");

		pr_info(ctx, "Changed to UID %i, GID %i.", ctx->conf->uid, ctx->conf->gid);
	}
}

static void set_groups(fastd_context_t *ctx) {
	if (ctx->conf->groups) {
		if (setgroups(ctx->conf->n_groups, ctx->conf->groups) < 0) {
			if (errno != EPERM)
				pr_debug_errno(ctx, "setgroups");
		}
	}
	else if (ctx->conf->user || ctx->conf->group) {
		if (setgroups(1, &ctx->conf->gid) < 0) {
			if (errno != EPERM)
				pr_debug_errno(ctx, "setgroups");
		}
	}
}

static void drop_caps(fastd_context_t *ctx) {
	set_user(ctx);
	fastd_cap_drop(ctx);
}

int main(int argc, char *argv[]) {
	fastd_context_t ctx = {};

	close_fds(&ctx);

	fastd_random_bytes(&ctx, &ctx.randseed, sizeof(ctx.randseed), false);

	init_pipes(&ctx);

	fastd_config_t conf;
	fastd_configure(&ctx, &conf, argc, argv);

	init_log(&ctx);

	if (conf.generate_key) {
		conf.protocol->generate_key(&ctx);
		exit(0);
	}

	init_signals(&ctx);

	conf.protocol_config = conf.protocol->init(&ctx);

	if (conf.show_key) {
		conf.protocol->show_key(&ctx);
		exit(0);
	}

	update_time(&ctx);

	conf.long_ago = ctx.now;
	conf.long_ago.tv_sec -= 86400; /* 24h in the past */

	ctx.next_keepalives = ctx.now;
	ctx.next_keepalives.tv_sec += conf.keepalive_interval;

	pr_info(&ctx, "fastd " FASTD_VERSION " starting");

	fastd_cap_init(&ctx);

	/* change groups early as the can be relevant for file access (for PID file & log files) */
	set_groups(&ctx);

	crypto_init(&ctx);

	init_sockets(&ctx);

	if (!fastd_socket_handle_binds(&ctx))
		exit_error(&ctx, "unable to bind default socket");

	on_pre_up(&ctx);

	fastd_tuntap_open(&ctx);

	init_peer_groups(&ctx);
	if (conf.daemon) {
		pid_t pid = fork();
		if (pid < 0) {
			exit_errno(&ctx, "fork");
		}
		else if (pid > 0) {
			write_pid(&ctx, pid);
			exit(0);
		}

		if (setsid() < 0)
			pr_error_errno(&ctx, "setsid");
	}
	else {
		write_pid(&ctx, getpid());
	}

	if (conf.drop_caps == DROP_CAPS_EARLY)
		drop_caps(&ctx);

	on_up(&ctx);

	if (conf.drop_caps == DROP_CAPS_ON)
		drop_caps(&ctx);
	else if (conf.drop_caps == DROP_CAPS_OFF)
		set_user(&ctx);

	fastd_config_load_peer_dirs(&ctx, &conf);
	init_peers(&ctx);

	while (!terminate) {
		handle_handshake_queue(&ctx);

		handle_input(&ctx);

		maintenance(&ctx);

		sigset_t set, oldset;
		sigemptyset(&set);
		pthread_sigmask(SIG_SETMASK, &set, &oldset);

		if (sighup) {
			sighup = false;

			pr_info(&ctx, "reconfigure triggered");

			close_log(&ctx);
			init_log(&ctx);

			fastd_config_load_peer_dirs(&ctx, &conf);
			init_peers(&ctx);
		}

		if (dump) {
			dump = false;
			dump_peers(&ctx);
		}

		pthread_sigmask(SIG_SETMASK, &oldset, NULL);
	}

	on_down(&ctx);

	delete_peers(&ctx);
	delete_peer_groups(&ctx);

	fastd_tuntap_close(&ctx);
	close_sockets(&ctx);

	on_post_down(&ctx);

	free(ctx.protocol_state);
	free(ctx.eth_addr);
	free(ctx.ifname);

	crypto_free(&ctx);

	close_log(&ctx);
	fastd_config_release(&ctx, &conf);

	return 0;
}