summaryrefslogtreecommitdiff
path: root/sbin/dhcpleased/frontend.c
blob: 9246960512e73c5d7a5c03c2bde17828059bfd79 (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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
/*	$OpenBSD: frontend.c,v 1.14 2021/07/26 09:26:36 florian Exp $	*/

/*
 * Copyright (c) 2017, 2021 Florian Obser <florian@openbsd.org>
 * Copyright (c) 2005 Claudio Jeker <claudio@openbsd.org>
 * Copyright (c) 2004 Esben Norby <norby@openbsd.org>
 * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/queue.h>
#include <sys/socket.h>
#include <sys/syslog.h>
#include <sys/uio.h>

#include <net/bpf.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_types.h>
#include <net/route.h>

#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <netinet/ip.h>
#include <netinet/udp.h>

#include <arpa/inet.h>

#include <errno.h>
#include <event.h>
#include <ifaddrs.h>
#include <imsg.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "bpf.h"
#include "log.h"
#include "dhcpleased.h"
#include "frontend.h"
#include "control.h"
#include "checksum.h"

#define	ROUTE_SOCKET_BUF_SIZE	16384
#define	BOOTP_MIN_LEN		300	/* fixed bootp packet adds up to 300 */

struct bpf_ev {
	struct event		 ev;
	uint8_t			 buf[BPFLEN];
};

struct iface {
	LIST_ENTRY(iface)	 entries;
	struct bpf_ev		 bpfev;
	struct imsg_ifinfo	 ifinfo;
	int			 send_discover;
	uint32_t		 xid;
	struct in_addr		 requested_ip;
	struct in_addr		 server_identifier;
	struct in_addr		 dhcp_server;
	int			 udpsock;
};

__dead void	 frontend_shutdown(void);
void		 frontend_sig_handler(int, short, void *);
void		 update_iface(struct if_msghdr *, struct sockaddr_dl *);
void		 frontend_startup(void);
void		 init_ifaces(void);
void		 route_receive(int, short, void *);
void		 handle_route_message(struct rt_msghdr *, struct sockaddr **);
void		 get_rtaddrs(int, struct sockaddr *, struct sockaddr **);
void		 bpf_receive(int, short, void *);
int		 get_flags(char *);
int		 get_xflags(char *);
struct iface	*get_iface_by_id(uint32_t);
void		 remove_iface(uint32_t);
void		 set_bpfsock(int, uint32_t);
ssize_t		 build_packet(uint8_t, char *, uint32_t, struct ether_addr *,
		     struct in_addr *, struct in_addr *);
void		 send_discover(struct iface *);
void		 send_request(struct iface *);
void		 bpf_send_packet(struct iface *, uint8_t *, ssize_t);
void		 udp_send_packet(struct iface *, uint8_t *, ssize_t);

LIST_HEAD(, iface)		 interfaces;
struct dhcpleased_conf		*frontend_conf;
static struct imsgev		*iev_main;
static struct imsgev		*iev_engine;
struct event			 ev_route;
int				 ioctlsock;

uint8_t				 dhcp_packet[1500];

void
frontend_sig_handler(int sig, short event, void *bula)
{
	/*
	 * Normal signal handler rules don't apply because libevent
	 * decouples for us.
	 */

	switch (sig) {
	case SIGINT:
	case SIGTERM:
		frontend_shutdown();
	default:
		fatalx("unexpected signal");
	}
}

void
frontend(int debug, int verbose)
{
	struct event		 ev_sigint, ev_sigterm;
	struct passwd		*pw;

#ifndef SMALL
	frontend_conf = config_new_empty();
#endif /* SMALL */

	log_init(debug, LOG_DAEMON);
	log_setverbose(verbose);

	if ((pw = getpwnam(DHCPLEASED_USER)) == NULL)
		fatal("getpwnam");

	if (chdir("/") == -1)
		fatal("chdir(\"/\")");

	if (unveil("/", "") == -1)
		fatal("unveil /");
	if (unveil(NULL, NULL) == -1)
		fatal("unveil");

	setproctitle("%s", "frontend");
	log_procinit("frontend");

	if ((ioctlsock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)) == -1)
		fatal("socket");

	if (setgroups(1, &pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
		fatal("can't drop privileges");

	if (pledge("stdio unix recvfd route", NULL) == -1)
		fatal("pledge");
	event_init();

	/* Setup signal handler. */
	signal_set(&ev_sigint, SIGINT, frontend_sig_handler, NULL);
	signal_set(&ev_sigterm, SIGTERM, frontend_sig_handler, NULL);
	signal_add(&ev_sigint, NULL);
	signal_add(&ev_sigterm, NULL);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGHUP, SIG_IGN);

	/* Setup pipe and event handler to the parent process. */
	if ((iev_main = malloc(sizeof(struct imsgev))) == NULL)
		fatal(NULL);
	imsg_init(&iev_main->ibuf, 3);
	iev_main->handler = frontend_dispatch_main;
	iev_main->events = EV_READ;
	event_set(&iev_main->ev, iev_main->ibuf.fd, iev_main->events,
	    iev_main->handler, iev_main);
	event_add(&iev_main->ev, NULL);

	LIST_INIT(&interfaces);
	event_dispatch();

	frontend_shutdown();
}

__dead void
frontend_shutdown(void)
{
	/* Close pipes. */
	msgbuf_write(&iev_engine->ibuf.w);
	msgbuf_clear(&iev_engine->ibuf.w);
	close(iev_engine->ibuf.fd);
	msgbuf_write(&iev_main->ibuf.w);
	msgbuf_clear(&iev_main->ibuf.w);
	close(iev_main->ibuf.fd);

#ifndef SMALL
	config_clear(frontend_conf);
#endif /* SMALL */

	free(iev_engine);
	free(iev_main);

	log_info("frontend exiting");
	exit(0);
}

int
frontend_imsg_compose_main(int type, pid_t pid, void *data,
    uint16_t datalen)
{
	return (imsg_compose_event(iev_main, type, 0, pid, -1, data,
	    datalen));
}

int
frontend_imsg_compose_engine(int type, uint32_t peerid, pid_t pid,
    void *data, uint16_t datalen)
{
	return (imsg_compose_event(iev_engine, type, peerid, pid, -1,
	    data, datalen));
}

void
frontend_dispatch_main(int fd, short event, void *bula)
{
	static struct dhcpleased_conf	*nconf;
	static struct iface_conf	*iface_conf;
	struct imsg			 imsg;
	struct imsgev			*iev = bula;
	struct imsgbuf			*ibuf = &iev->ibuf;
	struct iface			*iface;
	ssize_t				 n;
	int				 shut = 0, bpfsock, if_index, udpsock;

	if (event & EV_READ) {
		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
			fatal("imsg_read error");
		if (n == 0)	/* Connection closed. */
			shut = 1;
	}
	if (event & EV_WRITE) {
		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
			fatal("msgbuf_write");
		if (n == 0)	/* Connection closed. */
			shut = 1;
	}

	for (;;) {
		if ((n = imsg_get(ibuf, &imsg)) == -1)
			fatal("%s: imsg_get error", __func__);
		if (n == 0)	/* No more messages. */
			break;

		switch (imsg.hdr.type) {
		case IMSG_SOCKET_IPC:
			/*
			 * Setup pipe and event handler to the engine
			 * process.
			 */
			if (iev_engine)
				fatalx("%s: received unexpected imsg fd "
				    "to frontend", __func__);

			if ((fd = imsg.fd) == -1)
				fatalx("%s: expected to receive imsg fd to "
				   "frontend but didn't receive any",
				   __func__);

			iev_engine = malloc(sizeof(struct imsgev));
			if (iev_engine == NULL)
				fatal(NULL);

			imsg_init(&iev_engine->ibuf, fd);
			iev_engine->handler = frontend_dispatch_engine;
			iev_engine->events = EV_READ;

			event_set(&iev_engine->ev, iev_engine->ibuf.fd,
			iev_engine->events, iev_engine->handler, iev_engine);
			event_add(&iev_engine->ev, NULL);
			break;
		case IMSG_BPFSOCK:
			if ((bpfsock = imsg.fd) == -1)
				fatalx("%s: expected to receive imsg "
				    "bpf fd but didn't receive any",
				    __func__);
			if (IMSG_DATA_SIZE(imsg) != sizeof(if_index))
				fatalx("%s: IMSG_BPFSOCK wrong length: "
				    "%lu", __func__, IMSG_DATA_SIZE(imsg));
			memcpy(&if_index, imsg.data, sizeof(if_index));
			set_bpfsock(bpfsock, if_index);
			break;
		case IMSG_UDPSOCK:
			if ((udpsock = imsg.fd) == -1)
				fatalx("%s: expected to receive imsg "
				    "udpsocket fd but didn't receive any",
				    __func__);
			if (IMSG_DATA_SIZE(imsg) != sizeof(if_index))
				fatalx("%s: IMSG_UDPSOCK wrong length: "
				    "%lu", __func__, IMSG_DATA_SIZE(imsg));
			memcpy(&if_index, imsg.data, sizeof(if_index));
			if ((iface = get_iface_by_id(if_index)) == NULL) {
				close(fd);
				break;
			}
			if (iface->udpsock != -1)
				fatalx("%s: received unexpected udpsocket",
				    __func__);
			iface->udpsock = udpsock;
			break;
		case IMSG_CLOSE_UDPSOCK:
			if (IMSG_DATA_SIZE(imsg) != sizeof(if_index))
				fatalx("%s: IMSG_UDPSOCK wrong length: "
				    "%lu", __func__, IMSG_DATA_SIZE(imsg));
			memcpy(&if_index, imsg.data, sizeof(if_index));
			if ((iface = get_iface_by_id(if_index)) != NULL &&
			    iface->udpsock != -1) {
				close(iface->udpsock);
				iface->udpsock = -1;
			}
			break;
		case IMSG_ROUTESOCK:
			if ((fd = imsg.fd) == -1)
				fatalx("%s: expected to receive imsg "
				    "routesocket fd but didn't receive any",
				    __func__);
			event_set(&ev_route, fd, EV_READ | EV_PERSIST,
			    route_receive, NULL);
			break;
		case IMSG_STARTUP:
			frontend_startup();
			break;
#ifndef SMALL
		case IMSG_RECONF_CONF:
			if (nconf != NULL)
				fatalx("%s: IMSG_RECONF_CONF already in "
				    "progress", __func__);
			if ((nconf = malloc(sizeof(struct dhcpleased_conf))) ==
			    NULL)
				fatal(NULL);
			SIMPLEQ_INIT(&nconf->iface_list);
			break;
		case IMSG_RECONF_IFACE:
			if (IMSG_DATA_SIZE(imsg) != sizeof(struct
			    iface_conf))
				fatalx("%s: IMSG_RECONF_IFACE wrong length: "
				    "%lu", __func__, IMSG_DATA_SIZE(imsg));
			if ((iface_conf = malloc(sizeof(struct iface_conf)))
			    == NULL)
				fatal(NULL);
			memcpy(iface_conf, imsg.data, sizeof(struct
			    iface_conf));
			iface_conf->vc_id = NULL;
			iface_conf->vc_id_len = 0;
			iface_conf->c_id = NULL;
			iface_conf->c_id_len = 0;
			SIMPLEQ_INSERT_TAIL(&nconf->iface_list,
			    iface_conf, entry);
			break;
		case IMSG_RECONF_VC_ID:
			if (iface_conf == NULL)
				fatal("IMSG_RECONF_VC_ID without "
				    "IMSG_RECONF_IFACE");
			if (IMSG_DATA_SIZE(imsg) > 255 + 2)
				fatalx("%s: IMSG_RECONF_VC_ID wrong length: "
				    "%lu", __func__, IMSG_DATA_SIZE(imsg));
			if ((iface_conf->vc_id = malloc(IMSG_DATA_SIZE(imsg)))
			    == NULL)
				fatal(NULL);
			memcpy(iface_conf->vc_id, imsg.data,
			    IMSG_DATA_SIZE(imsg));
			iface_conf->vc_id_len = IMSG_DATA_SIZE(imsg);
			break;
		case IMSG_RECONF_C_ID:
			if (iface_conf == NULL)
				fatal("IMSG_RECONF_C_ID without "
				    "IMSG_RECONF_IFACE");
			if (IMSG_DATA_SIZE(imsg) > 255 + 2)
				fatalx("%s: IMSG_RECONF_C_ID wrong length: "
				    "%lu", __func__, IMSG_DATA_SIZE(imsg));
			if ((iface_conf->c_id = malloc(IMSG_DATA_SIZE(imsg)))
			    == NULL)
				fatal(NULL);
			memcpy(iface_conf->c_id, imsg.data,
			    IMSG_DATA_SIZE(imsg));
			iface_conf->c_id_len = IMSG_DATA_SIZE(imsg);
			break;
		case IMSG_RECONF_END:
			if (nconf == NULL)
				fatalx("%s: IMSG_RECONF_END without "
				    "IMSG_RECONF_CONF", __func__);
			merge_config(frontend_conf, nconf);
			nconf = NULL;
			break;
		case IMSG_CONTROLFD:
			if ((fd = imsg.fd) == -1)
				fatalx("%s: expected to receive imsg "
				    "control fd but didn't receive any",
				    __func__);
			/* Listen on control socket. */
			control_listen(fd);
			break;
		case IMSG_CTL_END:
			control_imsg_relay(&imsg);
			break;
#endif	/* SMALL */
		default:
			log_debug("%s: error handling imsg %d", __func__,
			    imsg.hdr.type);
			break;
		}
		imsg_free(&imsg);
	}
	if (!shut)
		imsg_event_add(iev);
	else {
		/* This pipe is dead. Remove its event handler. */
		event_del(&iev->ev);
		event_loopexit(NULL);
	}
}

void
frontend_dispatch_engine(int fd, short event, void *bula)
{
	struct imsgev		*iev = bula;
	struct imsgbuf		*ibuf = &iev->ibuf;
	struct imsg		 imsg;
	struct iface		*iface;
	ssize_t			 n;
	int			 shut = 0;

	if (event & EV_READ) {
		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
			fatal("imsg_read error");
		if (n == 0)	/* Connection closed. */
			shut = 1;
	}
	if (event & EV_WRITE) {
		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
			fatal("msgbuf_write");
		if (n == 0)	/* Connection closed. */
			shut = 1;
	}

	for (;;) {
		if ((n = imsg_get(ibuf, &imsg)) == -1)
			fatal("%s: imsg_get error", __func__);
		if (n == 0)	/* No more messages. */
			break;

		switch (imsg.hdr.type) {
#ifndef	SMALL
		case IMSG_CTL_END:
		case IMSG_CTL_SHOW_INTERFACE_INFO:
			control_imsg_relay(&imsg);
			break;
#endif	/* SMALL */
		case IMSG_SEND_DISCOVER: {
			struct imsg_req_discover	 imsg_req_discover;
			if (IMSG_DATA_SIZE(imsg) != sizeof(imsg_req_discover))
				fatalx("%s: IMSG_SEND_DISCOVER wrong "
				    "length: %lu", __func__,
				    IMSG_DATA_SIZE(imsg));
			memcpy(&imsg_req_discover, imsg.data,
			    sizeof(imsg_req_discover));
			iface = get_iface_by_id(imsg_req_discover.if_index);
			if (iface != NULL) {
				iface->xid = imsg_req_discover.xid;
				send_discover(iface);
			}
			break;
		}
		case IMSG_SEND_REQUEST: {
			struct imsg_req_request	 imsg_req_request;
			if (IMSG_DATA_SIZE(imsg) != sizeof(imsg_req_request))
				fatalx("%s: IMSG_SEND_REQUEST wrong "
				    "length: %lu", __func__,
				    IMSG_DATA_SIZE(imsg));
			memcpy(&imsg_req_request, imsg.data,
			    sizeof(imsg_req_request));
			iface = get_iface_by_id(imsg_req_request.if_index);
			if (iface != NULL) {
				iface->xid = imsg_req_request.xid;
				iface->requested_ip.s_addr =
				    imsg_req_request.requested_ip.s_addr;
				iface->server_identifier.s_addr =
				    imsg_req_request.server_identifier.s_addr;
				iface->dhcp_server.s_addr =
				    imsg_req_request.dhcp_server.s_addr;
				send_request(iface);
			}
			break;
		}
		default:
			log_debug("%s: error handling imsg %d", __func__,
			    imsg.hdr.type);
			break;
		}
		imsg_free(&imsg);
	}
	if (!shut)
		imsg_event_add(iev);
	else {
		/* This pipe is dead. Remove its event handler. */
		event_del(&iev->ev);
		event_loopexit(NULL);
	}
}

int
get_flags(char *if_name)
{
	struct ifreq		 ifr;

	strlcpy(ifr.ifr_name, if_name, sizeof(ifr.ifr_name));
	if (ioctl(ioctlsock, SIOCGIFFLAGS, (caddr_t)&ifr) == -1) {
		log_warn("SIOCGIFFLAGS");
		return -1;
	}
	return ifr.ifr_flags;
}

int
get_xflags(char *if_name)
{
	struct ifreq		 ifr;

	strlcpy(ifr.ifr_name, if_name, sizeof(ifr.ifr_name));
	if (ioctl(ioctlsock, SIOCGIFXFLAGS, (caddr_t)&ifr) == -1) {
		log_warn("SIOCGIFXFLAGS");
		return -1;
	}
	return ifr.ifr_flags;
}

void
update_iface(struct if_msghdr *ifm, struct sockaddr_dl *sdl)
{
	struct iface		*iface;
	struct imsg_ifinfo	 ifinfo;
	uint32_t		 if_index;
	int			 flags, xflags;
	char			 ifnamebuf[IF_NAMESIZE], *if_name;

	if_index = ifm->ifm_index;

	flags = ifm->ifm_flags;
	xflags = ifm->ifm_xflags;

	iface = get_iface_by_id(if_index);
	if_name = if_indextoname(if_index, ifnamebuf);

	if (if_name == NULL) {
		if (iface != NULL) {
			log_debug("interface with idx %d removed", if_index);
			frontend_imsg_compose_engine(IMSG_REMOVE_IF, 0, 0,
			    &if_index, sizeof(if_index));
			remove_iface(if_index);
		}
		return;
	}

	if (!(xflags & IFXF_AUTOCONF4)) {
		if (iface != NULL) {
			log_info("Removed autoconf flag from %s", if_name);
			frontend_imsg_compose_engine(IMSG_REMOVE_IF, 0, 0,
			    &if_index, sizeof(if_index));
			remove_iface(if_index);
		}
		return;
	}

	memset(&ifinfo, 0, sizeof(ifinfo));
	ifinfo.if_index = if_index;
	ifinfo.link_state = ifm->ifm_data.ifi_link_state;
	ifinfo.rdomain = ifm->ifm_tableid;
	ifinfo.running = (flags & (IFF_UP | IFF_RUNNING)) ==
	    (IFF_UP | IFF_RUNNING);

	if (sdl != NULL && sdl->sdl_type == IFT_ETHER &&
	    sdl->sdl_alen == ETHER_ADDR_LEN)
		memcpy(ifinfo.hw_address.ether_addr_octet, LLADDR(sdl),
		    ETHER_ADDR_LEN);
	else if (iface == NULL) {
		log_warnx("Could not find AF_LINK address for %s.", if_name);
		return;
	}

	if (iface == NULL) {
		if ((iface = calloc(1, sizeof(*iface))) == NULL)
			fatal("calloc");
		iface->udpsock = -1;
		LIST_INSERT_HEAD(&interfaces, iface, entries);
		frontend_imsg_compose_main(IMSG_OPEN_BPFSOCK, 0,
		    &if_index, sizeof(if_index));
	} else {
		if (iface->ifinfo.rdomain != ifinfo.rdomain &&
		    iface->udpsock != -1) {
			close(iface->udpsock);
			iface->udpsock = -1;
		}
	}

	if (memcmp(&iface->ifinfo, &ifinfo, sizeof(iface->ifinfo)) != 0) {
		memcpy(&iface->ifinfo, &ifinfo, sizeof(iface->ifinfo));
		frontend_imsg_compose_main(IMSG_UPDATE_IF, 0, &iface->ifinfo,
		    sizeof(iface->ifinfo));
	}
}

void
frontend_startup(void)
{
	if (!event_initialized(&ev_route))
		fatalx("%s: did not receive a route socket from the main "
		    "process", __func__);

	init_ifaces();
	if (pledge("stdio unix recvfd", NULL) == -1)
		fatal("pledge");
	event_add(&ev_route, NULL);
}

void
init_ifaces(void)
{
	struct iface		*iface;
	struct imsg_ifinfo	 ifinfo;
	struct if_nameindex	*ifnidxp, *ifnidx;
	struct ifaddrs		*ifap, *ifa;
	uint32_t		 if_index;
	int			 flags, xflags;
	char			*if_name;

	if ((ifnidxp = if_nameindex()) == NULL)
		fatalx("if_nameindex");

	if (getifaddrs(&ifap) != 0)
		fatal("getifaddrs");

	for (ifnidx = ifnidxp; ifnidx->if_index != 0 && ifnidx->if_name != NULL;
	    ifnidx++) {
		if_index = ifnidx->if_index;
		if_name = ifnidx->if_name;
		if ((flags = get_flags(if_name)) == -1)
			continue;
		if ((xflags = get_xflags(if_name)) == -1)
			continue;
		if (!(xflags & IFXF_AUTOCONF4))
			continue;

		memset(&ifinfo, 0, sizeof(ifinfo));
		ifinfo.if_index = if_index;
		ifinfo.link_state = -1;
		ifinfo.running = (flags & (IFF_UP | IFF_RUNNING)) ==
		    (IFF_UP | IFF_RUNNING);

		for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
			if (strcmp(if_name, ifa->ifa_name) != 0)
				continue;
			if (ifa->ifa_addr == NULL)
				continue;

			switch (ifa->ifa_addr->sa_family) {
			case AF_LINK: {
				struct if_data		*if_data;
				struct sockaddr_dl	*sdl;

				sdl = (struct sockaddr_dl *)ifa->ifa_addr;
				if (sdl->sdl_type != IFT_ETHER ||
				    sdl->sdl_alen != ETHER_ADDR_LEN)
					continue;
				memcpy(ifinfo.hw_address.ether_addr_octet,
				    LLADDR(sdl), ETHER_ADDR_LEN);

				if_data = (struct if_data *)ifa->ifa_data;
				ifinfo.link_state = if_data->ifi_link_state;
				ifinfo.rdomain = if_data->ifi_rdomain;
				goto out;
			}
			default:
				break;
			}
		}
 out:
		if (ifinfo.link_state == -1)
			/* no AF_LINK found */
			continue;

		if ((iface = calloc(1, sizeof(*iface))) == NULL)
			fatal("calloc");
		iface->udpsock = -1;
		memcpy(&iface->ifinfo, &ifinfo, sizeof(iface->ifinfo));
		LIST_INSERT_HEAD(&interfaces, iface, entries);
		frontend_imsg_compose_main(IMSG_OPEN_BPFSOCK, 0,
		    &if_index, sizeof(if_index));
		frontend_imsg_compose_main(IMSG_UPDATE_IF, 0, &iface->ifinfo,
		    sizeof(iface->ifinfo));
	}

	freeifaddrs(ifap);
	if_freenameindex(ifnidxp);
}

