summaryrefslogtreecommitdiff
path: root/usr.sbin/bgpd/rtr_proto.c
blob: f698064597990a8fe82359e6a12569a58e262b11 (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
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
/*	$OpenBSD: rtr_proto.c,v 1.41 2024/10/08 12:28:09 claudio Exp $ */

/*
 * Copyright (c) 2020 Claudio Jeker <claudio@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/tree.h>
#include <errno.h>
#include <stdint.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "bgpd.h"
#include "session.h"
#include "log.h"

struct rtr_header {
	uint8_t		version;
	uint8_t		type;
	union {
		uint16_t	session_id;
		uint16_t	errcode;
		struct {
			uint8_t	flags;
			uint8_t	zero;
		};
	};
	uint32_t	length;
} __packed;

#define RTR_MAX_PDU_SIZE	49152	/* XXX < IBUF_READ_SIZE */
#define RTR_MAX_PDU_ERROR_SIZE	256
#define RTR_DEFAULT_REFRESH	3600
#define RTR_DEFAULT_RETRY	600
#define RTR_DEFAULT_EXPIRE	7200
#define RTR_DEFAULT_ACTIVE	60

enum rtr_pdu_type {
	SERIAL_NOTIFY = 0,
	SERIAL_QUERY,
	RESET_QUERY,
	CACHE_RESPONSE,
	IPV4_PREFIX,
	IPV6_PREFIX = 6,
	END_OF_DATA = 7,
	CACHE_RESET = 8,
	ROUTER_KEY = 9,
	ERROR_REPORT = 10,
	ASPA = 11,
};

struct rtr_notify {
	struct rtr_header	hdr;
	uint32_t		serial;
} __packed;

struct rtr_query {
	struct rtr_header	hdr;
	uint32_t		serial;
} __packed;

struct rtr_reset {
	struct rtr_header	hdr;
} __packed;

struct rtr_response {
	struct rtr_header	hdr;
} __packed;

#define FLAG_ANNOUNCE	0x1
#define FLAG_MASK	FLAG_ANNOUNCE
struct rtr_ipv4 {
	struct rtr_header	hdr;
	uint8_t			flags;
	uint8_t			prefixlen;
	uint8_t			maxlen;
	uint8_t			zero;
	uint32_t		prefix;
	uint32_t		asnum;
} __packed;

struct rtr_ipv6 {
	struct rtr_header	hdr;
	uint8_t			flags;
	uint8_t			prefixlen;
	uint8_t			maxlen;
	uint8_t			zero;
	uint32_t		prefix[4];
	uint32_t		asnum;
} __packed;

struct rtr_routerkey {
	struct rtr_header	hdr;
	uint8_t			ski[20];
	uint32_t		asnum;
	/* followed by Subject Public Key Info */
} __packed;

struct rtr_aspa {
	struct rtr_header	hdr;
	uint32_t		cas;
	/* array of spas filling the rest of the packet */
} __packed;

struct rtr_endofdata {
	struct rtr_header	hdr;
	uint32_t		serial;
	uint32_t		refresh;
	uint32_t		retry;
	uint32_t		expire;
} __packed;

struct rtr_endofdata_v0 {
	struct rtr_header	hdr;
	uint32_t		serial;
} __packed;

enum rtr_event {
	RTR_EVNT_START,
	RTR_EVNT_CON_OPEN,
	RTR_EVNT_CON_CLOSE,
	RTR_EVNT_TIMER_REFRESH,
	RTR_EVNT_TIMER_RETRY,
	RTR_EVNT_TIMER_EXPIRE,
	RTR_EVNT_TIMER_ACTIVE,
	RTR_EVNT_SEND_ERROR,
	RTR_EVNT_SERIAL_NOTIFY,
	RTR_EVNT_CACHE_RESPONSE,
	RTR_EVNT_END_OF_DATA,
	RTR_EVNT_CACHE_RESET,
	RTR_EVNT_NO_DATA,
	RTR_EVNT_RESET_AND_CLOSE,
	RTR_EVNT_UNSUPP_PROTO_VERSION,
	RTR_EVNT_NEGOTIATION_DONE,
};

static const char *rtr_eventnames[] = {
	"start",
	"connection open",
	"connection closed",
	"refresh timer expired",
	"retry timer expired",
	"expire timer expired",
	"activity timer expired",
	"sent error",
	"serial notify received",
	"cache response received",
	"end of data received",
	"cache reset received",
	"no data",
	"connection closed with reset",
	"unsupported protocol version",
	"negotiation done",
};

enum rtr_state {
	RTR_STATE_CLOSED,
	RTR_STATE_ERROR,
	/* sessions with a state below this line will poll for incoming data */
	RTR_STATE_ESTABLISHED,
	RTR_STATE_EXCHANGE,
	RTR_STATE_NEGOTIATION,
};

static const char *rtr_statenames[] = {
	"closed",
	"error",
	"established",
	"exchange",
	"negotiation",
};

struct rtr_session {
	TAILQ_ENTRY(rtr_session)	entry;
	char				descr[PEER_DESCR_LEN];
	struct roa_tree			roa_set;
	struct aspa_tree		aspa;
	struct ibuf_read		r;
	struct msgbuf			w;
	struct timer_head		timers;
	uint32_t			id;		/* rtr_config id */
	uint32_t			serial;
	uint32_t			refresh;
	uint32_t			retry;
	uint32_t			expire;
	uint32_t			active;
	int				session_id;
	int				fd;
	int				active_lock;
	enum rtr_state			state;
	enum reconf_action		reconf_action;
	enum rtr_error			last_sent_error;
	enum rtr_error			last_recv_error;
	char				last_sent_msg[REASON_LEN];
	char				last_recv_msg[REASON_LEN];
	uint8_t				version;
	uint8_t				prev_version;
	uint8_t				min_version;
	uint8_t				errored;

};

TAILQ_HEAD(, rtr_session) rtrs = TAILQ_HEAD_INITIALIZER(rtrs);

static void	rtr_fsm(struct rtr_session *, enum rtr_event);

static const char *
log_rtr(struct rtr_session *rs)
{
	return rs->descr;
}

static const char *
log_rtr_type(enum rtr_pdu_type type)
{
	static char buf[20];

	switch (type) {
	case SERIAL_NOTIFY:
		return "serial notify";
	case SERIAL_QUERY:
		return "serial query";
	case RESET_QUERY:
		return "reset query";
	case CACHE_RESPONSE:
		return "cache response";
	case IPV4_PREFIX:
		return "IPv4 prefix";
	case IPV6_PREFIX:
		return "IPv6 prefix";
	case END_OF_DATA:
		return "end of data";
	case CACHE_RESET:
		return "cache reset";
	case ROUTER_KEY:
		return "router key";
	case ERROR_REPORT:
		return "error report";
	case ASPA:
		return "aspa";
	default:
		snprintf(buf, sizeof(buf), "unknown %u", type);
		return buf;
	}
};

static uint8_t
rtr_max_session_version(struct rtr_session *rs)
{
	if (rs->min_version > RTR_DEFAULT_VERSION)
		return rs->min_version;
	return RTR_DEFAULT_VERSION;
}

static void
rtr_reset_cache(struct rtr_session *rs)
{
	/* reset session */
	rs->session_id = -1;
	timer_stop(&rs->timers, Timer_Rtr_Expire);
	free_roatree(&rs->roa_set);
	free_aspatree(&rs->aspa);
}

static struct ibuf *
rtr_newmsg(struct rtr_session *rs, enum rtr_pdu_type type, uint32_t len,
    uint16_t session_id)
{
	struct ibuf *buf;
	int saved_errno;

	if (len > RTR_MAX_PDU_SIZE) {
		errno = ERANGE;
		return NULL;
	}
	len += sizeof(struct rtr_header);
	if ((buf = ibuf_open(len)) == NULL)
		goto fail;
	if (ibuf_add_n8(buf, rs->version) == -1)
		goto fail;
	if (ibuf_add_n8(buf, type) == -1)
		goto fail;
	if (ibuf_add_n16(buf, session_id) == -1)
		goto fail;
	if (ibuf_add_n32(buf, len) == -1)
		goto fail;

	return buf;

 fail:
	saved_errno = errno;
	ibuf_free(buf);
	errno = saved_errno;
	return NULL;
}

static void rtr_send_error(struct rtr_session *, struct ibuf *, enum rtr_error,
    const char *, ...) __attribute__((__format__ (printf, 4, 5)));

/*
 * Try to send an error PDU to cache, put connection into error
 * state.
 */
static void
rtr_send_error(struct rtr_session *rs, struct ibuf *pdu, enum rtr_error err,
    const char *fmt, ...)
{
	struct ibuf *buf;
	va_list ap;
	size_t len = 0, mlen = 0;

	rs->last_sent_error = err;
	memset(rs->last_sent_msg, 0, sizeof(rs->last_sent_msg));
	if (fmt != NULL) {
		va_start(ap, fmt);
		vsnprintf(rs->last_sent_msg, sizeof(rs->last_sent_msg),
		    fmt, ap);
		mlen = strlen(rs->last_sent_msg);
		va_end(ap);
	}

	log_warnx("rtr %s: sending error: %s%s%s", log_rtr(rs),
	    log_rtr_error(err), mlen > 0 ? ": " : "", rs->last_sent_msg);

	if (pdu != NULL) {
		ibuf_rewind(pdu);
		len = ibuf_size(pdu);
		if (len > RTR_MAX_PDU_ERROR_SIZE) {
			len = RTR_MAX_PDU_ERROR_SIZE;
			/* truncate down can not fail */
			ibuf_truncate(pdu, RTR_MAX_PDU_ERROR_SIZE);
		}
	}

	buf = rtr_newmsg(rs, ERROR_REPORT, 2 * sizeof(uint32_t) + len + mlen,
	    err);
	if (buf == NULL)
		goto fail;
	if (ibuf_add_n32(buf, len) == -1)
		goto fail;
	if (pdu != NULL) {
		if (ibuf_add_ibuf(buf, pdu) == -1)
			goto fail;
	}
	if (ibuf_add_n32(buf, mlen) == -1)
		goto fail;
	if (ibuf_add(buf, rs->last_sent_msg, mlen) == -1)
		goto fail;
	ibuf_close(&rs->w, buf);

	rtr_fsm(rs, RTR_EVNT_SEND_ERROR);
	return;

 fail:
	log_warn("rtr %s: send error report", log_rtr(rs));
	ibuf_free(buf);
}

static void
rtr_send_reset_query(struct rtr_session *rs)
{
	struct ibuf *buf;

	buf = rtr_newmsg(rs, RESET_QUERY, 0, 0);
	if (buf == NULL)
		goto fail;
	ibuf_close(&rs->w, buf);
	return;

 fail:
	rtr_send_error(rs, NULL, INTERNAL_ERROR,
	    "send %s: %s", log_rtr_type(RESET_QUERY), strerror(errno));
	ibuf_free(buf);
}

static void
rtr_send_serial_query(struct rtr_session *rs)
{
	struct ibuf *buf;

	buf = rtr_newmsg(rs, SERIAL_QUERY, sizeof(uint32_t), rs->session_id);
	if (buf == NULL)
		goto fail;
	if (ibuf_add_n32(buf, rs->serial) == -1)
		goto fail;
	ibuf_close(&rs->w, buf);
	return;

 fail:
	rtr_send_error(rs, NULL, INTERNAL_ERROR,
	    "send %s: %s", log_rtr_type(SERIAL_QUERY), strerror(errno));
	ibuf_free(buf);
}

/*
 * Check the session_id of the rtr_header to match the expected value.
 * Returns -1 on failure and 0 on success.
 */
static int
rtr_check_session_id(struct rtr_session *rs, uint16_t session_id,
    struct rtr_header *rh, struct ibuf *pdu)
{
	if (session_id != ntohs(rh->session_id)) {
		rtr_send_error(rs, pdu, CORRUPT_DATA,
		    "%s: bad session_id %d (expected %d)",
		    log_rtr_type(rh->type), ntohs(rh->session_id), session_id);
		return -1;
	}
	return 0;
}

/*
 * Parse the common rtr header (first 8 bytes) including the
 * included length field.
 * Returns -1 on failure. On success msgtype and msglen are set
 * and the function return 0.
 */
static int
rtr_parse_header(struct rtr_session *rs, struct ibuf *hdr,
    size_t *msglen, enum rtr_pdu_type *msgtype)
{
	struct rtr_header rh;
	size_t len;
	uint16_t errcode;

	if (ibuf_get(hdr, &rh, sizeof(rh)) == -1)
		fatal("%s: ibuf_get", __func__);

	len = ntohl(rh.length);

	if (len > RTR_MAX_PDU_SIZE) {
		rtr_send_error(rs, hdr, CORRUPT_DATA, "%s: too big: %zu bytes",
		    log_rtr_type(rh.type), len);
		return -1;
	}

	if (rs->state == RTR_STATE_NEGOTIATION) {
		switch (rh.type) {
		case CACHE_RESPONSE:
		case CACHE_RESET:
			/* implicit downgrade */
			if (rh.version < rs->version) {
				rs->prev_version = rs->version;
				rs->version = rh.version;
			}
			rtr_fsm(rs, RTR_EVNT_NEGOTIATION_DONE);
			break;
		case ERROR_REPORT:
			errcode = ntohs(rh.session_id);
			if (errcode == UNSUPP_PROTOCOL_VERS ||
			    errcode == NO_DATA_AVAILABLE) {
				if (rh.version < rs->version) {
					rs->prev_version = rs->version;
					rs->version = rh.version;
				}
			}
			break;
		case SERIAL_NOTIFY:
			/* ignore SERIAL_NOTIFY */
			break;
		default:
			rtr_send_error(rs, hdr, CORRUPT_DATA,
			    "%s: out of context", log_rtr_type(rh.type));
			return -1;
		}
	} else if (rh.version != rs->version && rh.type != ERROR_REPORT) {
		goto badversion;
	}

	switch (rh.type) {
	case SERIAL_NOTIFY:
		if (len != sizeof(struct rtr_notify))
			goto badlen;
		break;
	case CACHE_RESPONSE:
		if (len != sizeof(struct rtr_response))
			goto badlen;
		break;
	case IPV4_PREFIX:
		if (len != sizeof(struct rtr_ipv4))
			goto badlen;
		break;
	case IPV6_PREFIX:
		if (len != sizeof(struct rtr_ipv6))
			goto badlen;
		break;
	case END_OF_DATA:
		if (rs->version == 0) {
			if (len != sizeof(struct rtr_endofdata_v0))
				goto badlen;
		} else {
			if (len != sizeof(struct rtr_endofdata))
				goto badlen;
		}
		break;
	case CACHE_RESET:
		if (len != sizeof(struct rtr_reset))
			goto badlen;
		break;
	case ROUTER_KEY:
		if (rs->version < 1)
			goto badversion;
		if (len < sizeof(struct rtr_routerkey))
			goto badlen;
		break;
	case ERROR_REPORT:
		if (len < 16)
			goto badlen;
		break;
	case ASPA:
		if (rs->version < 2)
			goto badversion;
		if (len < sizeof(struct rtr_aspa) || (len % 4) != 0)
			goto badlen;
		break;
	default:
		rtr_send_error(rs, hdr, UNSUPP_PDU_TYPE, "type %s",
		    log_rtr_type(rh.type));
		return -1;
	}

	*msglen = len;
	*msgtype = rh.type;

	return 0;

 badlen:
	rtr_send_error(rs, hdr, CORRUPT_DATA, "%s: bad length: %zu bytes",
	    log_rtr_type(rh.type), len);
	return -1;

 badversion:
	rtr_send_error(rs, hdr, UNEXP_PROTOCOL_VERS, "%s: version %d",
	    log_rtr_type(rh.type), rh.version);
	return -1;
}

static int
rtr_parse_notify(struct rtr_session *rs, struct ibuf *pdu)
{
	struct rtr_notify notify;

	/* ignore SERIAL_NOTIFY during startup */
	if (rs->state == RTR_STATE_NEGOTIATION)
		return 0;

	if (ibuf_get(pdu, &notify, sizeof(notify)) == -1)
		goto badlen;

	/* set session_id if not yet happened */
	if (rs->session_id == -1)
		rs->session_id = ntohs(notify.hdr.session_id);

	if (rtr_check_session_id(rs, rs->session_id, &notify.hdr, pdu) == -1)
		return -1;

	if (rs->state != RTR_STATE_ESTABLISHED) {
		log_warnx("rtr %s: received %s: while in state %s (ignored)",
		    log_rtr(rs), log_rtr_type(SERIAL_NOTIFY),
		    rtr_statenames[rs->state]);
		return 0;
	}

	rtr_fsm(rs, RTR_EVNT_SERIAL_NOTIFY);
	return 0;

 badlen:
	rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: bad length",
	    log_rtr_type(SERIAL_NOTIFY));
	return -1;
}

