Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
/*	$NetBSD: dhcrelay.c,v 1.2 2018/04/07 22:37:30 christos Exp $	*/

/* dhcrelay.c

   DHCP/BOOTP Relay Agent. */

/*
 * Copyright(c) 2004-2018 by Internet Systems Consortium, Inc.("ISC")
 * Copyright(c) 1997-2003 by Internet Software Consortium
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC 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.
 *
 *   Internet Systems Consortium, Inc.
 *   950 Charter Street
 *   Redwood City, CA 94063
 *   <info@isc.org>
 *   https://www.isc.org/
 *
 */

#include <sys/cdefs.h>
__RCSID("$NetBSD: dhcrelay.c,v 1.2 2018/04/07 22:37:30 christos Exp $");

#include "dhcpd.h"
#include <syslog.h>
#include <signal.h>
#include <sys/time.h>
#include <isc/file.h>

TIME default_lease_time = 43200; /* 12 hours... */
TIME max_lease_time = 86400; /* 24 hours... */
struct tree_cache *global_options[256];

struct option *requested_opts[2];

/* Needed to prevent linking against conflex.c. */
int lexline;
int lexchar;
char *token_line;
char *tlname;

const char *path_dhcrelay_pid = _PATH_DHCRELAY_PID;
isc_boolean_t no_dhcrelay_pid = ISC_FALSE;
/* False (default) => we write and use a pid file */
isc_boolean_t no_pid_file = ISC_FALSE;

int bogus_agent_drops = 0;	/* Packets dropped because agent option
				   field was specified and we're not relaying
				   packets that already have an agent option
				   specified. */
int bogus_giaddr_drops = 0;	/* Packets sent to us to relay back to a
				   client, but with a bogus giaddr. */
int client_packets_relayed = 0;	/* Packets relayed from client to server. */
int server_packet_errors = 0;	/* Errors sending packets to servers. */
int server_packets_relayed = 0;	/* Packets relayed from server to client. */
int client_packet_errors = 0;	/* Errors sending packets to clients. */

int add_agent_options = 0;	/* If nonzero, add relay agent options. */
int add_rfc3527_suboption = 0;	/* If nonzero, add RFC3527 link selection sub-option. */

int agent_option_errors = 0;    /* Number of packets forwarded without
				   agent options because there was no room. */
int drop_agent_mismatches = 0;	/* If nonzero, drop server replies that
				   don't have matching circuit-id's. */
int corrupt_agent_options = 0;	/* Number of packets dropped because
				   relay agent information option was bad. */
int missing_agent_option = 0;	/* Number of packets dropped because no
				   RAI option matching our ID was found. */
int bad_circuit_id = 0;		/* Circuit ID option in matching RAI option
				   did not match any known circuit ID. */
int missing_circuit_id = 0;	/* Circuit ID option in matching RAI option
				   was missing. */
int max_hop_count = 10;		/* Maximum hop count */

int no_daemon = 0;
int dfd[2] = { -1, -1 };

#ifdef DHCPv6
	/* Force use of DHCPv6 interface-id option. */
isc_boolean_t use_if_id = ISC_FALSE;
#endif

	/* Maximum size of a packet with agent options added. */
int dhcp_max_agent_option_packet_length = DHCP_MTU_MIN;

	/* What to do about packets we're asked to relay that
	   already have a relay option: */
enum { forward_and_append,	/* Forward and append our own relay option. */
       forward_and_replace,	/* Forward, but replace theirs with ours. */
       forward_untouched,	/* Forward without changes. */
       discard } agent_relay_mode = forward_and_replace;

u_int16_t local_port = 0;
u_int16_t remote_port = 0;

/* Relay agent server list. */
struct server_list {
	struct server_list *next;
	struct sockaddr_in to;
} *servers;

struct interface_info *uplink = NULL;

#ifdef DHCPv6
struct stream_list {
	struct stream_list *next;
	struct interface_info *ifp;
	struct sockaddr_in6 link;
	int id;
} *downstreams, *upstreams;

static struct stream_list *parse_downstream(char *);
static struct stream_list *parse_upstream(char *);
static void setup_streams(void);

/*
 * A pointer to a subscriber id to add to the message we forward.
 * This is primarily for testing purposes as we only have one id
 * for the entire relay and don't determine one per client which
 * would be more useful.
 */
char *dhcrelay_sub_id = NULL;
#endif

libdhcp_callbacks_t dhcrelay_callbacks = {
	&local_port,
	&remote_port,
	classify,
	check_collection,
	dhcp,
#ifdef DHCPv6
	dhcpv6,
#endif /* DHCPv6 */
	bootp,
	find_class,
	parse_allow_deny,
	dhcp_set_control_state,
};

static void do_relay4(struct interface_info *, struct dhcp_packet *,
	              unsigned int, unsigned int, struct iaddr,
		      struct hardware *);
static int add_relay_agent_options(struct interface_info *,
				   struct dhcp_packet *, unsigned,
				   struct in_addr);
static int find_interface_by_agent_option(struct dhcp_packet *,
			       struct interface_info **, u_int8_t *, int);
static int strip_relay_agent_options(struct interface_info *,
				     struct interface_info **,
				     struct dhcp_packet *, unsigned);

static void request_v4_interface(const char* name, int flags);

static const char copyright[] =
"Copyright 2004-2018 Internet Systems Consortium.";
static const char arr[] = "All rights reserved.";
static const char message[] =
"Internet Systems Consortium DHCP Relay Agent";
static const char url[] =
"For info, please visit https://www.isc.org/software/dhcp/";

char *progname;

#ifdef DHCPv6
#ifdef RELAY_PORT
#define DHCRELAY_USAGE \
"Usage: %s [-4] [-d] [-q] [-a] [-D]\n" \
"                     [-A <length>] [-c <hops>]\n" \
"                     [-p <port> | -rp <relay-port>]\n" \
"                     [-pf <pid-file>] [--no-pid]\n"\
"                     [-m append|replace|forward|discard]\n" \
"                     [-i interface0 [ ... -i interfaceN]\n" \
"                     [-iu interface0 [ ... -iu interfaceN]\n" \
"                     [-id interface0 [ ... -id interfaceN]\n" \
"                     [-U interface]\n" \
"                     server0 [ ... serverN]\n\n" \
"       %s -6   [-d] [-q] [-I] [-c <hops>]\n" \
"                     [-p <port> | -rp <relay-port>]\n" \
"                     [-pf <pid-file>] [--no-pid]\n" \
"                     [-s <subscriber-id>]\n" \
"                     -l lower0 [ ... -l lowerN]\n" \
"                     -u upper0 [ ... -u upperN]\n" \
"           lower (client link): [address%%]interface[#index]\n" \
"           upper (server link): [address%%]interface\n\n" \
"       %s {--version|--help|-h}"
#else
#define DHCRELAY_USAGE \
"Usage: %s [-4] [-d] [-q] [-a] [-D]\n" \
"                     [-A <length>] [-c <hops>] [-p <port>]\n" \
"                     [-pf <pid-file>] [--no-pid]\n"\
"                     [-m append|replace|forward|discard]\n" \
"                     [-i interface0 [ ... -i interfaceN]\n" \
"                     [-iu interface0 [ ... -iu interfaceN]\n" \
"                     [-id interface0 [ ... -id interfaceN]\n" \
"                     [-U interface]\n" \
"                     server0 [ ... serverN]\n\n" \
"       %s -6   [-d] [-q] [-I] [-c <hops>] [-p <port>]\n" \
"                     [-pf <pid-file>] [--no-pid]\n" \
"                     [-s <subscriber-id>]\n" \
"                     -l lower0 [ ... -l lowerN]\n" \
"                     -u upper0 [ ... -u upperN]\n" \
"           lower (client link): [address%%]interface[#index]\n" \
"           upper (server link): [address%%]interface\n\n" \
"       %s {--version|--help|-h}"
#endif
#else /* !DHCPv6 */
#ifdef RELAY_PORT
#define DHCRELAY_USAGE \
"Usage: %s [-d] [-q] [-a] [-D] [-A <length>] [-c <hops>]\n" \
"                [-p <port> | -rp <relay-port>]\n" \
"                [-pf <pid-file>] [--no-pid]\n" \
"                [-m append|replace|forward|discard]\n" \
"                [-i interface0 [ ... -i interfaceN]\n" \
"                [-iu interface0 [ ... -iu interfaceN]\n" \
"                [-id interface0 [ ... -id interfaceN]\n" \
"                [-U interface]\n" \
"                server0 [ ... serverN]\n\n" \
"       %s {--version|--help|-h}"
#else
#define DHCRELAY_USAGE \
"Usage: %s [-d] [-q] [-a] [-D] [-A <length>] [-c <hops>] [-p <port>]\n" \
"                [-pf <pid-file>] [--no-pid]\n" \
"                [-m append|replace|forward|discard]\n" \
"                [-i interface0 [ ... -i interfaceN]\n" \
"                [-iu interface0 [ ... -iu interfaceN]\n" \
"                [-id interface0 [ ... -id interfaceN]\n" \
"                [-U interface]\n" \
"                server0 [ ... serverN]\n\n" \
"       %s {--version|--help|-h}"
#endif
#endif