void
route_receive(int fd, short events, void *arg)
{
	static uint8_t			 *buf;

	struct rt_msghdr		*rtm;
	struct sockaddr			*sa, *rti_info[RTAX_MAX];
	ssize_t				 n;

	if (buf == NULL) {
		buf = malloc(ROUTE_SOCKET_BUF_SIZE);
		if (buf == NULL)
			fatal("malloc");
	}
	rtm = (struct rt_msghdr *)buf;
	if ((n = read(fd, buf, ROUTE_SOCKET_BUF_SIZE)) == -1) {
		if (errno == EAGAIN || errno == EINTR)
			return;
		log_warn("dispatch_rtmsg: read error");
		return;
	}

	if (n == 0)
		fatal("routing socket closed");

	if (n < (ssize_t)sizeof(rtm->rtm_msglen) || n < rtm->rtm_msglen) {
		log_warnx("partial rtm of %zd in buffer", n);
		return;
	}

	if (rtm->rtm_version != RTM_VERSION)
		return;

	sa = (struct sockaddr *)(buf + rtm->rtm_hdrlen);
	get_rtaddrs(rtm->rtm_addrs, sa, rti_info);

	handle_route_message(rtm, rti_info);
}

void
handle_route_message(struct rt_msghdr *rtm, struct sockaddr **rti_info)
{
	struct sockaddr_dl	*sdl = NULL;
	switch (rtm->rtm_type) {
	case RTM_IFINFO:
		if (rtm->rtm_addrs & RTA_IFP && rti_info[RTAX_IFP]->sa_family
		    == AF_LINK)
			sdl = (struct sockaddr_dl *)rti_info[RTAX_IFP];
		update_iface((struct if_msghdr *)rtm, sdl);
		break;
	case RTM_PROPOSAL:
		if (rtm->rtm_priority == RTP_PROPOSAL_SOLICIT) {
			log_debug("RTP_PROPOSAL_SOLICIT");
			frontend_imsg_compose_engine(IMSG_REPROPOSE_RDNS,
			    0, 0, NULL, 0);
		}
		break;
	default:
		log_debug("unexpected RTM: %d", rtm->rtm_type);
		break;
	}
}