static int
rtr_parse_cache_response(struct rtr_session *rs, struct ibuf *pdu)
{
	struct rtr_response resp;

	if (ibuf_get(pdu, &resp, sizeof(resp)) == -1)
		goto badlen;

	/* set session_id if not yet happened */
	if (rs->session_id == -1)
		rs->session_id = ntohs(resp.hdr.session_id);

	if (rtr_check_session_id(rs, rs->session_id, &resp.hdr, pdu) == -1)
		return -1;

	if (rs->state != RTR_STATE_ESTABLISHED) {
		rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: out of context",
		    log_rtr_type(CACHE_RESPONSE));
		return -1;
	}

	rtr_fsm(rs, RTR_EVNT_CACHE_RESPONSE);
	return 0;

 badlen:
	rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: bad length",
	    log_rtr_type(CACHE_RESPONSE));
	return -1;
}

static int
rtr_parse_ipv4_prefix(struct rtr_session *rs, struct ibuf *pdu)
{
	struct rtr_ipv4 ip4;
	struct roa *roa;

	if (ibuf_get(pdu, &ip4, sizeof(ip4)) == -1)
		goto badlen;

	if (rtr_check_session_id(rs, 0, &ip4.hdr, pdu) == -1)
		return -1;

	if (rs->state != RTR_STATE_EXCHANGE) {
		rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: out of context",
		    log_rtr_type(IPV4_PREFIX));
		return -1;
	}

	if (ip4.prefixlen > 32 || ip4.maxlen > 32 ||
	    ip4.prefixlen > ip4.maxlen) {
		rtr_send_error(rs, pdu, CORRUPT_DATA,
		    "%s: bad prefixlen / maxlen", log_rtr_type(IPV4_PREFIX));
		return -1;
	}

	if ((roa = calloc(1, sizeof(*roa))) == NULL) {
		rtr_send_error(rs, NULL, INTERNAL_ERROR, "out of memory");
		return -1;
	}
	roa->aid = AID_INET;
	roa->prefixlen = ip4.prefixlen;
	roa->maxlen = ip4.maxlen;
	roa->asnum = ntohl(ip4.asnum);
	roa->prefix.inet.s_addr = ip4.prefix;

	if (ip4.flags & FLAG_ANNOUNCE) {
		if (RB_INSERT(roa_tree, &rs->roa_set, roa) != NULL) {
			rtr_send_error(rs, pdu, DUP_REC_RECV, "%s %s",
			    log_rtr_type(IPV4_PREFIX), log_roa(roa));
			free(roa);
			return -1;
		}
	} else {
		struct roa *r;

		r = RB_FIND(roa_tree, &rs->roa_set, roa);
		if (r == NULL) {
			rtr_send_error(rs, pdu, UNK_REC_WDRAWL, "%s %s",
			    log_rtr_type(IPV4_PREFIX), log_roa(roa));
			free(roa);
			return -1;
		}
		RB_REMOVE(roa_tree, &rs->roa_set, r);
		free(r);
		free(roa);
	}

	return 0;

 badlen:
	rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: bad length",
	    log_rtr_type(IPV4_PREFIX));
	return -1;
}