/*!
 *
 * \brief Print the generic usage message
 *
 * If the user has provided an incorrect command line print out
 * the description of the command line.  The arguments provide
 * a way for the caller to request more specific information about
 * the error be printed as well.  Mostly this will be that some
 * comamnd doesn't include its argument.
 *
 * \param sfmt - The basic string and format for the specific error
 * \param sarg - Generally the offending argument from the comamnd line.
 *
 * \return Nothing
 */

#include <sys/cdefs.h>
__RCSID("$NetBSD: dhcrelay.c,v 1.2 2018/04/07 22:37:30 christos Exp $");
static const char use_noarg[] = "No argument for command: %s";
#ifdef RELAY_PORT
static const char use_port_defined[] = "Port already set, %s inappropriate";
#if !defined (USE_BPF_RECEIVE) && !defined (USE_LPF_RECEIVE)
static const char bpf_sock_support[] = "Only LPF and BPF are supported: %s";
#endif
#endif
#ifdef DHCPv6
static const char use_badproto[] = "Protocol already set, %s inappropriate";
static const char use_v4command[] = "Command not used for DHCPv6: %s";
static const char use_v6command[] = "Command not used for DHCPv4: %s";
#endif

static void
usage(const char *sfmt, const char *sarg) {
	log_info("%s %s", message, PACKAGE_VERSION);
	log_info(copyright);
	log_info(arr);
	log_info(url);

	/* If desired print out the specific error message */
#ifdef PRINT_SPECIFIC_CL_ERRORS
	if (sfmt != NULL)
		log_error(sfmt, sarg);
#endif

	log_fatal(DHCRELAY_USAGE,
#ifdef DHCPv6
		  isc_file_basename(progname),
#endif
		  isc_file_basename(progname),
		  isc_file_basename(progname));
}