#define ROUNDUP(a) \
	((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))

void
get_rtaddrs(int addrs, struct sockaddr *sa, struct sockaddr **rti_info)
{
	int	i;

	for (i = 0; i < RTAX_MAX; i++) {
		if (addrs & (1 << i)) {
			rti_info[i] = sa;
			sa = (struct sockaddr *)((char *)(sa) +
			    ROUNDUP(sa->sa_len));
		} else
			rti_info[i] = NULL;
	}
}

void
bpf_receive(int fd, short events, void *arg)
{
	struct bpf_hdr		*hdr;
	struct imsg_dhcp	 imsg_dhcp;
	struct iface		*iface;
	ssize_t			 len, rem;
	uint8_t			*p;

	iface = (struct iface *)arg;

	if ((len = read(fd, iface->bpfev.buf, BPFLEN)) == -1) {
		log_warn("read");
		return;
	}

	if (len == 0)
		fatal("%s len == 0", __func__);

	memset(&imsg_dhcp, 0, sizeof(imsg_dhcp));
	imsg_dhcp.if_index = iface->ifinfo.if_index;

	rem = len;
	p = iface->bpfev.buf;

	while (rem > 0) {
		if ((size_t)rem < sizeof(*hdr)) {
			log_warnx("packet too short");
			return;
		}
		hdr = (struct bpf_hdr *)p;
		if (hdr->bh_caplen != hdr->bh_datalen) {
			log_warnx("skipping truncated packet");
			goto cont;
		}
		if (rem < hdr->bh_hdrlen + hdr->bh_caplen)
			/* we are done */
			break;
		if (hdr->bh_caplen > sizeof(imsg_dhcp.packet)) {
			log_warn("packet too big");
			goto cont;
		}
		memcpy(&imsg_dhcp.packet, p + hdr->bh_hdrlen, hdr->bh_caplen);
		imsg_dhcp.len = hdr->bh_caplen;
		frontend_imsg_compose_engine(IMSG_DHCP, 0, 0, &imsg_dhcp,
		    sizeof(imsg_dhcp));
 cont:
		p += BPF_WORDALIGN(hdr->bh_hdrlen + hdr->bh_caplen);
		rem -= BPF_WORDALIGN(hdr->bh_hdrlen + hdr->bh_caplen);

	}
}