static int
rtr_parse_ipv6_prefix(struct rtr_session *rs, struct ibuf *pdu)
{
	struct rtr_ipv6 ip6;
	struct roa *roa;

	if (ibuf_get(pdu, &ip6, sizeof(ip6)) == -1)
		goto badlen;

	if (rtr_check_session_id(rs, 0, &ip6.hdr, pdu) == -1)
		return -1;

	if (rs->state != RTR_STATE_EXCHANGE) {
		rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: out of context",
		    log_rtr_type(IPV6_PREFIX));
		return -1;
	}

	if (ip6.prefixlen > 128 || ip6.maxlen > 128 ||
	    ip6.prefixlen > ip6.maxlen) {
		rtr_send_error(rs, pdu, CORRUPT_DATA,
		    "%s: bad prefixlen / maxlen", log_rtr_type(IPV6_PREFIX));
		return -1;
	}

	if ((roa = calloc(1, sizeof(*roa))) == NULL) {
		rtr_send_error(rs, NULL, INTERNAL_ERROR, "out of memory");
		return -1;
	}
	roa->aid = AID_INET6;
	roa->prefixlen = ip6.prefixlen;
	roa->maxlen = ip6.maxlen;
	roa->asnum = ntohl(ip6.asnum);
	memcpy(&roa->prefix.inet6, ip6.prefix, sizeof(roa->prefix.inet6));

	if (ip6.flags & FLAG_ANNOUNCE) {
		if (RB_INSERT(roa_tree, &rs->roa_set, roa) != NULL) {
			rtr_send_error(rs, pdu, DUP_REC_RECV, "%s %s",
			    log_rtr_type(IPV6_PREFIX), log_roa(roa));
			free(roa);
			return -1;
		}
	} else {
		struct roa *r;

		r = RB_FIND(roa_tree, &rs->roa_set, roa);
		if (r == NULL) {
			rtr_send_error(rs, pdu, UNK_REC_WDRAWL, "%s %s",
			    log_rtr_type(IPV6_PREFIX), log_roa(roa));
			free(roa);
			return -1;
		}
		RB_REMOVE(roa_tree, &rs->roa_set, r);
		free(r);
		free(roa);
	}
	return 0;

 badlen:
	rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: bad length",
	    log_rtr_type(IPV6_PREFIX));
	return -1;
}