int 
main(int argc, char **argv) {
	isc_result_t status;
	struct servent *ent;
	struct server_list *sp = NULL;
	char *service_local = NULL, *service_remote = NULL;
	u_int16_t port_local = 0, port_remote = 0;
	int quiet = 0;
	int fd;
	int i;
#ifdef RELAY_PORT
	int port_defined = 0;
#endif
#ifdef DHCPv6
	struct stream_list *sl = NULL;
	int local_family_set = 0;
#endif

#ifdef OLD_LOG_NAME
	progname = "dhcrelay";
#else
	progname = argv[0];
#endif

	/* Make sure that file descriptors 0(stdin), 1,(stdout), and
	   2(stderr) are open. To do this, we assume that when we
	   open a file the lowest available file descriptor is used. */
	fd = open("/dev/null", O_RDWR);
	if (fd == 0)
		fd = open("/dev/null", O_RDWR);
	if (fd == 1)
		fd = open("/dev/null", O_RDWR);
	if (fd == 2)
		log_perror = 0; /* No sense logging to /dev/null. */
	else if (fd != -1)
		close(fd);

	openlog(isc_file_basename(progname), DHCP_LOG_OPTIONS, LOG_DAEMON);

#if !defined(DEBUG)
	setlogmask(LOG_UPTO(LOG_INFO));
#endif	

	/* Parse arguments changing no_daemon */
	for (i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "-d")) {
			no_daemon = 1;
		} else if (!strcmp(argv[i], "--version")) {
			log_info("isc-dhcrelay-%s", PACKAGE_VERSION);
			exit(0);
		} else if (!strcmp(argv[i], "--help") ||
			   !strcmp(argv[i], "-h")) {
			log_info(DHCRELAY_USAGE,
#ifdef DHCPv6
				 isc_file_basename(progname),
#endif
				 isc_file_basename(progname),
				 isc_file_basename(progname));
			exit(0);
		}
	}
	/* When not forbidden prepare to become a daemon */
	if (!no_daemon) {
		int pid;

		if (pipe(dfd) == -1)
			log_fatal("Can't get pipe: %m");
		if ((pid = fork ()) < 0)
			log_fatal("Can't fork daemon: %m");
		if (pid != 0) {
			/* Parent: wait for the child to start */
			int n;

			(void) close(dfd[1]);
			do {
				char buf;

				n = read(dfd[0], &buf, 1);
				if (n == 1)
					_exit(0);
			} while (n == -1 && errno == EINTR);
			_exit(1);
		}
		/* Child */
		(void) close(dfd[0]);
	}


	/* Set up the isc and dns library managers */
	status = dhcp_context_create(DHCP_CONTEXT_PRE_DB, NULL, NULL);
	if (status != ISC_R_SUCCESS)
		log_fatal("Can't initialize context: %s",
			  isc_result_totext(status));

	/* Set up the OMAPI. */
	status = omapi_init();
	if (status != ISC_R_SUCCESS)
		log_fatal("Can't initialize OMAPI: %s",
			   isc_result_totext(status));

	/* Set up the OMAPI wrappers for the interface object. */
	interface_setup();

	for (i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "-4")) {
#ifdef DHCPv6
			if (local_family_set && (local_family == AF_INET6)) {
				usage(use_badproto, "-4");
			}
			local_family_set = 1;
			local_family = AF_INET;
		} else if (!strcmp(argv[i], "-6")) {
			if (local_family_set && (local_family == AF_INET)) {
				usage(use_badproto, "-6");
			}
			local_family_set = 1;
			local_family = AF_INET6;
#endif
		} else if (!strcmp(argv[i], "-d")) {
			/* no_daemon = 1; */
		} else if (!strcmp(argv[i], "-q")) {
			quiet = 1;
			quiet_interface_discovery = 1;
		} else if (!strcmp(argv[i], "-p")) {
			if (++i == argc)
				usage(use_noarg, argv[i-1]);
#ifdef RELAY_PORT
			if (port_defined)
				usage(use_port_defined, argv[i-1]);
			port_defined = 1;
#endif
			local_port = validate_port(argv[i]);
			log_debug("binding to user-specified port %d",
				  ntohs(local_port));
#ifdef RELAY_PORT
		} else if (!strcmp(argv[i], "-rp")) {
			if (++i == argc)
				usage(use_noarg, argv[i-1]);
			if (port_defined)
				usage(use_port_defined, argv[i-1]);
			port_defined = 1;
			relay_port = validate_port(argv[i]);
			log_debug("binding to user-specified relay port %d",
				  ntohs(relay_port));
			add_agent_options = 1;
#endif
		} else if (!strcmp(argv[i], "-c")) {
			int hcount;
			if (++i == argc)
				usage(use_noarg, argv[i-1]);
			hcount = atoi(argv[i]);
			if (hcount <= 255)
				max_hop_count= hcount;
			else
				usage("Bad hop count to -c: %s", argv[i]);
 		} else if (!strcmp(argv[i], "-i")) {
#ifdef DHCPv6
			if (local_family_set && (local_family == AF_INET6)) {
				usage(use_v4command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET;
#endif
			if (++i == argc) {
				usage(use_noarg, argv[i-1]);
			}

			request_v4_interface(argv[i], INTERFACE_STREAMS);
		} else if (!strcmp(argv[i], "-iu")) {
#ifdef DHCPv6
			if (local_family_set && (local_family == AF_INET6)) {
				usage(use_v4command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET;
#endif
			if (++i == argc) {
				usage(use_noarg, argv[i-1]);
			}

			request_v4_interface(argv[i], INTERFACE_UPSTREAM);
		} else if (!strcmp(argv[i], "-id")) {
#ifdef DHCPv6
			if (local_family_set && (local_family == AF_INET6)) {
				usage(use_v4command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET;
#endif
			if (++i == argc) {
				usage(use_noarg, argv[i-1]);
			}

			request_v4_interface(argv[i], INTERFACE_DOWNSTREAM);
		} else if (!strcmp(argv[i], "-a")) {
#ifdef DHCPv6
			if (local_family_set && (local_family == AF_INET6)) {
				usage(use_v4command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET;
#endif
			add_agent_options = 1;
		} else if (!strcmp(argv[i], "-A")) {
#ifdef DHCPv6
			if (local_family_set && (local_family == AF_INET6)) {
				usage(use_v4command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET;
#endif
			if (++i == argc)
				usage(use_noarg, argv[i-1]);

			dhcp_max_agent_option_packet_length = atoi(argv[i]);

			if (dhcp_max_agent_option_packet_length > DHCP_MTU_MAX)
				log_fatal("%s: packet length exceeds "
					  "longest possible MTU\n",
					  argv[i]);
		} else if (!strcmp(argv[i], "-m")) {
#ifdef DHCPv6
			if (local_family_set && (local_family == AF_INET6)) {
				usage(use_v4command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET;
#endif
			if (++i == argc)
				usage(use_noarg, argv[i-1]);
			if (!strcasecmp(argv[i], "append")) {
				agent_relay_mode = forward_and_append;
			} else if (!strcasecmp(argv[i], "replace")) {
				agent_relay_mode = forward_and_replace;
			} else if (!strcasecmp(argv[i], "forward")) {
				agent_relay_mode = forward_untouched;
			} else if (!strcasecmp(argv[i], "discard")) {
				agent_relay_mode = discard;
			} else
				usage("Unknown argument to -m: %s", argv[i]);
		} else if (!strcmp(argv [i], "-U")) {
			if (++i == argc)
				usage(use_noarg, argv[i-1]);

			if (uplink) {
				usage("more than one uplink (-U) specified: %s"
				      ,argv[i]);
			}

			/* Allocate the uplink interface */
			status = interface_allocate(&uplink, MDL);
			if (status != ISC_R_SUCCESS) {
				log_fatal("%s: uplink interface_allocate: %s",
					 argv[i], isc_result_totext(status));
			}
		
			if (strlen(argv[i]) >= sizeof(uplink->name)) {
				log_fatal("%s: uplink name too long,"
					  " it cannot exceed: %ld characters",
					  argv[i], (long)(sizeof(uplink->name) - 1));
			}

			uplink->name[sizeof(uplink->name) - 1] = 0x00;
			strncpy(uplink->name, argv[i],
				sizeof(uplink->name) - 1);
			interface_snorf(uplink, (INTERFACE_REQUESTED |
						INTERFACE_STREAMS));

			/* Turn on -a, in case they don't do so explicitly */
			add_agent_options = 1;
			add_rfc3527_suboption = 1;
		} else if (!strcmp(argv[i], "-D")) {
#ifdef DHCPv6
			if (local_family_set && (local_family == AF_INET6)) {
				usage(use_v4command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET;
#endif
			drop_agent_mismatches = 1;
#ifdef DHCPv6
		} else if (!strcmp(argv[i], "-I")) {
			if (local_family_set && (local_family == AF_INET)) {
				usage(use_v6command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET6;
			use_if_id = ISC_TRUE;
		} else if (!strcmp(argv[i], "-l")) {
			if (local_family_set && (local_family == AF_INET)) {
				usage(use_v6command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET6;
			if (downstreams != NULL)
				use_if_id = ISC_TRUE;
			if (++i == argc)
				usage(use_noarg, argv[i-1]);
			sl = parse_downstream(argv[i]);
			sl->next = downstreams;
			downstreams = sl;
		} else if (!strcmp(argv[i], "-u")) {
			if (local_family_set && (local_family == AF_INET)) {
				usage(use_v6command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET6;
			if (++i == argc)
				usage(use_noarg, argv[i-1]);
			sl = parse_upstream(argv[i]);
			sl->next = upstreams;
			upstreams = sl;
		} else if (!strcmp(argv[i], "-s")) {
			if (local_family_set && (local_family == AF_INET)) {
				usage(use_v6command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET6;
			if (++i == argc)
				usage(use_noarg, argv[i-1]);
			dhcrelay_sub_id = argv[i];
#endif
		} else if (!strcmp(argv[i], "-pf")) {
			if (++i == argc)
				usage(use_noarg, argv[i-1]);
			path_dhcrelay_pid = argv[i];
			no_dhcrelay_pid = ISC_TRUE;
		} else if (!strcmp(argv[i], "--no-pid")) {
			no_pid_file = ISC_TRUE;
 		} else if (argv[i][0] == '-') {
			usage("Unknown command: %s", argv[i]);
 		} else {
			struct hostent *he;
			struct in_addr ia, *iap = NULL;

#ifdef DHCPv6
			if (local_family_set && (local_family == AF_INET6)) {
				usage(use_v4command, argv[i]);
			}
			local_family_set = 1;
			local_family = AF_INET;
#endif
			if (inet_aton(argv[i], &ia)) {
				iap = &ia;
			} else {
				he = gethostbyname(argv[i]);
				if (!he) {
					log_error("%s: host unknown", argv[i]);
				} else {
					iap = ((struct in_addr *)
					       he->h_addr_list[0]);
				}
			}

			if (iap) {
				sp = ((struct server_list *)
				      dmalloc(sizeof *sp, MDL));
				if (!sp)
					log_fatal("no memory for server.\n");
				sp->next = servers;
				servers = sp;
				memcpy(&sp->to.sin_addr, iap, sizeof *iap);
			}
 		}
	}

#if defined(RELAY_PORT) && \
    !defined (USE_BPF_RECEIVE) && !defined (USE_LPF_RECEIVE)
	if (relay_port && (local_family == AF_INET))
		usage(bpf_sock_support, "-rp");
#endif

	/*
	 * If the user didn't specify a pid file directly
	 * find one from environment variables or defaults
	 */
	if (no_dhcrelay_pid == ISC_FALSE) {
		if (local_family == AF_INET) {
			path_dhcrelay_pid = getenv("PATH_DHCRELAY_PID");
			if (path_dhcrelay_pid == NULL)
				path_dhcrelay_pid = _PATH_DHCRELAY_PID;
		}
#ifdef DHCPv6
		else {
			path_dhcrelay_pid = getenv("PATH_DHCRELAY6_PID");
			if (path_dhcrelay_pid == NULL)
				path_dhcrelay_pid = _PATH_DHCRELAY6_PID;
		}
#endif
	}

	if (!quiet) {
		log_info("%s %s", message, PACKAGE_VERSION);
		log_info(copyright);
		log_info(arr);
		log_info(url);
	} else 
		log_perror = 0;

	/* Set default port */
	if (local_family == AF_INET) {
 		service_local = "bootps";
 		service_remote = "bootpc";
		port_local = htons(67);
 		port_remote = htons(68);
	}
#ifdef DHCPv6
	else {
		service_local = "dhcpv6-server";
		service_remote = "dhcpv6-client";
		port_local = htons(547);
		port_remote = htons(546);
	}
#endif

	if (!local_port) {
		ent = getservbyname(service_local, "udp");
		if (ent)
			local_port = ent->s_port;
		else
			local_port = port_local;

		ent = getservbyname(service_remote, "udp");
		if (ent)
			remote_port = ent->s_port;
		else
			remote_port = port_remote;

		endservent();
	}

	if (local_family == AF_INET) {
		/* We need at least one server */
		if (servers == NULL) {
			log_fatal("No servers specified.");
		}


		/* Set up the server sockaddrs. */
		for (sp = servers; sp; sp = sp->next) {
			sp->to.sin_port = local_port;
			sp->to.sin_family = AF_INET;
#ifdef HAVE_SA_LEN
			sp->to.sin_len = sizeof sp->to;
#endif
		}
	}
#ifdef DHCPv6
	else {
		unsigned code;

		/* We need at least one upstream and one downstream interface */
		if (upstreams == NULL || downstreams == NULL) {
			log_info("Must specify at least one lower "
				 "and one upper interface.\n");
			usage(NULL, NULL);
		}

		/* Set up the initial dhcp option universe. */
		initialize_common_option_spaces();

		/* Check requested options. */
		code = D6O_RELAY_MSG;
		if (!option_code_hash_lookup(&requested_opts[0],
					     dhcpv6_universe.code_hash,
					     &code, 0, MDL))
			log_fatal("Unable to find the RELAY_MSG "
				  "option definition.");
		code = D6O_INTERFACE_ID;
		if (!option_code_hash_lookup(&requested_opts[1],
					     dhcpv6_universe.code_hash,
					     &code, 0, MDL))
			log_fatal("Unable to find the INTERFACE_ID "
				  "option definition.");
	}
#endif

	/* Become a daemon... */
	if (!no_daemon) {
		char buf = 0;
		FILE *pf;
		int pfdesc;

		log_perror = 0;

		/* Signal parent we started successfully. */
		if (dfd[0] != -1 && dfd[1] != -1) {
			if (write(dfd[1], &buf, 1) != 1)
				log_fatal("write to parent: %m");
			(void) close(dfd[1]);
			dfd[0] = dfd[1] = -1;
		}

		/* Create the pid file. */
		if (no_pid_file == ISC_FALSE) {
			pfdesc = open(path_dhcrelay_pid,
				      O_CREAT | O_TRUNC | O_WRONLY, 0644);

			if (pfdesc < 0) {
				log_error("Can't create %s: %m",
					  path_dhcrelay_pid);
			} else {
				pf = fdopen(pfdesc, "w");
				if (!pf)
					log_error("Can't fdopen %s: %m",
						  path_dhcrelay_pid);
				else {
					fprintf(pf, "%ld\n",(long)getpid());
					fclose(pf);
				}	
			}
		}

		(void) close(0);
		(void) close(1);
		(void) close(2);
		(void) setsid();

		IGNORE_RET (chdir("/"));
	}

	/* Set up the isc and dns library managers */
	status = dhcp_context_create(DHCP_CONTEXT_PRE_DB | DHCP_CONTEXT_POST_DB,
				     NULL, NULL);
	if (status != ISC_R_SUCCESS)
		log_fatal("Can't initialize context: %s",
			  isc_result_totext(status));

	/* Get the current time... */
	gettimeofday(&cur_tv, NULL);

	/* Discover all the network interfaces. */
	discover_interfaces(DISCOVER_RELAY);

#ifdef DHCPv6
	if (local_family == AF_INET6)
		setup_streams();
#endif

	/* Set up the packet handler... */
	if (local_family == AF_INET)
		bootp_packet_handler = do_relay4;
#ifdef DHCPv6
	else
		dhcpv6_packet_handler = do_packet6;
#endif

#if defined(ENABLE_GENTLE_SHUTDOWN)
	/* no signal handlers until we deal with the side effects */
        /* install signal handlers */
	signal(SIGINT, dhcp_signal_handler);   /* control-c */
	signal(SIGTERM, dhcp_signal_handler);  /* kill */
#endif

	/* Start dispatching packets and timeouts... */
	dispatch();

	/* In fact dispatch() never returns. */
	return (0);
}

static void
do_relay4(struct interface_info *ip, struct dhcp_packet *packet,
	  unsigned int length, unsigned int from_port, struct iaddr from,
	  struct hardware *hfrom) {
	struct server_list *sp;
	struct sockaddr_in to;
	struct interface_info *out;
	struct hardware hto, *htop;

	if (packet->hlen > sizeof packet->chaddr) {
		log_info("Discarding packet with invalid hlen, received on "
			 "%s interface.", ip->name);
		return;
	}
	if (ip->address_count < 1 || ip->addresses == NULL) {
		log_info("Discarding packet received on %s interface that "
			 "has no IPv4 address assigned.", ip->name);
		return;
	}

	/* Find the interface that corresponds to the giaddr
	   in the packet. */
	if (packet->giaddr.s_addr) {
		for (out = interfaces; out; out = out->next) {
			int i;

			for (i = 0 ; i < out->address_count ; i++ ) {
				if (out->addresses[i].s_addr ==
				    packet->giaddr.s_addr) {
					i = -1;
					break;
				}
			}

			if (i == -1)
				break;
		}
	} else {
		out = NULL;
	}

	/* If it's a bootreply, forward it to the client. */
	if (packet->op == BOOTREPLY) {
		if (!(ip->flags & INTERFACE_UPSTREAM)) {
			log_debug("Dropping reply received on %s", ip->name);
			return;
		}

		if (!(packet->flags & htons(BOOTP_BROADCAST)) &&
			can_unicast_without_arp(out)) {
			to.sin_addr = packet->yiaddr;
			to.sin_port = remote_port;

			/* and hardware address is not broadcast */
			htop = &hto;
		} else {
			to.sin_addr.s_addr = htonl(INADDR_BROADCAST);
			to.sin_port = remote_port;

			/* hardware address is broadcast */
			htop = NULL;
		}
		to.sin_family = AF_INET;
#ifdef HAVE_SA_LEN
		to.sin_len = sizeof to;
#endif

		memcpy(&hto.hbuf[1], packet->chaddr, packet->hlen);
		hto.hbuf[0] = packet->htype;
		hto.hlen = packet->hlen + 1;

		/* Wipe out the agent relay options and, if possible, figure
		   out which interface to use based on the contents of the
		   option that we put on the request to which the server is
		   replying. */
		if (!(length =
		      strip_relay_agent_options(ip, &out, packet, length)))
			return;

		if (!out) {
			log_error("Packet to bogus giaddr %s.\n",
			      inet_ntoa(packet->giaddr));
			++bogus_giaddr_drops;
			return;
		}

		if (send_packet(out, NULL, packet, length, out->addresses[0],
				&to, htop) < 0) {
			++server_packet_errors;
		} else {
			log_debug("Forwarded BOOTREPLY for %s to %s",
			       print_hw_addr(packet->htype, packet->hlen,
					      packet->chaddr),
			       inet_ntoa(to.sin_addr));

			++server_packets_relayed;
		}
		return;
	}

	/* If giaddr matches one of our addresses, ignore the packet -
	   we just sent it. */
	if (out)
		return;

	if (!(ip->flags & INTERFACE_DOWNSTREAM)) {
		log_debug("Dropping request received on %s", ip->name);
		return;
	}

	/* Add relay agent options if indicated.   If something goes wrong,
	 * drop the packet.  Note this may set packet->giaddr if RFC3527
	 * is enabled. */
	if (!(length = add_relay_agent_options(ip, packet, length,
					       ip->addresses[0])))
		return;

	/* If giaddr is not already set, Set it so the server can
	   figure out what net it's from and so that we can later
	   forward the response to the correct net.    If it's already
	   set, the response will be sent directly to the relay agent
	   that set giaddr, so we won't see it. */
	if (!packet->giaddr.s_addr)
		packet->giaddr = ip->addresses[0];
	if (packet->hops < max_hop_count)
		packet->hops = packet->hops + 1;
	else
		return;

	/* Otherwise, it's a BOOTREQUEST, so forward it to all the
	   servers. */
	for (sp = servers; sp; sp = sp->next) {
		if (send_packet((fallback_interface
				 ? fallback_interface : interfaces),
				 NULL, packet, length, ip->addresses[0],
				 &sp->to, NULL) < 0) {
			++client_packet_errors;
		} else {
			log_debug("Forwarded BOOTREQUEST for %s to %s",
			       print_hw_addr(packet->htype, packet->hlen,
					      packet->chaddr),
			       inet_ntoa(sp->to.sin_addr));
			++client_packets_relayed;
		}
	}
				 
}

/* Strip any Relay Agent Information options from the DHCP packet
   option buffer.   If there is a circuit ID suboption, look up the
   outgoing interface based upon it. */

static int
strip_relay_agent_options(struct interface_info *in,
			  struct interface_info **out,
			  struct dhcp_packet *packet,
			  unsigned length) {
	int is_dhcp = 0;
	u_int8_t *op, *nextop, *sp, *max;
	int good_agent_option = 0;
	int status;

	/* If we're not adding agent options to packets, we're not taking
	   them out either. */
	if (!add_agent_options)
		return (length);

	/* If there's no cookie, it's a bootp packet, so we should just
	   forward it unchanged. */
	if (memcmp(packet->options, DHCP_OPTIONS_COOKIE, 4))
		return (length);

	max = ((u_int8_t *)packet) + length;
	sp = op = &packet->options[4];

	while (op < max) {
		switch(*op) {
			/* Skip padding... */
		      case DHO_PAD:
			if (sp != op)
				*sp = *op;
			++op;
			++sp;
			continue;

			/* If we see a message type, it's a DHCP packet. */
		      case DHO_DHCP_MESSAGE_TYPE:
			is_dhcp = 1;
			goto skip;
			break;

			/* Quit immediately if we hit an End option. */
		      case DHO_END:
			if (sp != op)
				*sp++ = *op++;
			goto out;

		      case DHO_DHCP_AGENT_OPTIONS:
			/* We shouldn't see a relay agent option in a
			   packet before we've seen the DHCP packet type,
			   but if we do, we have to leave it alone. */
			if (!is_dhcp)
				goto skip;

			/* Do not process an agent option if it exceeds the
			 * buffer.  Fail this packet.
			 */
			nextop = op + op[1] + 2;
			if (nextop > max)
				return (0);

			status = find_interface_by_agent_option(packet,
								out, op + 2,
								op[1]);
			if (status == -1 && drop_agent_mismatches)
				return (0);
			if (status)
				good_agent_option = 1;
			op = nextop;
			break;

		      skip:
			/* Skip over other options. */
		      default:
			/* Fail if processing this option will exceed the
			 * buffer(op[1] is malformed).
			 */
			nextop = op + op[1] + 2;
			if (nextop > max)
				return (0);

			if (sp != op) {
				memmove(sp, op, op[1] + 2);
				sp += op[1] + 2;
				op = nextop;
			} else
				op = sp = nextop;

			break;
		}
	}
      out:

	/* If it's not a DHCP packet, we're not supposed to touch it. */
	if (!is_dhcp)
		return (length);

	/* If none of the agent options we found matched, or if we didn't
	   find any agent options, count this packet as not having any
	   matching agent options, and if we're relying on agent options
	   to determine the outgoing interface, drop the packet. */

	if (!good_agent_option) {
		++missing_agent_option;
		if (drop_agent_mismatches)
			return (0);
	}

	/* Adjust the length... */
	if (sp != op) {
		length = sp -((u_int8_t *)packet);

		/* Make sure the packet isn't short(this is unlikely,
		   but WTH) */
		if (length < BOOTP_MIN_LEN) {
			memset(sp, DHO_PAD, BOOTP_MIN_LEN - length);
			length = BOOTP_MIN_LEN;
		}
	}
	return (length);
}


/* Find an interface that matches the circuit ID specified in the
   Relay Agent Information option.   If one is found, store it through
   the pointer given; otherwise, leave the existing pointer alone.

   We actually deviate somewhat from the current specification here:
   if the option buffer is corrupt, we suggest that the caller not
   respond to this packet.  If the circuit ID doesn't match any known
   interface, we suggest that the caller to drop the packet.  Only if
   we find a circuit ID that matches an existing interface do we tell
   the caller to go ahead and process the packet. */

static int
find_interface_by_agent_option(struct dhcp_packet *packet,
			       struct interface_info **out,
			       u_int8_t *buf, int len) {
	int i = 0;
	u_int8_t *circuit_id = 0;
	unsigned circuit_id_len = 0;
	struct interface_info *ip;

	while (i < len) {
		/* If the next agent option overflows the end of the
		   packet, the agent option buffer is corrupt. */
		if (i + 1 == len ||
		    i + buf[i + 1] + 2 > len) {
			++corrupt_agent_options;
			return (-1);
		}
		switch(buf[i]) {
			/* Remember where the circuit ID is... */
		      case RAI_CIRCUIT_ID:
			circuit_id = &buf[i + 2];
			circuit_id_len = buf[i + 1];
			i += circuit_id_len + 2;
			continue;

		      default:
			i += buf[i + 1] + 2;
			break;
		}
	}

	/* If there's no circuit ID, it's not really ours, tell the caller
	   it's no good. */
	if (!circuit_id) {
		++missing_circuit_id;
		return (-1);
	}

	/* Scan the interface list looking for an interface whose
	   name matches the one specified in circuit_id. */

	for (ip = interfaces; ip; ip = ip->next) {
		if (ip->circuit_id &&
		    ip->circuit_id_len == circuit_id_len &&
		    !memcmp(ip->circuit_id, circuit_id, circuit_id_len))
			break;
	}

	/* If we got a match, use it. */
	if (ip) {
		*out = ip;
		return (1);
	}

	/* If we didn't get a match, the circuit ID was bogus. */
	++bad_circuit_id;
	return (-1);
}

/*
 * Examine a packet to see if it's a candidate to have a Relay
 * Agent Information option tacked onto its tail.   If it is, tack
 * the option on.
 */
static int
add_relay_agent_options(struct interface_info *ip, struct dhcp_packet *packet,
			unsigned length, struct in_addr giaddr) {
	int is_dhcp = 0, mms;
	unsigned optlen;
	u_int8_t *op, *nextop, *sp, *max, *end_pad = NULL;
	int adding_link_select;

	/* If we're not adding agent options to packets, we can skip
	   this. */
	if (!add_agent_options)
		return (length);

	/* If there's no cookie, it's a bootp packet, so we should just
	   forward it unchanged. */
	if (memcmp(packet->options, DHCP_OPTIONS_COOKIE, 4))
		return (length);

	max = ((u_int8_t *)packet) + dhcp_max_agent_option_packet_length;

	/* Add link selection suboption if enabled and we're the first relay */
	adding_link_select = (add_rfc3527_suboption
			      && (packet->giaddr.s_addr == 0));

	/* Commence processing after the cookie. */
	sp = op = &packet->options[4];

	while (op < max) {
		switch(*op) {
			/* Skip padding... */
		      case DHO_PAD:
			/* Remember the first pad byte so we can commandeer
			 * padded space.
			 *
			 * XXX: Is this really a good idea?  Sure, we can
			 * seemingly reduce the packet while we're looking,
			 * but if the packet was signed by the client then
			 * this padding is part of the checksum(RFC3118),
			 * and its nonpresence would break authentication.
			 */
			if (end_pad == NULL)
				end_pad = sp;

			if (sp != op)
				*sp++ = *op++;
			else
				sp = ++op;

			continue;

			/* If we see a message type, it's a DHCP packet. */
		      case DHO_DHCP_MESSAGE_TYPE:
			is_dhcp = 1;
			goto skip;

			/*
			 * If there's a maximum message size option, we
			 * should pay attention to it
			 */
		      case DHO_DHCP_MAX_MESSAGE_SIZE:
			mms = ntohs(*(op + 2));
			if (mms < dhcp_max_agent_option_packet_length &&
			    mms >= DHCP_MTU_MIN)
				max = ((u_int8_t *)packet) + mms;
			goto skip;

			/* Quit immediately if we hit an End option. */
		      case DHO_END:
			goto out;

		      case DHO_DHCP_AGENT_OPTIONS:
			/* We shouldn't see a relay agent option in a
			   packet before we've seen the DHCP packet type,
			   but if we do, we have to leave it alone. */
			if (!is_dhcp)
				goto skip;

			end_pad = NULL;

			/* There's already a Relay Agent Information option
			   in this packet.   How embarrassing.   Decide what
			   to do based on the mode the user specified. */

			switch(agent_relay_mode) {
			      case forward_and_append:
				goto skip;
			      case forward_untouched:
				return (length);
			      case discard:
				return (0);
			      case forward_and_replace:
			      default:
				break;
			}

			/* Skip over the agent option and start copying
			   if we aren't copying already. */
			op += op[1] + 2;
			break;

		      skip:
			/* Skip over other options. */
		      default:
			/* Fail if processing this option will exceed the
			 * buffer(op[1] is malformed).
			 */
			nextop = op + op[1] + 2;
			if (nextop > max)
				return (0);

			end_pad = NULL;

			if (sp != op) {
				memmove(sp, op, op[1] + 2);
				sp += op[1] + 2;
				op = nextop;
			} else
				op = sp = nextop;

			break;
		}
	}
      out:

	/* If it's not a DHCP packet, we're not supposed to touch it. */
	if (!is_dhcp)
		return (length);

	/* If the packet was padded out, we can store the agent option
	   at the beginning of the padding. */

	if (end_pad != NULL)
		sp = end_pad;

#if 0
	/* Remember where the end of the packet was after parsing
	   it. */
	op = sp;
#endif

	/* Sanity check.  Had better not ever happen. */
	if ((ip->circuit_id_len > 255) ||(ip->circuit_id_len < 1))
		log_fatal("Circuit ID length %d out of range [1-255] on "
			  "%s\n", ip->circuit_id_len, ip->name);
	optlen = ip->circuit_id_len + 2;            /* RAI_CIRCUIT_ID + len */

	if (ip->remote_id) {
		if (ip->remote_id_len > 255 || ip->remote_id_len < 1)
			log_fatal("Remote ID length %d out of range [1-255] "
				  "on %s\n", ip->remote_id_len, ip->name);
		optlen += ip->remote_id_len + 2;    /* RAI_REMOTE_ID + len */
	}

	if (adding_link_select) {
		optlen += 6;
	}

#ifdef RELAY_PORT
	if (relay_port) {
		optlen += 2;
	}
#endif

	/* We do not support relay option fragmenting(multiple options to
	 * support an option data exceeding 255 bytes).
	 */
	if ((optlen < 3) ||(optlen > 255))
		log_fatal("Total agent option length(%u) out of range "
			   "[3 - 255] on %s\n", optlen, ip->name);

	/*
	 * Is there room for the option, its code+len, and DHO_END?
	 * If not, forward without adding the option.
	 */
	if (max - sp >= optlen + 3) {
		log_debug("Adding %d-byte relay agent option", optlen + 3);

		/* Okay, cons up *our* Relay Agent Information option. */
		*sp++ = DHO_DHCP_AGENT_OPTIONS;
		*sp++ = optlen;

		/* Copy in the circuit id... */
		*sp++ = RAI_CIRCUIT_ID;
		*sp++ = ip->circuit_id_len;
		memcpy(sp, ip->circuit_id, ip->circuit_id_len);
		sp += ip->circuit_id_len;

		/* Copy in remote ID... */
		if (ip->remote_id) {
			*sp++ = RAI_REMOTE_ID;
			*sp++ = ip->remote_id_len;
			memcpy(sp, ip->remote_id, ip->remote_id_len);
			sp += ip->remote_id_len;
		}

		/* RFC3527: Use the inbound packet's interface address in
		 * the link selection suboption and set the outbound giaddr
		 * to the uplink address. */
		if (adding_link_select) {
			*sp++ = RAI_LINK_SELECT;
			*sp++ = 4u;
			memcpy(sp, &giaddr.s_addr, 4);
			sp += 4;
			packet->giaddr = uplink->addresses[0];
			log_debug ("Adding link selection suboption"
				   " with addr: %s", inet_ntoa(giaddr));
		}

#ifdef RELAY_PORT
		/* draft-ietf-dhc-relay-port-10.txt section 5.1 */
		if (relay_port) {
			*sp++ = RAI_RELAY_PORT;
			*sp++ = 0u;
		}
#endif
	} else {
		++agent_option_errors;
		log_error("No room in packet (used %d of %d) "
			  "for %d-byte relay agent option: omitted",
			   (int) (sp - ((u_int8_t *) packet)),
			   (int) (max - ((u_int8_t *) packet)),
			   optlen + 3);
	}

	/*
	 * Deposit an END option unless the packet is full (shouldn't
	 * be possible).
	 */
	if (sp < max)
		*sp++ = DHO_END;

	/* Recalculate total packet length. */
	length = sp -((u_int8_t *)packet);

	/* Make sure the packet isn't short(this is unlikely, but WTH) */
	if (length < BOOTP_MIN_LEN) {
		memset(sp, DHO_PAD, BOOTP_MIN_LEN - length);
		return (BOOTP_MIN_LEN);
	}

	return (length);
}

#ifdef DHCPv6
/*
 * Parse a downstream argument: [address%]interface[#index].
 */
static struct stream_list *
parse_downstream(char *arg) {
	struct stream_list *dp, *up;
	struct interface_info *ifp = NULL;
	char *ifname, *addr, *iid;
	isc_result_t status;

	if (!supports_multiple_interfaces(ifp) &&
	    (downstreams != NULL))
		log_fatal("No support for multiple interfaces.");

	/* Decode the argument. */
	ifname = strchr(arg, '%');
	if (ifname == NULL) {
		ifname = arg;
		addr = NULL;
	} else {
		*ifname++ = '\0';
		addr = arg;
	}
	iid = strchr(ifname, '#');
	if (iid != NULL) {
		*iid++ = '\0';
	}
	if (strlen(ifname) >= sizeof(ifp->name)) {
		usage("Interface name '%s' too long", ifname);
	}

	/* Don't declare twice. */
	for (dp = downstreams; dp; dp = dp->next) {
		if (strcmp(ifname, dp->ifp->name) == 0)
			log_fatal("Down interface '%s' declared twice.",
				  ifname);
	}

	/* Share with up side? */
	for (up = upstreams; up; up = up->next) {
		if (strcmp(ifname, up->ifp->name) == 0) {
			log_info("parse_downstream: Interface '%s' is "
				 "both down and up.", ifname);
			ifp = up->ifp;
			break;
		}
	}

	/* New interface. */
	if (ifp == NULL) {
		status = interface_allocate(&ifp, MDL);
		if (status != ISC_R_SUCCESS)
			log_fatal("%s: interface_allocate: %s",
				  arg, isc_result_totext(status));
		strcpy(ifp->name, ifname);
		if (interfaces) {
			interface_reference(&ifp->next, interfaces, MDL);
			interface_dereference(&interfaces, MDL);
		}
		interface_reference(&interfaces, ifp, MDL);
	}
	ifp->flags |= INTERFACE_REQUESTED | INTERFACE_DOWNSTREAM;

	/* New downstream. */
	dp = (struct stream_list *) dmalloc(sizeof(*dp), MDL);
	if (!dp)
		log_fatal("No memory for downstream.");
	dp->ifp = ifp;
	if (iid != NULL) {
		dp->id = atoi(iid);
	} else {
		dp->id = -1;
	}
	/* !addr case handled by setup. */
	if (addr && (inet_pton(AF_INET6, addr, &dp->link.sin6_addr) <= 0))
		log_fatal("Bad link address '%s'", addr);

	return dp;
}

/*
 * Parse an upstream argument: [address]%interface.
 */
static struct stream_list *
parse_upstream(char *arg) {
	struct stream_list *up, *dp;
	struct interface_info *ifp = NULL;
	char *ifname, *addr;
	isc_result_t status;

	/* Decode the argument. */
	ifname = strchr(arg, '%');
	if (ifname == NULL) {
		ifname = arg;
		addr = All_DHCP_Servers;
	} else {
		*ifname++ = '\0';
		addr = arg;
	}
	if (strlen(ifname) >= sizeof(ifp->name)) {
		log_fatal("Interface name '%s' too long", ifname);
	}

	/* Shared up interface? */
	for (up = upstreams; up; up = up->next) {
		if (strcmp(ifname, up->ifp->name) == 0) {
			ifp = up->ifp;
			break;
		}
	}
	for (dp = downstreams; dp; dp = dp->next) {
		if (strcmp(ifname, dp->ifp->name) == 0) {
			log_info("parse_upstream: Interface '%s' is "
				 "both down and up.", ifname);
			ifp = dp->ifp;
			break;
		}
	}

	/* New interface. */
	if (ifp == NULL) {
		status = interface_allocate(&ifp, MDL);
		if (status != ISC_R_SUCCESS)
			log_fatal("%s: interface_allocate: %s",
				  arg, isc_result_totext(status));
		strcpy(ifp->name, ifname);
		if (interfaces) {
			interface_reference(&ifp->next, interfaces, MDL);
			interface_dereference(&interfaces, MDL);
		}
		interface_reference(&interfaces, ifp, MDL);
	}
	ifp->flags |= INTERFACE_REQUESTED | INTERFACE_UPSTREAM;

	/* New upstream. */
	up = (struct stream_list *) dmalloc(sizeof(*up), MDL);
	if (up == NULL)
		log_fatal("No memory for upstream.");

	up->ifp = ifp;

	if (inet_pton(AF_INET6, addr, &up->link.sin6_addr) <= 0)
		log_fatal("Bad address %s", addr);

	return up;
}

/*
 * Setup downstream interfaces.
 */
static void
setup_streams(void) {
	struct stream_list *dp, *up;
	int i;
	isc_boolean_t link_is_set;

	for (dp = downstreams; dp; dp = dp->next) {
		/* Check interface */
		if (dp->ifp->v6address_count == 0)
			log_fatal("Interface '%s' has no IPv6 addresses.",
				  dp->ifp->name);

		/* Check/set link. */
		if (IN6_IS_ADDR_UNSPECIFIED(&dp->link.sin6_addr))
			link_is_set = ISC_FALSE;
		else
			link_is_set = ISC_TRUE;
		for (i = 0; i < dp->ifp->v6address_count; i++) {
			if (IN6_IS_ADDR_LINKLOCAL(&dp->ifp->v6addresses[i]))
				continue;
			if (!link_is_set)
				break;
			if (!memcmp(&dp->ifp->v6addresses[i],
				    &dp->link.sin6_addr,
				    sizeof(dp->link.sin6_addr)))
				break;
		}
		if (i == dp->ifp->v6address_count)
			log_fatal("Interface %s does not have global IPv6 "
				  "address assigned.", dp->ifp->name);
		if (!link_is_set)
			memcpy(&dp->link.sin6_addr,
			       &dp->ifp->v6addresses[i],
			       sizeof(dp->link.sin6_addr));

		/* Set interface-id. */
		if (dp->id == -1)
			dp->id = dp->ifp->index;
	}

	for (up = upstreams; up; up = up->next) {
		up->link.sin6_port = local_port;
		up->link.sin6_family = AF_INET6;
#ifdef HAVE_SA_LEN
		up->link.sin6_len = sizeof(up->link);
#endif

		if (up->ifp->v6address_count == 0)
			log_fatal("Interface '%s' has no IPv6 addresses.",
				  up->ifp->name);

		/* RFC 3315 Sec 20 - "If the relay agent relays messages to
		 * the All_DHCP_Servers address or other multicast addresses,
		 * it sets the Hop Limit field to 32." */
		if (IN6_IS_ADDR_MULTICAST(&up->link.sin6_addr)) {
			set_multicast_hop_limit(up->ifp, HOP_COUNT_LIMIT);
		}
	}
}

/*
 * Add DHCPv6 agent options here.
 */
static const int required_forw_opts[] = {
	D6O_INTERFACE_ID,
	D6O_SUBSCRIBER_ID,
#if defined(RELAY_PORT)
	D6O_RELAY_SOURCE_PORT,
#endif
	D6O_RELAY_MSG,
	0
};

/*
 * Process a packet upwards, i.e., from client to server.
 */
static void
process_up6(struct packet *packet, struct stream_list *dp) {
	char forw_data[65535];
	unsigned cursor;
	struct dhcpv6_relay_packet *relay;
	struct option_state *opts;
	struct stream_list *up;
	u_int16_t relay_client_port = 0;

	/* Check if the message should be relayed to the server. */
	switch (packet->dhcpv6_msg_type) {
	      case DHCPV6_SOLICIT:
	      case DHCPV6_REQUEST:
	      case DHCPV6_CONFIRM:
	      case DHCPV6_RENEW:
	      case DHCPV6_REBIND:
	      case DHCPV6_RELEASE:
	      case DHCPV6_DECLINE:
	      case DHCPV6_INFORMATION_REQUEST:
	      case DHCPV6_RELAY_FORW:
	      case DHCPV6_LEASEQUERY:
	      case DHCPV6_DHCPV4_QUERY:
		log_info("Relaying %s from %s port %d going up.",
			 dhcpv6_type_names[packet->dhcpv6_msg_type],
			 piaddr(packet->client_addr),
			 ntohs(packet->client_port));
		break;

	      case DHCPV6_ADVERTISE:
	      case DHCPV6_REPLY:
	      case DHCPV6_RECONFIGURE:
	      case DHCPV6_RELAY_REPL:
	      case DHCPV6_LEASEQUERY_REPLY:
	      case DHCPV6_DHCPV4_RESPONSE:
		log_info("Discarding %s from %s port %d going up.",
			 dhcpv6_type_names[packet->dhcpv6_msg_type],
			 piaddr(packet->client_addr),
			 ntohs(packet->client_port));
		return;

	      default:
		log_info("Unknown %d type from %s port %d going up.",
			 packet->dhcpv6_msg_type,
			 piaddr(packet->client_addr),
			 ntohs(packet->client_port));
		return;
	}

	/* Build the relay-forward header. */
	relay = (struct dhcpv6_relay_packet *) forw_data;
	cursor = offsetof(struct dhcpv6_relay_packet, options);
	relay->msg_type = DHCPV6_RELAY_FORW;
	if (packet->dhcpv6_msg_type == DHCPV6_RELAY_FORW) {
		if (packet->dhcpv6_hop_count >= max_hop_count) {
			log_info("Hop count exceeded,");
			return;
		}
		relay->hop_count = packet->dhcpv6_hop_count + 1;
		if (dp) {
			memcpy(&relay->link_address, &dp->link.sin6_addr, 16);
		} else {
			/* On smart relay add: && !global. */
			if (!use_if_id && downstreams->next) {
				log_info("Shan't get back the interface.");
				return;
			}
			memset(&relay->link_address, 0, 16);
		}

		if (packet->client_port != htons(547)) {
			relay_client_port = packet->client_port;
		}
	} else {
		relay->hop_count = 0;
		if (!dp)
			return;
		memcpy(&relay->link_address, &dp->link.sin6_addr, 16);
	}
	memcpy(&relay->peer_address, packet->client_addr.iabuf, 16);

	/* Get an option state. */
	opts = NULL;
	if (!option_state_allocate(&opts, MDL)) {
		log_fatal("No memory for upwards options.");
	}
	
	/* Add an interface-id (if used). */
	if (use_if_id) {
		int if_id;

		if (dp) {
			if_id = dp->id;
		} else if (!downstreams->next) {
			if_id = downstreams->id;
		} else {
			log_info("Don't know the interface.");
			option_state_dereference(&opts, MDL);
			return;
		}

		if (!save_option_buffer(&dhcpv6_universe, opts,
					NULL, (unsigned char *) &if_id,
					sizeof(int),
					D6O_INTERFACE_ID, 0)) {
			log_error("Can't save interface-id.");
			option_state_dereference(&opts, MDL);
			return;
		}
	}

	/* Add a subscriber-id if desired. */
	/* This is for testing rather than general use */
	if (dhcrelay_sub_id != NULL) {
		if (!save_option_buffer(&dhcpv6_universe, opts, NULL,
					(unsigned char *) dhcrelay_sub_id,
					strlen(dhcrelay_sub_id),
					D6O_SUBSCRIBER_ID, 0)) {
			log_error("Can't save subsriber-id.");
			option_state_dereference(&opts, MDL);
			return;
		}
	}
		

#if defined(RELAY_PORT)
	/*
	 * If we use a non-547 UDP source port or if we have received
	 * from a downstream relay agent uses a non-547 port, we need
	 * to include the RELAY-SOURCE-PORT option. The "Downstream
	 * UDP Port" field value in the option allow us to send
	 * relay-reply message back to the downstream relay agent
	 * with the correct UDP source port.
        */
	if (relay_port || relay_client_port) {
		if (!save_option_buffer(&dhcpv6_universe, opts, NULL,
					(unsigned char *) &relay_client_port,
					sizeof(u_int16_t),
					D6O_RELAY_SOURCE_PORT, 0)) {
			log_error("Can't save relay-source-port.");
			option_state_dereference(&opts, MDL);
			return;
		}
	}
#else
	/* Avoid unused but set warning, */
	(void)(relay_client_port);
#endif

	/* Add the relay-msg carrying the packet. */
	if (!save_option_buffer(&dhcpv6_universe, opts,
				NULL, (unsigned char *) packet->raw,
				packet->packet_length,
				D6O_RELAY_MSG, 0)) {
		log_error("Can't save relay-msg.");
		option_state_dereference(&opts, MDL);
		return;
	}

	/* Finish the relay-forward message. */
	cursor += store_options6(forw_data + cursor,
				 sizeof(forw_data) - cursor,
				 opts, packet, 
				 required_forw_opts, NULL);
	option_state_dereference(&opts, MDL);

	/* Send it to all upstreams. */
	for (up = upstreams; up; up = up->next) {
		send_packet6(up->ifp, (unsigned char *) forw_data,
			     (size_t) cursor, &up->link);
	}
}
			     
/*
 * Process a packet downwards, i.e., from server to client.
 */
static void
process_down6(struct packet *packet) {
	struct stream_list *dp;
	struct option_cache *oc;
	struct data_string relay_msg;
	const struct dhcpv6_packet *msg;
	struct data_string if_id;
#if defined(RELAY_PORT)
	struct data_string down_port;
#endif
	struct sockaddr_in6 to;
	struct iaddr peer;

	/* The packet must be a relay-reply message. */
	if (packet->dhcpv6_msg_type != DHCPV6_RELAY_REPL) {
		if (packet->dhcpv6_msg_type < dhcpv6_type_name_max)
			log_info("Discarding %s from %s port %d going down.",
				 dhcpv6_type_names[packet->dhcpv6_msg_type],
				 piaddr(packet->client_addr),
				 ntohs(packet->client_port));
		else
			log_info("Unknown %d type from %s port %d going down.",
				 packet->dhcpv6_msg_type,
				 piaddr(packet->client_addr),
				 ntohs(packet->client_port));
		return;
	}

	/* Inits. */
	memset(&relay_msg, 0, sizeof(relay_msg));
	memset(&if_id, 0, sizeof(if_id));
#if defined(RELAY_PORT)
	memset(&down_port, 0, sizeof(down_port));
#endif
	memset(&to, 0, sizeof(to));
	to.sin6_family = AF_INET6;
#ifdef HAVE_SA_LEN
	to.sin6_len = sizeof(to);
#endif
	to.sin6_port = remote_port;
	peer.len = 16;

	/* Get the relay-msg option (carrying the message to relay). */
	oc = lookup_option(&dhcpv6_universe, packet->options, D6O_RELAY_MSG);
	if (oc == NULL) {
		log_info("No relay-msg.");
		return;
	}
	if (!evaluate_option_cache(&relay_msg, packet, NULL, NULL,
				   packet->options, NULL,
				   &global_scope, oc, MDL) ||
	    (relay_msg.len < offsetof(struct dhcpv6_packet, options))) {
		log_error("Can't evaluate relay-msg.");
		return;
	}
	msg = (const struct dhcpv6_packet *) relay_msg.data;

	/* Get the interface-id (if exists) and the downstream. */
	oc = lookup_option(&dhcpv6_universe, packet->options,
			   D6O_INTERFACE_ID);
	if (oc != NULL) {
		int if_index;

		if (!evaluate_option_cache(&if_id, packet, NULL, NULL,
					   packet->options, NULL,
					   &global_scope, oc, MDL) ||
		    (if_id.len != sizeof(int))) {
			log_info("Can't evaluate interface-id.");
			goto cleanup;
		}
		memcpy(&if_index, if_id.data, sizeof(int));
		for (dp = downstreams; dp; dp = dp->next) {
			if (dp->id == if_index)
				break;
		}
	} else {
		if (use_if_id) {
			/* Require an interface-id. */
			log_info("No interface-id.");
			goto cleanup;
		}
		for (dp = downstreams; dp; dp = dp->next) {
			/* Get the first matching one. */
			if (!memcmp(&dp->link.sin6_addr,
				    &packet->dhcpv6_link_address,
				    sizeof(struct in6_addr)))
				break;
		}
	}
	/* Why bother when there is no choice. */
	if (!dp && downstreams && !downstreams->next)
		dp = downstreams;
	if (!dp) {
		log_info("Can't find the down interface.");
		goto cleanup;
	}
	memcpy(peer.iabuf, &packet->dhcpv6_peer_address, peer.len);
	to.sin6_addr = packet->dhcpv6_peer_address;

	/* Check if we should relay the carried message. */
	switch (msg->msg_type) {
		/* Relay-Reply of for another relay, not a client. */
	      case DHCPV6_RELAY_REPL:
		to.sin6_port = local_port;

#if defined(RELAY_PORT)
		oc = lookup_option(&dhcpv6_universe, packet->options,
				   D6O_RELAY_SOURCE_PORT);
		if (oc != NULL) {
			u_int16_t down_relay_port;

			memset(&down_port, 0, sizeof(down_port));
			if (!evaluate_option_cache(&down_port, packet, NULL,
						   NULL, packet->options, NULL,
						   &global_scope, oc, MDL) ||
			    (down_port.len != sizeof(u_int16_t))) {
				log_info("Can't evaluate down "
					 "relay-source-port.");
				goto cleanup;
			}
			memcpy(&down_relay_port, down_port.data,
			       sizeof(u_int16_t));
			/*
			 * If the down_relay_port value is non-zero,
			 * that means our downstream relay agent uses
			 * a non-547 UDP source port sending
			 * relay-forw message to us. We need to use
			 * the same UDP port sending reply back.
			 */
			if (down_relay_port) {
				to.sin6_port = down_relay_port;
			}
		}
#endif

		/* Fall into: */

	      case DHCPV6_ADVERTISE:
	      case DHCPV6_REPLY:
	      case DHCPV6_RECONFIGURE:
	      case DHCPV6_RELAY_FORW:
	      case DHCPV6_LEASEQUERY_REPLY:
	      case DHCPV6_DHCPV4_RESPONSE:
		log_info("Relaying %s to %s port %d down.",
			 dhcpv6_type_names[msg->msg_type],
			 piaddr(peer),
			 ntohs(to.sin6_port));
		break;

	      case DHCPV6_SOLICIT:
	      case DHCPV6_REQUEST:
	      case DHCPV6_CONFIRM:
	      case DHCPV6_RENEW:
	      case DHCPV6_REBIND:
	      case DHCPV6_RELEASE:
	      case DHCPV6_DECLINE:
	      case DHCPV6_INFORMATION_REQUEST:
	      case DHCPV6_LEASEQUERY:
	      case DHCPV6_DHCPV4_QUERY:
		log_info("Discarding %s to %s port %d down.",
			 dhcpv6_type_names[msg->msg_type],
			 piaddr(peer),
			 ntohs(to.sin6_port));
		goto cleanup;

	      default:
		log_info("Unknown %d type to %s port %d down.",
			 msg->msg_type,
			 piaddr(peer),
			 ntohs(to.sin6_port));
		goto cleanup;
	}

	/* Send the message to the downstream. */
	send_packet6(dp->ifp, (unsigned char *) relay_msg.data,
		     (size_t) relay_msg.len, &to);

      cleanup:
	if (relay_msg.data != NULL)
		data_string_forget(&relay_msg, MDL);
	if (if_id.data != NULL)
		data_string_forget(&if_id, MDL);
}

/*
 * Called by the dispatch packet handler with a decoded packet.
 */
void
dhcpv6(struct packet *packet) {
	struct stream_list *dp;

	/* Try all relay-replies downwards. */
	if (packet->dhcpv6_msg_type == DHCPV6_RELAY_REPL) {
		process_down6(packet);
		return;
	}
	/* Others are candidates to go up if they come from down. */
	for (dp = downstreams; dp; dp = dp->next) {
		if (packet->interface != dp->ifp)
			continue;
		process_up6(packet, dp);
		return;
	}
	/* Relay-forward could work from an unknown interface. */
	if (packet->dhcpv6_msg_type == DHCPV6_RELAY_FORW) {
		process_up6(packet, NULL);
		return;
	}

	log_info("Can't process packet from interface '%s'.",
		 packet->interface->name);
}
#endif

/* Stub routines needed for linking with DHCP libraries. */
void
bootp(struct packet *packet) {
	return;
}

void
dhcp(struct packet *packet) {
	return;
}

#if defined(DHCPv6) && defined(DHCP4o6)
isc_result_t dhcpv4o6_handler(omapi_object_t *h)
{
	return ISC_R_NOTIMPLEMENTED;
}
#endif

void
classify(struct packet *p, struct class *c) {
	return;
}

int
check_collection(struct packet *p, struct lease *l, struct collection *c) {
	return 0;
}

isc_result_t
find_class(struct class **class, const char *c1, const char *c2, int i) {
	return ISC_R_NOTFOUND;
}

int
parse_allow_deny(struct option_cache **oc, struct parse *p, int i) {
	return 0;
}

isc_result_t
dhcp_set_control_state(control_object_state_t oldstate,
		       control_object_state_t newstate) {
	char buf = 0;

	if (newstate != server_shutdown)
		return ISC_R_SUCCESS;

	if (no_pid_file == ISC_FALSE)
		(void) unlink(path_dhcrelay_pid);

	if (!no_daemon && dfd[0] != -1 && dfd[1] != -1) {
		IGNORE_RET(write(dfd[1], &buf, 1));
		(void) close(dfd[1]);
		dfd[0] = dfd[1] = -1;
	}
	exit(0);
}

/*!
 *
 * \brief Allocate an interface as requested with a given set of flags
 *
 * The requested interface is allocated, its flags field is set to
 * INTERFACE_REQUESTED OR'd with the given flags,  and then added to
 * the list of interfaces.
 *
 * \param name - name of the requested interface
 * \param flags - additional flags for the interface
 *
 * \return Nothing
 */
void request_v4_interface(const char* name, int flags) {
        struct interface_info *tmp = NULL;
        int len = strlen(name);
        isc_result_t status;

        if (len >= sizeof(tmp->name)) {
                log_fatal("%s: interface name too long (is %d)", name, len);
        }

        status = interface_allocate(&tmp, MDL);
        if (status != ISC_R_SUCCESS) {
                log_fatal("%s: interface_allocate: %s", name,
                          isc_result_totext(status));
        }

	log_debug("Requesting: %s as upstream: %c downstream: %c", name,
		  (flags & INTERFACE_UPSTREAM ? 'Y' : 'N'),
		  (flags & INTERFACE_DOWNSTREAM ? 'Y' : 'N'));

        strncpy(tmp->name, name, len);
        interface_snorf(tmp, (INTERFACE_REQUESTED | flags));
        interface_dereference(&tmp, MDL);
}