ssize_t
build_packet(uint8_t message_type, char *if_name, uint32_t xid,
    struct ether_addr *hw_address, struct in_addr *requested_ip,
    struct in_addr *server_identifier)
{
	static uint8_t	 dhcp_cookie[] = DHCP_COOKIE;
	static uint8_t	 dhcp_message_type[] = {DHO_DHCP_MESSAGE_TYPE, 1,
		DHCPDISCOVER};
	static uint8_t	 dhcp_hostname[255] = {DHO_HOST_NAME, 0 /*, ... */};
	static uint8_t	 dhcp_client_id[] = {DHO_DHCP_CLIENT_IDENTIFIER, 7,
		HTYPE_ETHER, 0, 0, 0, 0, 0, 0};
	static uint8_t	 dhcp_req_list[] = {DHO_DHCP_PARAMETER_REQUEST_LIST,
		8, DHO_SUBNET_MASK, DHO_ROUTERS, DHO_DOMAIN_NAME_SERVERS,
		DHO_HOST_NAME, DHO_DOMAIN_NAME, DHO_BROADCAST_ADDRESS,
		DHO_DOMAIN_SEARCH, DHO_CLASSLESS_STATIC_ROUTES};
	static uint8_t	 dhcp_requested_address[] = {DHO_DHCP_REQUESTED_ADDRESS,
		4, 0, 0, 0, 0};
	static uint8_t	 dhcp_server_identifier[] = {DHO_DHCP_SERVER_IDENTIFIER,
		4, 0, 0, 0, 0};
#ifndef SMALL
	struct iface_conf	*iface_conf;
#endif /* SMALL */
	struct dhcp_hdr		*hdr;
	ssize_t			 len;
	uint8_t			*p;
	char			*c;

#ifndef SMALL
	iface_conf = find_iface_conf(&frontend_conf->iface_list, if_name);
#endif /* SMALL */