static int
rtr_parse_aspa(struct rtr_session *rs, struct ibuf *pdu)
{
	struct rtr_aspa rtr_aspa;
	struct aspa_set *aspa, *a;
	uint32_t cnt, i;
	uint8_t flags;

	if (ibuf_get(pdu, &rtr_aspa, sizeof(rtr_aspa)) == -1)
		goto badlen;

	flags = rtr_aspa.hdr.flags;
	cnt = ibuf_size(pdu) / sizeof(uint32_t);

	if ((flags & FLAG_ANNOUNCE) && cnt == 0) {
		rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: "
		    "announce with empty SPAS", log_rtr_type(ASPA));
		return -1;
	}
	if ((flags & FLAG_ANNOUNCE) == 0 && cnt != 0) {
		rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: "
		    "withdraw with non-empty SPAS", log_rtr_type(ASPA));
		return -1;
	}

	if (rs->state != RTR_STATE_EXCHANGE) {
		rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: out of context",
		    log_rtr_type(ASPA));
		return -1;
	}

	/* treat ASPA records with too many SPAS like a withdraw */
	if (cnt > MAX_ASPA_SPAS_COUNT) {
		struct aspa_set needle = { 0 };
		needle.as = ntohl(rtr_aspa.cas);

		log_warnx("rtr %s: oversized ASPA PDU: "
		    "imlicit withdraw of customerAS %s",
		    log_rtr(rs), log_as(needle.as));
		a = RB_FIND(aspa_tree, &rs->aspa, &needle);
		if (a != NULL) {
			RB_REMOVE(aspa_tree, &rs->aspa, a);
			free_aspa(a);
		}
		return 0;
	}

	/* create aspa_set entry from the rtr aspa pdu */
	if ((aspa = calloc(1, sizeof(*aspa))) == NULL) {
		rtr_send_error(rs, NULL, INTERNAL_ERROR, "out of memory");
		return -1;
	}
	aspa->as = ntohl(rtr_aspa.cas);
	aspa->num = cnt;
	if (cnt > 0) {
		if ((aspa->tas = calloc(cnt, sizeof(uint32_t))) == NULL) {
			free_aspa(aspa);
			rtr_send_error(rs, NULL, INTERNAL_ERROR,
			    "out of memory");
			return -1;
		}
		for (i = 0; i < cnt; i++) {
			if (ibuf_get_n32(pdu, &aspa->tas[i]) == -1)
				goto badlen;
		}
	}

	if (flags & FLAG_ANNOUNCE) {
		a = RB_INSERT(aspa_tree, &rs->aspa, aspa);
		if (a != NULL) {
			RB_REMOVE(aspa_tree, &rs->aspa, a);
			free_aspa(a);

			if (RB_INSERT(aspa_tree, &rs->aspa, aspa) != NULL) {
				rtr_send_error(rs, NULL, INTERNAL_ERROR,
				    "corrupt aspa tree");
				free_aspa(aspa);
				return -1;
			}
		}
	} else {
		a = RB_FIND(aspa_tree, &rs->aspa, aspa);
		if (a == NULL) {
			rtr_send_error(rs, pdu, UNK_REC_WDRAWL, "%s %s",
			    log_rtr_type(ASPA), log_aspa(aspa));
			free_aspa(aspa);
			return -1;
		}
		RB_REMOVE(aspa_tree, &rs->aspa, a);
		free_aspa(a);
		free_aspa(aspa);
	}

	return 0;

 badlen:
	rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: bad length",
	    log_rtr_type(ASPA));
	return -1;
}