	memset(dhcp_packet, 0, sizeof(dhcp_packet));
	dhcp_message_type[2] = message_type;
	p = dhcp_packet;
	hdr = (struct dhcp_hdr *)p;
	hdr->op = DHCP_BOOTREQUEST;
	hdr->htype = HTYPE_ETHER;
	hdr->hlen = 6;
	hdr->hops = 0;
	hdr->xid = xid;
	hdr->secs = 0;
	memcpy(hdr->chaddr, hw_address, sizeof(*hw_address));
	p += sizeof(struct dhcp_hdr);
	memcpy(p, dhcp_cookie, sizeof(dhcp_cookie));
	p += sizeof(dhcp_cookie);
	memcpy(p, dhcp_message_type, sizeof(dhcp_message_type));
	p += sizeof(dhcp_message_type);
	if (gethostname(dhcp_hostname + 2, sizeof(dhcp_hostname) - 2) == 0) {
		if ((c = strchr(dhcp_hostname + 2, '.')) != NULL)
			*c = '\0';
		dhcp_hostname[1] = strlen(dhcp_hostname + 2);
		memcpy(p, dhcp_hostname, dhcp_hostname[1] + 2);
		p += dhcp_hostname[1] + 2;
	}

#ifndef SMALL
	if (iface_conf != NULL) {
		if (iface_conf->c_id_len > 0) {
			/* XXX check space */
			memcpy(p, iface_conf->c_id, iface_conf->c_id_len);
			p += iface_conf->c_id_len;
		}
		if (iface_conf->vc_id_len > 0) {
			/* XXX check space */
			memcpy(p, iface_conf->vc_id, iface_conf->vc_id_len);
			p += iface_conf->vc_id_len;
		}
	} else
#endif /* SMALL */
	{
		memcpy(dhcp_client_id + 3, hw_address, sizeof(*hw_address));
		memcpy(p, dhcp_client_id, sizeof(dhcp_client_id));
		p += sizeof(dhcp_client_id);
	}
	memcpy(p, dhcp_req_list, sizeof(dhcp_req_list));
	p += sizeof(dhcp_req_list);

	if (message_type == DHCPREQUEST) {
		memcpy(dhcp_requested_address + 2, requested_ip,
		    sizeof(*requested_ip));
		memcpy(p, dhcp_requested_address,
		    sizeof(dhcp_requested_address));
		p += sizeof(dhcp_requested_address);

		if (server_identifier->s_addr != INADDR_ANY) {
			memcpy(dhcp_server_identifier + 2, server_identifier,
			    sizeof(*server_identifier));
			memcpy(p, dhcp_server_identifier,
			    sizeof(dhcp_server_identifier));
			p += sizeof(dhcp_server_identifier);
		}
	}

	*p = DHO_END;
	p += 1;

	len = p - dhcp_packet;

	/* dhcp_packet is initialized with DHO_PADs */
	if (len < BOOTP_MIN_LEN)
		len = BOOTP_MIN_LEN;

	return (len);
}

void
send_discover(struct iface *iface)
{
	ssize_t			 pkt_len;
	char			 ifnamebuf[IF_NAMESIZE], *if_name;

	if (!event_initialized(&iface->bpfev.ev)) {
		iface->send_discover = 1;
		return;
	}
	iface->send_discover = 0;

	if_name = if_indextoname(iface->ifinfo.if_index, ifnamebuf);
	log_debug("DHCPDISCOVER on %s", if_name == NULL ? "?" : if_name);

	pkt_len = build_packet(DHCPDISCOVER, if_name, iface->xid,
	    &iface->ifinfo.hw_address, &iface->requested_ip, NULL);
	bpf_send_packet(iface, dhcp_packet, pkt_len);
}