static int
rtr_parse_end_of_data_v0(struct rtr_session *rs, struct ibuf *pdu)
{
	struct rtr_endofdata_v0 eod;

	if (ibuf_get(pdu, &eod, sizeof(eod)) == -1)
		goto badlen;

	if (rtr_check_session_id(rs, rs->session_id, &eod.hdr, pdu) == -1)
		return -1;

	if (rs->state != RTR_STATE_EXCHANGE) {
		rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: out of context",
		    log_rtr_type(END_OF_DATA));
		return -1;
	}

	rs->serial = ntohl(eod.serial);

	rtr_fsm(rs, RTR_EVNT_END_OF_DATA);
	return 0;

 badlen:
	rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: bad length",
	    log_rtr_type(END_OF_DATA));
	return -1;
}

static int
rtr_parse_end_of_data(struct rtr_session *rs, struct ibuf *pdu)
{
	struct rtr_endofdata eod;
	uint32_t t;

	/* version 0 does not have the timing values */
	if (rs->version == 0)
		return rtr_parse_end_of_data_v0(rs, pdu);

	if (ibuf_get(pdu, &eod, sizeof(eod)) == -1)
		goto badlen;

	if (rtr_check_session_id(rs, rs->session_id, &eod.hdr, pdu) == -1)
		return -1;

	if (rs->state != RTR_STATE_EXCHANGE) {
		rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: out of context",
		    log_rtr_type(END_OF_DATA));
		return -1;
	}

	rs->serial = ntohl(eod.serial);
	/* validate timer values to be in the right range */
	t = ntohl(eod.refresh);
	if (t < 1 || t > 86400)
		goto bad;
	rs->refresh = t;
	t = ntohl(eod.retry);
	if (t < 1 || t > 7200)
		goto bad;
	rs->retry = t;
	t = ntohl(eod.expire);
	if (t < 600 || t > 172800)
		goto bad;
	if (t <= rs->retry || t <= rs->refresh)
		goto bad;
	rs->expire = t;

	rtr_fsm(rs, RTR_EVNT_END_OF_DATA);
	return 0;

bad:
	rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: bad timeout values",
	    log_rtr_type(END_OF_DATA));
	return -1;

badlen:
	rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: bad length",
	    log_rtr_type(END_OF_DATA));
	return -1;
}

static int
rtr_parse_cache_reset(struct rtr_session *rs, struct ibuf *pdu)
{
	struct rtr_reset reset;

	if (ibuf_get(pdu, &reset, sizeof(reset)) == -1)
		goto badlen;

	if (rtr_check_session_id(rs, 0, &reset.hdr, pdu) == -1)
		return -1;

	if (rs->state != RTR_STATE_ESTABLISHED) {
		rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: out of context",
		    log_rtr_type(CACHE_RESET));
		return -1;
	}

	rtr_fsm(rs, RTR_EVNT_CACHE_RESET);
	return 0;

 badlen:
	rtr_send_error(rs, pdu, CORRUPT_DATA, "%s: bad length",
	    log_rtr_type(CACHE_RESET));
	return -1;
}

/*
 * Parse an Error Response message. This function behaves a bit different
 * from other parse functions since on error the connection needs to be
 * dropped without sending an error response back.
 */
static int
rtr_parse_error(struct rtr_session *rs, struct ibuf *pdu)
{
	struct rtr_header rh;
	struct ibuf err_pdu;
	uint32_t pdu_len, msg_len;
	char *str = NULL;
	uint16_t errcode;
	int rv = -1;

	if (ibuf_get(pdu, &rh, sizeof(rh)) == -1)
		goto fail;
	errcode = ntohs(rh.errcode);

	if (ibuf_get_n32(pdu, &pdu_len) == -1)
		goto fail;

	/* for now just ignore the embedded pdu */
	if (ibuf_get_ibuf(pdu, pdu_len, &err_pdu) == -1)
		goto fail;

	if (ibuf_get_n32(pdu, &msg_len) == -1)
		goto fail;

	/* optional error msg */
	if (msg_len != 0)
		if ((str = ibuf_get_string(pdu, msg_len)) == NULL)
			goto fail;

	log_warnx("rtr %s: received error: %s%s%s", log_rtr(rs),
	    log_rtr_error(errcode), str ? ": " : "", str ? str : "");

	if (errcode == NO_DATA_AVAILABLE) {
		rtr_fsm(rs, RTR_EVNT_NO_DATA);
		rv = 0;
	} else if (errcode == UNSUPP_PROTOCOL_VERS) {
		rtr_fsm(rs, RTR_EVNT_UNSUPP_PROTO_VERSION);
		rv = 0;
	} else
		rtr_fsm(rs, RTR_EVNT_RESET_AND_CLOSE);

	rs->last_recv_error = errcode;
	if (str)
		strlcpy(rs->last_recv_msg, str, sizeof(rs->last_recv_msg));
	else
		memset(rs->last_recv_msg, 0, sizeof(rs->last_recv_msg));

	free(str);
	return rv;

 fail:
	log_warnx("rtr %s: received %s: bad encoding", log_rtr(rs),
	    log_rtr_type(ERROR_REPORT));
	rtr_fsm(rs, RTR_EVNT_RESET_AND_CLOSE);
	return -1;
}

/*
 * Try to process received rtr message, it is possible that not a full
 * message is in the buffer. In that case stop, once new data is available
 * a retry will be done.
 */