void
send_request(struct iface *iface)
{
	ssize_t			 pkt_len;
	char			 ifnamebuf[IF_NAMESIZE], *if_name;

	if_name = if_indextoname(iface->ifinfo.if_index, ifnamebuf);
	log_debug("DHCPREQUEST on %s", if_name == NULL ? "?" : if_name);

	pkt_len = build_packet(DHCPREQUEST, if_name, iface->xid,
	    &iface->ifinfo.hw_address, &iface->requested_ip,
	    &iface->server_identifier);
	if (iface->dhcp_server.s_addr != INADDR_ANY)
		udp_send_packet(iface, dhcp_packet, pkt_len);
	else
		bpf_send_packet(iface, dhcp_packet, pkt_len);
}

void
udp_send_packet(struct iface *iface, uint8_t *packet, ssize_t len)
{
	struct sockaddr_in	to;

	memset(&to, 0, sizeof(to));
	to.sin_family = AF_INET;
	to.sin_len = sizeof(to);
	to.sin_addr.s_addr = iface->dhcp_server.s_addr;
	to.sin_port = ntohs(SERVER_PORT);

	if (sendto(iface->udpsock, packet, len, 0, (struct sockaddr *)&to,
	    sizeof(to)) == -1)
		log_warn("sendto");
}
void
bpf_send_packet(struct iface *iface, uint8_t *packet, ssize_t len)
{
	struct iovec		 iov[4];
	struct ether_header	 eh;
	struct ip		 ip;
	struct udphdr		 udp;
	ssize_t			 total, result;
	int			 iovcnt = 0, i;

	memset(eh.ether_dhost, 0xff, sizeof(eh.ether_dhost));
	memcpy(eh.ether_shost, &iface->ifinfo.hw_address,
	    sizeof(eh.ether_dhost));
	eh.ether_type = htons(ETHERTYPE_IP);
	iov[0].iov_base = &eh;
	iov[0].iov_len = sizeof(eh);
	iovcnt++;

	ip.ip_v = 4;
	ip.ip_hl = 5;
	ip.ip_tos = IPTOS_LOWDELAY;
	ip.ip_len = htons(sizeof(ip) + sizeof(udp) + len);
	ip.ip_id = 0;
	ip.ip_off = 0;
	ip.ip_ttl = 128;
	ip.ip_p = IPPROTO_UDP;
	ip.ip_sum = 0;
	ip.ip_src.s_addr = 0;
	ip.ip_dst.s_addr = INADDR_BROADCAST;
	ip.ip_sum = wrapsum(checksum((unsigned char *)&ip, sizeof(ip), 0));
	iov[iovcnt].iov_base = &ip;
	iov[iovcnt].iov_len = sizeof(ip);
	iovcnt++;

	udp.uh_sport = htons(CLIENT_PORT);
	udp.uh_dport = htons(SERVER_PORT);
	udp.uh_ulen = htons(sizeof(udp) + len);
	udp.uh_sum = 0;
	udp.uh_sum = wrapsum(checksum((unsigned char *)&udp, sizeof(udp),
	    checksum((unsigned char *)packet, len,
	    checksum((unsigned char *)&ip.ip_src,
	    2 * sizeof(ip.ip_src),
	    IPPROTO_UDP + (uint32_t)ntohs(udp.uh_ulen)))));
	iov[iovcnt].iov_base = &udp;
	iov[iovcnt].iov_len = sizeof(udp);
	iovcnt++;

	iov[iovcnt].iov_base = packet;
	iov[iovcnt].iov_len = len;
	iovcnt++;

	total = 0;
	for (i = 0; i < iovcnt; i++)
		total += iov[i].iov_len;

	result = writev(EVENT_FD(&iface->bpfev.ev), iov, iovcnt);
	if (result == -1)
		log_warn("%s: writev", __func__);
	else if (result < total) {
		log_warnx("%s, writev: %zd of %zd bytes", __func__, result,
		    total);
	}
}

struct iface*
get_iface_by_id(uint32_t if_index)
{
	struct iface	*iface;

	LIST_FOREACH (iface, &interfaces, entries) {
		if (iface->ifinfo.if_index == if_index)
			return (iface);
	}

	return (NULL);
}

void
remove_iface(uint32_t if_index)
{
	struct iface	*iface;

	iface = get_iface_by_id(if_index);

	if (iface == NULL)
		return;

	LIST_REMOVE(iface, entries);
	event_del(&iface->bpfev.ev);
	close(EVENT_FD(&iface->bpfev.ev));
	if (iface->udpsock != -1)
		close(iface->udpsock);
	free(iface);
}

void
set_bpfsock(int bpfsock, uint32_t if_index)
{
	struct iface	*iface;

	if ((iface = get_iface_by_id(if_index)) == NULL) {
		/*
		 * The interface disappeared while we were waiting for the
		 * parent process to open the raw socket.
		 */
		close(bpfsock);
	} else {
		event_set(&iface->bpfev.ev, bpfsock, EV_READ |
		    EV_PERSIST, bpf_receive, iface);
		event_add(&iface->bpfev.ev, NULL);
		if (iface->send_discover)
			send_discover(iface);
	}
}

#ifndef SMALL
struct iface_conf*
find_iface_conf(struct iface_conf_head *head, char *if_name)
{
	struct iface_conf	*iface_conf;

	if (if_name == NULL)
		return (NULL);

	SIMPLEQ_FOREACH(iface_conf, head, entry) {
		if (strcmp(iface_conf->name, if_name) == 0)
			return iface_conf;
	}
	return (NULL);
}
#endif /* SMALL */