static void
rtr_process_msg(struct rtr_session *rs)
{
	struct ibuf rbuf, hdr, msg;
	size_t msglen;
	enum rtr_pdu_type msgtype;

	ibuf_from_buffer(&rbuf, rs->r.buf, rs->r.wpos);

	for (;;) {
		if (ibuf_size(&rbuf) < sizeof(struct rtr_header))
			break;

		/* parse header */
		ibuf_from_buffer(&hdr, ibuf_data(&rbuf),
		    sizeof(struct rtr_header));
		if (rtr_parse_header(rs, &hdr, &msglen, &msgtype) == -1)
			return;

		/* extract message */
		if (ibuf_get_ibuf(&rbuf, msglen, &msg) == -1)
			break;

		switch (msgtype) {
		case SERIAL_NOTIFY:
			if (rtr_parse_notify(rs, &msg) == -1)
				return;
			break;
		case CACHE_RESPONSE:
			if (rtr_parse_cache_response(rs, &msg) == -1)
				return;
			break;
		case IPV4_PREFIX:
			if (rtr_parse_ipv4_prefix(rs, &msg) == -1)
				return;
			break;
		case IPV6_PREFIX:
			if (rtr_parse_ipv6_prefix(rs, &msg) == -1)
				return;
			break;
		case END_OF_DATA:
			if (rtr_parse_end_of_data(rs, &msg) == -1)
				return;
			break;
		case CACHE_RESET:
			if (rtr_parse_cache_reset(rs, &msg) == -1)
				return;
			break;
		case ROUTER_KEY:
			/* silently ignore router key */
			break;
		case ERROR_REPORT:
			if (rtr_parse_error(rs, &msg) == -1) {
				/* no need to send back an error */
				return;
			}
			break;
		case ASPA:
			if (rtr_parse_aspa(rs, &msg) == -1)
				return;
			break;
		default:
			/* unreachable, checked in rtr_parse_header() */
			rtr_send_error(rs, &msg, UNSUPP_PDU_TYPE, "type %s",
			    log_rtr_type(msgtype));
			return;
		}
	}

	memmove(&rs->r.buf, ibuf_data(&rbuf), ibuf_size(&rbuf));
	rs->r.wpos = ibuf_size(&rbuf);
}

/*
 * Simple FSM for RTR sessions
 */
static void
rtr_fsm(struct rtr_session *rs, enum rtr_event event)
{
	enum rtr_state prev_state = rs->state;

	switch (event) {
	case RTR_EVNT_UNSUPP_PROTO_VERSION:
		if (rs->prev_version == rs->version ||
		    rs->version < rs->min_version) {
			/*
			 * Can't downgrade anymore, fail connection.
			 * RFC requires sending the error with the
			 * highest supported version number.
			 */
			rs->version = rtr_max_session_version(rs);
			rtr_send_error(rs, NULL, UNSUPP_PROTOCOL_VERS,
			    "negotiation failed");
			return;
		}
		/* try again with new version */
		if (rs->session_id == -1)
			rtr_send_reset_query(rs);
		else
			rtr_send_serial_query(rs);
		break;
	case RTR_EVNT_RESET_AND_CLOSE:
		rtr_reset_cache(rs);
		rtr_recalc();
		/* FALLTHROUGH */
	case RTR_EVNT_CON_CLOSE:
		if (rs->fd != -1) {
			/* flush buffers */
			msgbuf_clear(&rs->w);
			rs->r.wpos = 0;
			close(rs->fd);
			rs->fd = -1;
			rtr_imsg_compose(IMSG_SOCKET_TEARDOWN, rs->id, 0,
			    NULL, 0);
		}
		/* try to reopen session */
		if (!rs->errored)
			timer_set(&rs->timers, Timer_Rtr_Retry,
			    arc4random_uniform(10));
		else
			timer_set(&rs->timers, Timer_Rtr_Retry, rs->retry);

		rs->errored = 1;
		/*
		 * A close event during version negotiation needs to remain
		 * in the negotiation state else the same error will happen
		 * over and over again. The RFC is utterly underspecified
		 * and some RTR caches close the connection after sending
		 * the error PDU.
		 */
		if (rs->state != RTR_STATE_NEGOTIATION)
			rs->state = RTR_STATE_CLOSED;
		break;
	case RTR_EVNT_START:
	case RTR_EVNT_TIMER_RETRY:
		switch (rs->state) {
		case RTR_STATE_ERROR:
			rtr_fsm(rs, RTR_EVNT_CON_CLOSE);
			break;
		case RTR_STATE_CLOSED:
		case RTR_STATE_NEGOTIATION:
			timer_set(&rs->timers, Timer_Rtr_Retry, rs->retry);
			rtr_imsg_compose(IMSG_SOCKET_SETUP, rs->id, 0, NULL, 0);
			break;
		case RTR_STATE_ESTABLISHED:
			if (rs->session_id == -1)
				rtr_send_reset_query(rs);
			else
				rtr_send_serial_query(rs);
		default:
			break;
		}
		break;
	case RTR_EVNT_CON_OPEN:
		timer_stop(&rs->timers, Timer_Rtr_Retry);
		rs->state = RTR_STATE_NEGOTIATION;
		if (rs->session_id == -1)
			rtr_send_reset_query(rs);
		else
			rtr_send_serial_query(rs);
		break;
	case RTR_EVNT_SERIAL_NOTIFY:
		/* schedule a refresh after a quick wait */
		timer_set(&rs->timers, Timer_Rtr_Refresh,
		    arc4random_uniform(10));
		break;
	case RTR_EVNT_TIMER_REFRESH:
		rtr_send_serial_query(rs);
		break;
	case RTR_EVNT_TIMER_EXPIRE:
		rtr_reset_cache(rs);
		rtr_recalc();
		break;
	case RTR_EVNT_TIMER_ACTIVE:
		log_warnx("rtr %s: activity timer fired", log_rtr(rs));
		rtr_sem_release(rs->active_lock);
		rtr_recalc();
		rs->active_lock = 0;
		break;
	case RTR_EVNT_CACHE_RESPONSE:
		rs->state = RTR_STATE_EXCHANGE;
		timer_stop(&rs->timers, Timer_Rtr_Refresh);
		timer_stop(&rs->timers, Timer_Rtr_Retry);
		timer_set(&rs->timers, Timer_Rtr_Active, rs->active);
		/* prevent rtr_recalc from running while active */
		rs->active_lock = 1;
		rtr_sem_acquire(rs->active_lock);
		break;
	case RTR_EVNT_END_OF_DATA:
		/* start refresh and expire timers */
		timer_set(&rs->timers, Timer_Rtr_Refresh, rs->refresh);
		timer_set(&rs->timers, Timer_Rtr_Expire, rs->expire);
		timer_stop(&rs->timers, Timer_Rtr_Active);
		rs->state = RTR_STATE_ESTABLISHED;
		rtr_sem_release(rs->active_lock);
		rtr_recalc();
		rs->active_lock = 0;
		rs->errored = 0;
		/* clear the last errors */
		rs->last_sent_error = NO_ERROR;
		rs->last_recv_error = NO_ERROR;
		rs->last_sent_msg[0] = '\0';
		rs->last_recv_msg[0] = '\0';
		break;
	case RTR_EVNT_CACHE_RESET:
		rtr_reset_cache(rs);
		rtr_recalc();
		/* retry after a quick wait */
		timer_set(&rs->timers, Timer_Rtr_Retry,
		    arc4random_uniform(10));
		break;
	case RTR_EVNT_NO_DATA:
		/* start retry timer */
		timer_set(&rs->timers, Timer_Rtr_Retry, rs->retry);
		/* stop refresh timer just to be sure */
		timer_stop(&rs->timers, Timer_Rtr_Refresh);
		rs->state = RTR_STATE_ESTABLISHED;
		break;
	case RTR_EVNT_SEND_ERROR:
		rtr_reset_cache(rs);
		rtr_recalc();
		rs->state = RTR_STATE_ERROR;
		/* flush receive buffer */
		rs->r.wpos = 0;
		break;
	case RTR_EVNT_NEGOTIATION_DONE:
		rs->state = RTR_STATE_ESTABLISHED;
		break;
	}

	log_debug("rtr %s: state change %s -> %s, reason: %s",
	    log_rtr(rs), rtr_statenames[prev_state], rtr_statenames[rs->state],
	    rtr_eventnames[event]);
}

/*
 * IO handler for RTR sessions
 */
static void
rtr_dispatch_msg(struct pollfd *pfd, struct rtr_session *rs)
{
	ssize_t n;
	int error;

	if (pfd->revents & POLLHUP) {
		log_warnx("rtr %s: Connection closed, hangup", log_rtr(rs));
		rtr_fsm(rs, RTR_EVNT_CON_CLOSE);
		return;
	}
	if (pfd->revents & (POLLERR|POLLNVAL)) {
		log_warnx("rtr %s: Connection closed, error", log_rtr(rs));
		rtr_fsm(rs, RTR_EVNT_CON_CLOSE);
		return;
	}
	if (pfd->revents & POLLOUT && msgbuf_queuelen(&rs->w) > 0) {
		if ((error = ibuf_write(&rs->w)) == -1) {
			if (errno != EAGAIN) {
				log_warn("rtr %s: write error", log_rtr(rs));
				rtr_fsm(rs, RTR_EVNT_CON_CLOSE);
			}
		}
		if (error == 0)
			rtr_fsm(rs, RTR_EVNT_CON_CLOSE);
		if (rs->state == RTR_STATE_ERROR &&
		    msgbuf_queuelen(&rs->w) == 0)
			rtr_fsm(rs, RTR_EVNT_CON_CLOSE);
	}
	if (pfd->revents & POLLIN) {
		if ((n = read(rs->fd, rs->r.buf + rs->r.wpos,
		    sizeof(rs->r.buf) - rs->r.wpos)) == -1) {
			if (errno != EINTR && errno != EAGAIN) {
				log_warn("rtr %s: read error", log_rtr(rs));
				rtr_fsm(rs, RTR_EVNT_CON_CLOSE);
			}
			return;
		}
		if (n == 0) {
			rtr_fsm(rs, RTR_EVNT_CON_CLOSE);
			return;
		}
		rs->r.wpos += n;

		/* new data arrived, try to process it */
		rtr_process_msg(rs);
	}

}

void
rtr_check_events(struct pollfd *pfds, size_t npfds)
{
	struct rtr_session *rs;
	struct timer *t;
	time_t now;
	size_t i = 0;

	for (i = 0; i < npfds; i++) {
		if (pfds[i].revents == 0)
			continue;
		TAILQ_FOREACH(rs, &rtrs, entry)
			if (rs->fd == pfds[i].fd) {
				rtr_dispatch_msg(&pfds[i], rs);
				break;
			}
		if (rs == NULL)
			log_warnx("%s: unknown fd in pollfds", __func__);
	}

	/* run all timers */
	now = getmonotime();
	TAILQ_FOREACH(rs, &rtrs, entry)
		if ((t = timer_nextisdue(&rs->timers, now)) != NULL) {
			/* stop timer so it does not trigger again */
			timer_stop(&rs->timers, t->type);
			switch (t->type) {
			case Timer_Rtr_Refresh:
				rtr_fsm(rs, RTR_EVNT_TIMER_REFRESH);
				break;
			case Timer_Rtr_Retry:
				rtr_fsm(rs, RTR_EVNT_TIMER_RETRY);
				break;
			case Timer_Rtr_Expire:
				rtr_fsm(rs, RTR_EVNT_TIMER_EXPIRE);
				break;
			case Timer_Rtr_Active:
				rtr_fsm(rs, RTR_EVNT_TIMER_ACTIVE);
				break;
			default:
				fatalx("King Bula lost in time");
			}
		}
}

size_t
rtr_count(void)
{
	struct rtr_session *rs;
	size_t count = 0;

	TAILQ_FOREACH(rs, &rtrs, entry)
		count++;
	return count;
}

size_t
rtr_poll_events(struct pollfd *pfds, size_t npfds, time_t *timeout)
{
	struct rtr_session *rs;
	time_t now = getmonotime();
	size_t i = 0;

	TAILQ_FOREACH(rs, &rtrs, entry) {
		time_t nextaction;
		struct pollfd *pfd = pfds + i++;

		if (i > npfds)
			fatalx("%s: too many sessions for pollfd", __func__);

		if ((nextaction = timer_nextduein(&rs->timers, now)) != -1 &&
		    nextaction < *timeout)
			*timeout = nextaction;

		if (rs->state == RTR_STATE_CLOSED) {
			pfd->fd = -1;
			continue;
		}

		pfd->fd = rs->fd;
		pfd->events = 0;

		if (msgbuf_queuelen(&rs->w) > 0)
			pfd->events |= POLLOUT;
		if (rs->state >= RTR_STATE_ESTABLISHED)
			pfd->events |= POLLIN;
	}

	return i;
}

struct rtr_session *
rtr_new(uint32_t id, struct rtr_config_msg *conf)
{
	struct rtr_session *rs;

	if ((rs = calloc(1, sizeof(*rs))) == NULL)
		fatal("RTR session %s", conf->descr);

	RB_INIT(&rs->roa_set);
	RB_INIT(&rs->aspa);
	TAILQ_INIT(&rs->timers);
	msgbuf_init(&rs->w);

	strlcpy(rs->descr, conf->descr, sizeof(rs->descr));
	rs->id = id;
	rs->session_id = -1;
	rs->min_version = conf->min_version;	/* must be set before version */
	rs->version = rtr_max_session_version(rs);
	rs->prev_version = rtr_max_session_version(rs);
	rs->refresh = RTR_DEFAULT_REFRESH;
	rs->retry = RTR_DEFAULT_RETRY;
	rs->expire = RTR_DEFAULT_EXPIRE;
	rs->active = RTR_DEFAULT_ACTIVE;
	rs->state = RTR_STATE_CLOSED;
	rs->reconf_action = RECONF_REINIT;
	rs->last_recv_error = NO_ERROR;
	rs->last_sent_error = NO_ERROR;

	/* make sure that some timer is running to abort bad sessions */
	timer_set(&rs->timers, Timer_Rtr_Expire, rs->expire);

	log_debug("rtr %s: new session, start", log_rtr(rs));
	TAILQ_INSERT_TAIL(&rtrs, rs, entry);
	rtr_fsm(rs, RTR_EVNT_START);

	return rs;
}

struct rtr_session *
rtr_get(uint32_t id)
{
	struct rtr_session *rs;

	TAILQ_FOREACH(rs, &rtrs, entry)
		if (rs->id == id)
			return rs;
	return NULL;
}

void
rtr_free(struct rtr_session *rs)
{
	if (rs == NULL)
		return;

	rtr_reset_cache(rs);
	rtr_fsm(rs, RTR_EVNT_CON_CLOSE);
	timer_remove_all(&rs->timers);
	free(rs);
}

void
rtr_open(struct rtr_session *rs, int fd)
{
	if (rs->state != RTR_STATE_CLOSED &&
	    rs->state != RTR_STATE_NEGOTIATION) {
		log_warnx("rtr %s: bad session state", log_rtr(rs));
		rtr_fsm(rs, RTR_EVNT_CON_CLOSE);
	}

	if (rs->state == RTR_STATE_CLOSED) {
		rs->version = rtr_max_session_version(rs);
		rs->prev_version = rtr_max_session_version(rs);
	}

	rs->fd = rs->w.fd = fd;
	rtr_fsm(rs, RTR_EVNT_CON_OPEN);
}

void
rtr_config_prep(void)
{
	struct rtr_session *rs;

	TAILQ_FOREACH(rs, &rtrs, entry)
		rs->reconf_action = RECONF_DELETE;
}

void
rtr_config_merge(void)
{
	struct rtr_session *rs, *nrs;

	TAILQ_FOREACH_SAFE(rs, &rtrs, entry, nrs)
		if (rs->reconf_action == RECONF_DELETE) {
			TAILQ_REMOVE(&rtrs, rs, entry);
			rtr_free(rs);
		}
}

void
rtr_config_keep(struct rtr_session *rs, struct rtr_config_msg *conf)
{
	strlcpy(rs->descr, conf->descr, sizeof(rs->descr));
	rs->min_version = conf->min_version;
	rs->reconf_action = RECONF_KEEP;
}

void
rtr_roa_merge(struct roa_tree *rt)
{
	struct rtr_session *rs;
	struct roa *roa;

	TAILQ_FOREACH(rs, &rtrs, entry) {
		RB_FOREACH(roa, roa_tree, &rs->roa_set)
			rtr_roa_insert(rt, roa);
	}
}

void
rtr_aspa_merge(struct aspa_tree *at)
{
	struct rtr_session *rs;
	struct aspa_set *aspa;

	TAILQ_FOREACH(rs, &rtrs, entry) {
		RB_FOREACH(aspa, aspa_tree, &rs->aspa)
			rtr_aspa_insert(at, aspa);
	}
}

void
rtr_shutdown(void)
{
	struct rtr_session *rs, *nrs;

	TAILQ_FOREACH_SAFE(rs, &rtrs, entry, nrs)
		rtr_free(rs);
}

void
rtr_show(struct rtr_session *rs, pid_t pid)
{
	struct ctl_show_rtr msg;
	struct ctl_timer ct;
	u_int i;
	time_t d;

	memset(&msg, 0, sizeof(msg));

	/* descr, remote_addr, local_addr and remote_port set by parent */
	msg.version = rs->version;
	msg.min_version = rs->min_version;
	msg.serial = rs->serial;
	msg.refresh = rs->refresh;
	msg.retry = rs->retry;
	msg.expire = rs->expire;
	msg.session_id = rs->session_id;
	msg.last_sent_error = rs->last_sent_error;
	msg.last_recv_error = rs->last_recv_error;
	strlcpy(msg.state, rtr_statenames[rs->state], sizeof(msg.state));
	strlcpy(msg.last_sent_msg, rs->last_sent_msg,
	    sizeof(msg.last_sent_msg));
	strlcpy(msg.last_recv_msg, rs->last_recv_msg,
	    sizeof(msg.last_recv_msg));

	/* send back imsg */
	rtr_imsg_compose(IMSG_CTL_SHOW_RTR, rs->id, pid, &msg, sizeof(msg));

	/* send back timer imsgs */
	for (i = 1; i < Timer_Max; i++) {
		if (!timer_running(&rs->timers, i, &d))
			continue;
		ct.type = i;
		ct.val = d;
		rtr_imsg_compose(IMSG_CTL_SHOW_TIMER, rs->id, pid,
		    &ct, sizeof(ct));
	}
}