summaryrefslogtreecommitdiffstats
path: root/src/lib/dhcp/iface_mgr.cc
blob: abb0f27d6f3b666550787ab79239142ef132fb33 (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
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
// Copyright (C) 2011-2022 Internet Systems Consortium, Inc. ("ISC")
//
// 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/.

#include <config.h>
#include <asiolink/asio_wrapper.h>
#include <asiolink/io_error.h>
#include <asiolink/udp_endpoint.h>
#include <dhcp/dhcp4.h>
#include <dhcp/dhcp6.h>
#include <dhcp/iface_mgr.h>
#include <dhcp/iface_mgr_error_handler.h>
#include <dhcp/pkt_filter_inet.h>
#include <dhcp/pkt_filter_inet6.h>
#include <exceptions/exceptions.h>
#include <util/io/pktinfo_utilities.h>
#include <util/multi_threading_mgr.h>

#include <boost/scoped_ptr.hpp>

#include <cstring>
#include <errno.h>
#include <fstream>
#include <functional>
#include <limits>
#include <sstream>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/select.h>

#ifndef FD_COPY
#define FD_COPY(orig, copy) \
    do { \
        memmove(copy, orig, sizeof(fd_set)); \
    } while (0)
#endif

using namespace std;
using namespace isc::asiolink;
using namespace isc::util;
using namespace isc::util::io;
using namespace isc::util::io::internal;

namespace isc {
namespace dhcp {

IfaceMgr&
IfaceMgr::instance() {
    return (*instancePtr());
}

const IfaceMgrPtr&
IfaceMgr::instancePtr() {
    static IfaceMgrPtr iface_mgr(new IfaceMgr());
    return (iface_mgr);
}

Iface::Iface(const std::string& name, unsigned int ifindex)
    : name_(name), ifindex_(ifindex), mac_len_(0), hardware_type_(0),
      flag_loopback_(false), flag_up_(false), flag_running_(false),
      flag_multicast_(false), flag_broadcast_(false), flags_(0),
      inactive4_(false), inactive6_(false) {
    // Sanity checks.
    if (name.empty()) {
        isc_throw(BadValue, "Interface name must not be empty");
    }
    memset(mac_, 0, sizeof(mac_));
}

void
Iface::closeSockets() {
    // Close IPv4 sockets.
    closeSockets(AF_INET);
    // Close IPv6 sockets.
    closeSockets(AF_INET6);
}

void
Iface::closeSockets(const uint16_t family) {
    // Check that the correct 'family' value has been specified.
    // The possible values are AF_INET or AF_INET6. Note that, in
    // the current code they are used to differentiate that the
    // socket is used to transmit IPv4 or IPv6 traffic. However,
    // the actual family types of the sockets may be different,
    // e.g. for LPF we are using raw sockets of AF_PACKET family.
    //
    // @todo Consider replacing the AF_INET and AF_INET6 with some
    // enum which will not be confused with the actual socket type.
    if ((family != AF_INET) && (family != AF_INET6)) {
        isc_throw(BadValue, "Invalid socket family " << family
                  << " specified when requested to close all sockets"
                  << " which belong to this family");
    }

    // Search for the socket of the specific type.
    SocketCollection::iterator sock = sockets_.begin();
    while (sock != sockets_.end()) {
        if (sock->family_ == family) {
            // Close and delete the socket and move to the
            // next one.
            close(sock->sockfd_);
            // Close fallback socket if open.
            if (sock->fallbackfd_ >= 0) {
                close(sock->fallbackfd_);
            }
            sockets_.erase(sock++);

        } else {
            // Different type of socket. Let's move
            // to the next one.
            ++sock;

        }
    }
}

std::string
Iface::getFullName() const {
    ostringstream tmp;
    tmp << name_ << "/" << ifindex_;
    return (tmp.str());
}

std::string
Iface::getPlainMac() const {
    ostringstream tmp;
    tmp.fill('0');
    tmp << hex;
    for (int i = 0; i < mac_len_; i++) {
        tmp.width(2);
        tmp << static_cast<int>(mac_[i]);
        if (i < mac_len_-1) {
            tmp << ":";
        }
    }
    return (tmp.str());
}

void Iface::setMac(const uint8_t* mac, size_t len) {
    if (len > MAX_MAC_LEN) {
        isc_throw(OutOfRange, "Interface " << getFullName()
                  << " was detected to have link address of length "
                  << len << ", but maximum supported length is "
                  << MAX_MAC_LEN);
    }
    mac_len_ = len;
    if (len > 0) {
        memcpy(mac_, mac, len);
    }
}

bool Iface::delAddress(const isc::asiolink::IOAddress& addr) {
    for (AddressCollection::iterator a = addrs_.begin();
         a!=addrs_.end(); ++a) {
        if (a->get() == addr) {
            addrs_.erase(a);
            return (true);
        }
    }
    return (false);
}

bool Iface::delSocket(const uint16_t sockfd) {
    list<SocketInfo>::iterator sock = sockets_.begin();
    while (sock!=sockets_.end()) {
        if (sock->sockfd_ == sockfd) {
            close(sockfd);
            // Close fallback socket if open.
            if (sock->fallbackfd_ >= 0) {
                close(sock->fallbackfd_);
            }
            sockets_.erase(sock);
            return (true); //socket found
        }
        ++sock;
    }
    return (false); // socket not found
}

IfaceMgr::IfaceMgr()
    : packet_filter_(new PktFilterInet()),
      packet_filter6_(new PktFilterInet6()),
      test_mode_(false),
      allow_loopback_(false) {

    // Ensure that PQMs have been created to guarantee we have
    // default packet queues in place.
    try {
        packet_queue_mgr4_.reset(new PacketQueueMgr4());
        packet_queue_mgr6_.reset(new PacketQueueMgr6());
    } catch (const std::exception& ex) {
        isc_throw(Unexpected, "Failed to create PacketQueueManagers: " << ex.what());
    }

    try {

        // required for sending/receiving packets
        // let's keep it in front, just in case someone
        // wants to send anything during initialization
        detectIfaces();

    } catch (const std::exception& ex) {
        isc_throw(IfaceDetectError, ex.what());
    }
}

void Iface::addUnicast(const isc::asiolink::IOAddress& addr) {
    for (Address a : unicasts_) {
        if (a.get() == addr) {
            isc_throw(BadValue, "Address " << addr
                      << " already defined on the " << name_ << " interface.");
        }
    }
    unicasts_.push_back(Optional<IOAddress>(addr));
}

bool
Iface::getAddress4(isc::asiolink::IOAddress& address) const {
    // Iterate over existing addresses assigned to the interface.
    // Try to find the one that is IPv4.
    for (Address addr : getAddresses()) {
        // If address is IPv4, we assign it to the function argument
        // and return true.
        if (addr.get().isV4()) {
            address = addr.get();
            return (true);
        }
    }
    // There is no IPv4 address assigned to this interface.
    return (false);
}

bool
Iface::hasAddress(const isc::asiolink::IOAddress& address) const {
    for (Address addr : getAddresses()) {
        if (address == addr.get()) {
            return (true);
        }
    }
    return (false);
}

void
Iface::addAddress(const isc::asiolink::IOAddress& addr) {
    if (!hasAddress(addr)) {
        addrs_.push_back(Address(addr));
    }
}

void
Iface::setActive(const IOAddress& address, const bool active) {
    for (AddressCollection::iterator addr_it = addrs_.begin();
         addr_it != addrs_.end(); ++addr_it) {
        if (address == addr_it->get()) {
            addr_it->unspecified(!active);
            return;
        }
    }
    isc_throw(BadValue, "specified address " << address << " was not"
              " found on the interface " << getName());
}

void
Iface::setActive(const bool active) {
    for (AddressCollection::iterator addr_it = addrs_.begin();
         addr_it != addrs_.end(); ++addr_it) {
        addr_it->unspecified(!active);
    }
}

unsigned int
Iface::countActive4() const {
    uint16_t count = 0;
    for (Address addr : addrs_) {
        if (!addr.unspecified() && addr.get().isV4()) {
            ++count;
        }
    }
    return (count);
}

void IfaceMgr::closeSockets() {
    // Clears bound addresses.
    clearBoundAddresses();

    // Stops the receiver thread if there is one.
    stopDHCPReceiver();

    for (IfacePtr iface : ifaces_) {
        iface->closeSockets();
    }
}

void IfaceMgr::stopDHCPReceiver() {
    if (isDHCPReceiverRunning()) {
        dhcp_receiver_->stop();
    }

    dhcp_receiver_.reset();

    if (getPacketQueue4()) {
        getPacketQueue4()->clear();
    }

    if (getPacketQueue6()) {
        getPacketQueue6()->clear();
    }
}

IfaceMgr::~IfaceMgr() {
    closeSockets();
}

bool
IfaceMgr::isDirectResponseSupported() const {
    return (packet_filter_->isDirectResponseSupported());
}

void
IfaceMgr::addExternalSocket(int socketfd, SocketCallback callback) {
    if (socketfd < 0) {
        isc_throw(BadValue, "Attempted to install callback for invalid socket "
                  << socketfd);
    }
    std::lock_guard<std::mutex> lock(callbacks_mutex_);
    for (SocketCallbackInfo s : callbacks_) {
        // There's such a socket description there already.
        // Update the callback and we're done
        if (s.socket_ == socketfd) {
            s.callback_ = callback;
            return;
        }
    }

    // Add a new entry to the callbacks vector
    SocketCallbackInfo x;
    x.socket_ = socketfd;
    x.callback_ = callback;
    callbacks_.push_back(x);
}

void
IfaceMgr::deleteExternalSocket(int socketfd) {
    std::lock_guard<std::mutex> lock(callbacks_mutex_);
    deleteExternalSocketInternal(socketfd);
}

void
IfaceMgr::deleteExternalSocketInternal(int socketfd) {
    for (SocketCallbackInfoContainer::iterator s = callbacks_.begin();
         s != callbacks_.end(); ++s) {
        if (s->socket_ == socketfd) {
            callbacks_.erase(s);
            return;
        }
    }
}

int
IfaceMgr::purgeBadSockets() {
    std::lock_guard<std::mutex> lock(callbacks_mutex_);
    std::vector<int> bad_fds;
    for (SocketCallbackInfo s : callbacks_) {
        errno = 0;
        if (fcntl(s.socket_, F_GETFD) < 0 && (errno == EBADF)) {
            bad_fds.push_back(s.socket_);
        }
    }

    for (auto bad_fd : bad_fds) {
        deleteExternalSocketInternal(bad_fd);
    }

    return (bad_fds.size());
}

void
IfaceMgr::deleteAllExternalSockets() {
    std::lock_guard<std::mutex> lock(callbacks_mutex_);
    callbacks_.clear();
}

void
IfaceMgr::setPacketFilter(const PktFilterPtr& packet_filter) {
    // Do not allow null pointer.
    if (!packet_filter) {
        isc_throw(InvalidPacketFilter, "NULL packet filter object specified for"
                  " DHCPv4");
    }
    // Different packet filters use different socket types. It does not make
    // sense to allow the change of packet filter when there are IPv4 sockets
    // open because they can't be used by the receive/send functions of the
    // new packet filter. Below, we check that there are no open IPv4 sockets.
    // If we find at least one, we have to fail. However, caller still has a
    // chance to replace the packet filter if he closes sockets explicitly.
    if (hasOpenSocket(AF_INET)) {
        // There is at least one socket open, so we have to fail.
        isc_throw(PacketFilterChangeDenied,
                  "it is not allowed to set new packet"
                  << " filter when there are open IPv4 sockets - need"
                  << " to close them first");
    }
    // Everything is fine, so replace packet filter.
    packet_filter_ = packet_filter;
}

void
IfaceMgr::setPacketFilter(const PktFilter6Ptr& packet_filter) {
    if (!packet_filter) {
        isc_throw(InvalidPacketFilter, "NULL packet filter object specified for"
                  " DHCPv6");
    }

    if (hasOpenSocket(AF_INET6)) {
        // There is at least one socket open, so we have to fail.
        isc_throw(PacketFilterChangeDenied,
                  "it is not allowed to set new packet"
                  << " filter when there are open IPv6 sockets - need"
                  << " to close them first");
    }

    packet_filter6_ = packet_filter;
}

bool
IfaceMgr::hasOpenSocket(const uint16_t family) const {
    // Iterate over all interfaces and search for open sockets.
    for (IfacePtr iface : ifaces_) {
        for (SocketInfo sock : iface->getSockets()) {
            // Check if the socket matches specified family.
            if (sock.family_ == family) {
                // There is at least one socket open, so return.
                return (true);
            }
        }
    }
    // There are no open sockets found for the specified family.
    return (false);
}

bool
IfaceMgr::hasOpenSocket(const IOAddress& addr) const {
    // Fast track for IPv4 using bound addresses.
    if (addr.isV4() && !bound_address_.empty()) {
        return (bound_address_.count(addr.toUint32()) != 0);
    }
    // Iterate over all interfaces and search for open sockets.
    for (IfacePtr iface : ifaces_) {
        for (SocketInfo sock : iface->getSockets()) {
            // Check if the socket address matches the specified address or
            // if address is unspecified (in6addr_any).
            if (sock.addr_ == addr) {
                return (true);
            } else if (sock.addr_.isV6Zero()) {
                // Handle the case that the address is unspecified (any).
                // This happens only with IPv6 so we do not check IPv4.
                // In this case, we should check if the specified address
                // belongs to any of the interfaces.
                for (IfacePtr it : ifaces_) {
                    for (Iface::Address a : it->getAddresses()) {
                        if (addr == a.get()) {
                            return (true);
                        }
                    }
                }
                // The address does not belongs to any interface.
                return (false);
            }
        }
    }
    // There are no open sockets found for the specified family.
    return (false);
}

void IfaceMgr::stubDetectIfaces() {
    string ifaceName;
    const string v4addr("127.0.0.1"), v6addr("::1");

    // This is a stub implementation for interface detection. Actual detection
    // is faked by detecting loopback interface (lo or lo0). It will eventually
    // be removed once we have actual implementations for all supported systems.

    if (if_nametoindex("lo") > 0) {
        ifaceName = "lo";
        // this is Linux-like OS
    } else if (if_nametoindex("lo0") > 0) {
        ifaceName = "lo0";
        // this is BSD-like OS
    } else {
        // we give up. What OS is this, anyway? Solaris? Hurd?
        isc_throw(NotImplemented,
                  "Interface detection on this OS is not supported.");
    }

    IfacePtr iface(new Iface(ifaceName, if_nametoindex(ifaceName.c_str())));
    iface->flag_up_ = true;
    iface->flag_running_ = true;

    // Note that we claim that this is not a loopback. iface_mgr tries to open a
    // socket on all interfaces that are up, running and not loopback. As this is
    // the only interface we were able to detect, let's pretend this is a normal
    // interface.
    iface->flag_loopback_ = false;
    iface->flag_multicast_ = true;
    iface->flag_broadcast_ = true;
    iface->setHWType(HWTYPE_ETHERNET);

    iface->addAddress(IOAddress(v4addr));
    iface->addAddress(IOAddress(v6addr));
    addInterface(iface);
}

bool
IfaceMgr::openSockets4(const uint16_t port, const bool use_bcast,
                       IfaceMgrErrorMsgCallback error_handler,
                       const bool skip_opened) {
    int count = 0;
    int bcast_num = 0;

    for (IfacePtr iface : ifaces_) {
        // Clear any errors from previous socket opening.
        iface->clearErrors();

        // If the interface is inactive, there is nothing to do. Simply
        // proceed to the next detected interface.
        if (iface->inactive4_) {
            continue;
        }

        // If the interface has been specified in the configuration that
        // it should be used to listen the DHCP traffic we have to check
        // that the interface configuration is valid and that the interface
        // is not a loopback interface. In both cases, we want to report
        // that the socket will not be opened.
        // Relax the check when the loopback interface was explicitly
        // allowed
        if (iface->flag_loopback_ && !allow_loopback_) {
            IFACEMGR_ERROR(SocketConfigError, error_handler, iface,
                            "must not open socket on the loopback"
                            " interface " << iface->getName());
            continue;
        }

        if (!iface->flag_up_) {
            IFACEMGR_ERROR(SocketConfigError, error_handler, iface,
                            "the interface " << iface->getName()
                            << " is down");
            continue;
        }

        if (!iface->flag_running_) {
            IFACEMGR_ERROR(SocketConfigError, error_handler, iface,
                            "the interface " << iface->getName()
                            << " is not running");
            continue;
        }

        IOAddress out_address("0.0.0.0");
        if (!iface->getAddress4(out_address)) {
            IFACEMGR_ERROR(SocketConfigError, error_handler, iface,
                            "the interface " << iface->getName()
                            << " has no usable IPv4 addresses configured");
            continue;
        }

        for (Iface::Address addr : iface->getAddresses()) {
            // Skip non-IPv4 addresses and those that weren't selected..
            if (addr.unspecified() || !addr.get().isV4()) {
                continue;
            }

            // If selected interface is broadcast capable set appropriate
            // options on the socket so as it can receive and send broadcast
            // messages.
            bool is_open_as_broadcast = iface->flag_broadcast_ && use_bcast;

            // The DHCP server must have means to determine which interface
            // the broadcast packets are coming from. This is achieved by
            // binding a socket to the device (interface) and specialized
            // packet filters (e.g. BPF and LPF) implement this mechanism.
            // If the PktFilterInet (generic one) is used, the socket is
            // bound to INADDR_ANY which effectively binds the socket to
            // all addresses on all interfaces. So, only one of those can
            // be opened. Currently, the direct response support is
            // provided by the PktFilterLPF and PktFilterBPF, so by checking
            // the support for direct response we actually determine that
            // one of those objects is in use. For all other objects we
            // assume that binding to the device is not supported and we
            // cease opening sockets and display the appropriate message.
            if (is_open_as_broadcast && !isDirectResponseSupported() && bcast_num > 0) {
                IFACEMGR_ERROR(SocketConfigError, error_handler, iface,
                               "Binding socket to an interface is not"
                               " supported on this OS; therefore only"
                               " one socket listening to broadcast traffic"
                               " can be opened. Sockets will not be opened"
                               " on remaining interfaces");
                continue;
            }

            // Skip the address that already has a bound socket. It allows
            // for preventing bind errors or re-opening sockets.
            if (!skip_opened || !IfaceMgr::hasOpenSocket(addr.get())) {
                try {
                    // We haven't open any broadcast sockets yet, so we can
                    // open at least one more or
                    // not broadcast capable, do not set broadcast flags.
                    IfaceMgr::openSocket(iface->getName(), addr.get(), port,
                                         is_open_as_broadcast,
                                         is_open_as_broadcast);
                } catch (const Exception& ex) {
                    IFACEMGR_ERROR(SocketConfigError, error_handler, iface,
                        "Failed to open socket on interface "
                            << iface->getName()
                            << ", reason: "
                            << ex.what());
                    continue;
                }
            }

            if (is_open_as_broadcast) {
                // Binding socket to an interface is not supported so we
                // can't open any more broadcast sockets. Increase the
                // number of open broadcast sockets.
                ++bcast_num;
            }

            ++count;
        }
    }

    // If we have open sockets, start the receiver.
    if (count > 0) {
        // Collects bound addresses.
        collectBoundAddresses();

        // Starts the receiver thread (if queueing is enabled).
        startDHCPReceiver(AF_INET);
    }

    return (count > 0);
}

bool
IfaceMgr::openSockets6(const uint16_t port,
                       IfaceMgrErrorMsgCallback error_handler,
                       const bool skip_opened) {
    int count = 0;

    for (IfacePtr iface : ifaces_) {
        // Clear any errors from previous socket opening.
        iface->clearErrors();

        // If the interface is inactive, there is nothing to do. Simply
        // proceed to the next detected interface.
        if (iface->inactive6_) {
            continue;
        }

        // If the interface has been specified in the configuration that
        // it should be used to listen the DHCP traffic we have to check
        // that the interface configuration is valid and that the interface
        // is not a loopback interface. In both cases, we want to report
        // that the socket will not be opened.
        // Relax the check when the loopback interface was explicitly
        // allowed
        if (iface->flag_loopback_ && !allow_loopback_) {
            IFACEMGR_ERROR(SocketConfigError, error_handler, iface,
                           "must not open socket on the loopback"
                           " interface " << iface->getName());
            continue;
        } else if (!iface->flag_up_) {
            IFACEMGR_ERROR(SocketConfigError, error_handler, iface,
                           "the interface " << iface->getName()
                           << " is down");
            continue;
        } else if (!iface->flag_running_) {
            IFACEMGR_ERROR(SocketConfigError, error_handler, iface,
                           "the interface " << iface->getName()
                           << " is not running");
            continue;
        }

        // Open unicast sockets if there are any unicast addresses defined
        for (Iface::Address addr : iface->getUnicasts()) {
            // Skip the address that already has a bound socket. It allows
            // for preventing bind errors or re-opening sockets.
            // The @ref IfaceMgr::hasOpenSocket(addr) does match the "::"
            // address on BSD and Solaris on any interface, so we make sure that
            // that interface actually has opened sockets by checking the number
            // of sockets to be non zero.
            if (!skip_opened || !IfaceMgr::hasOpenSocket(addr) ||
                !iface->getSockets().size()) {
                try {
                    IfaceMgr::openSocket(iface->getName(), addr, port, false, false);
                } catch (const Exception& ex) {
                    IFACEMGR_ERROR(SocketConfigError, error_handler, iface,
                        "Failed to open unicast socket on interface "
                        << iface->getName()
                        << ", reason: " << ex.what());
                    continue;
                }
            }

            count++;
        }

        for (Iface::Address addr : iface->getAddresses()) {

            // Skip all but V6 addresses.
            if (!addr.get().isV6()) {
                continue;
            }

            // Bind link-local addresses only. Otherwise we bind several sockets
            // on interfaces that have several global addresses. For examples
            // with interface with 2 global addresses, we would bind 3 sockets
            // (one for link-local and two for global). That would result in
            // getting each message 3 times.
            if (!addr.get().isV6LinkLocal()){
                continue;
            }

            // Run OS-specific function to open a socket capable of receiving
            // packets sent to All_DHCP_Relay_Agents_and_Servers multicast
            // address.

            // Skip the address that already has a bound socket. It allows
            // for preventing bind errors or re-opening sockets.
            // The @ref IfaceMgr::hasOpenSocket(addr) does match the "::"
            // address on BSD and Solaris on any interface, so we make sure that
            // the interface actually has opened sockets by checking the number
            // of sockets to be non zero.
            if (!skip_opened || !IfaceMgr::hasOpenSocket(addr) ||
                !iface->getSockets().size()) {
                try {
                    // Pass a null pointer as an error handler to avoid
                    // suppressing an exception in a system-specific function.
                    IfaceMgr::openMulticastSocket(*iface, addr, port);
                } catch (const Exception& ex) {
                    IFACEMGR_ERROR(SocketConfigError, error_handler, iface,
                        "Failed to open multicast socket on interface "
                        << iface->getName() << ", reason: " << ex.what());
                    continue;
                }
            }

            ++count;
        }
    }

    // If we have open sockets, start the receiver.
    if (count > 0) {
        // starts the receiver thread (if queueing is enabled).
        startDHCPReceiver(AF_INET6);
    }
    return (count > 0);
}

void
IfaceMgr::startDHCPReceiver(const uint16_t family) {
    if (isDHCPReceiverRunning()) {
        isc_throw(InvalidOperation, "a receiver thread already exists");
    }

    switch (family) {
    case AF_INET:
        // If the queue doesn't exist, packet queing has been configured
        // as disabled. If there is no queue, we do not create a receiver.
        if(!getPacketQueue4()) {
            return;
        }

        dhcp_receiver_.reset(new WatchedThread());
        dhcp_receiver_->start(std::bind(&IfaceMgr::receiveDHCP4Packets, this));
        break;
    case AF_INET6:
        // If the queue doesn't exist, packet queing has been configured
        // as disabled. If there is no queue, we do not create a receiver.
        if(!getPacketQueue6()) {
            return;
        }

        dhcp_receiver_.reset(new WatchedThread());
        dhcp_receiver_->start(std::bind(&IfaceMgr::receiveDHCP6Packets, this));
        break;
    default:
        isc_throw (BadValue, "startDHCPReceiver: invalid family: " << family);
        break;
    }
}

void
IfaceMgr::addInterface(const IfacePtr& iface) {
    for (const IfacePtr& existing : ifaces_) {
        if ((existing->getName() == iface->getName()) ||
            (existing->getIndex() == iface->getIndex())) {
            isc_throw(Unexpected, "Can't add " << iface->getFullName() <<
                      " when " << existing->getFullName() <<
                      " already exists.");
        }
    }
    ifaces_.push_back(iface);
}

void
IfaceMgr::printIfaces(std::ostream& out /*= std::cout*/) {
    for (IfacePtr iface : ifaces_) {
        const Iface::AddressCollection& addrs = iface->getAddresses();

        out << "Detected interface " << iface->getFullName()
            << ", hwtype=" << iface->getHWType()
            << ", mac=" << iface->getPlainMac();
        out << ", flags=" << hex << iface->flags_ << dec << "("
            << (iface->flag_loopback_?"LOOPBACK ":"")
            << (iface->flag_up_?"UP ":"")
            << (iface->flag_running_?"RUNNING ":"")
            << (iface->flag_multicast_?"MULTICAST ":"")
            << (iface->flag_broadcast_?"BROADCAST ":"")
            << ")" << endl;
        out << "  " << addrs.size() << " addr(s):";

        for (Iface::Address addr : addrs) {
            out << "  " << addr.get().toText();
        }
        out << endl;
    }
}

IfacePtr
IfaceCollection::getIface(uint32_t ifindex) {
    return (getIfaceInternal(ifindex, MultiThreadingMgr::instance().getMode()));
}


IfacePtr
IfaceCollection::getIface(const std::string& ifname) {
    return (getIfaceInternal(ifname, MultiThreadingMgr::instance().getMode()));
}

IfacePtr
IfaceCollection::getIfaceInternal(uint32_t ifindex, bool need_lock) {
    if (need_lock) {
        lock_guard<mutex> lock(mutex_);
        if (cache_ && (cache_->getIndex() == ifindex)) {
            return (cache_);
        }
    } else {
        if (cache_ && (cache_->getIndex() == ifindex)) {
            return (cache_);
        }
    }
    const auto& idx = ifaces_container_.get<1>();
    auto it = idx.find(ifindex);
    if (it == idx.end()) {
        return (IfacePtr()); // not found
    }
    if (need_lock) {
        lock_guard<mutex> lock(mutex_);
        cache_ = *it;
        return (cache_);
    } else {
        lock_guard<mutex> lock(mutex_);
        cache_ = *it;
        return (cache_);
    }
}

IfacePtr
IfaceCollection::getIfaceInternal(const std::string& ifname, bool need_lock) {
    if (need_lock) {
        lock_guard<mutex> lock(mutex_);
        if (cache_ && (cache_->getName() == ifname)) {
            return (cache_);
        }
    } else {
        if (cache_ && (cache_->getName() == ifname)) {
            return (cache_);
        }
    }
    const auto& idx = ifaces_container_.get<2>();
    auto it = idx.find(ifname);
    if (it == idx.end()) {
        return (IfacePtr()); // not found
    }
    if (need_lock) {
        lock_guard<mutex> lock(mutex_);
        cache_ = *it;
        return (cache_);
    } else {
        lock_guard<mutex> lock(mutex_);
        cache_ = *it;
        return (cache_);
    }
}

IfacePtr
IfaceMgr::getIface(int ifindex) {
    if ((ifindex < 0) || (ifindex > std::numeric_limits<int32_t>::max())) {
        return (IfacePtr()); // out of range
    }
    return (ifaces_.getIface(ifindex));
}

IfacePtr
IfaceMgr::getIface(const std::string& ifname) {
    if (ifname.empty()) {
        return (IfacePtr()); // empty
    }
    return (ifaces_.getIface(ifname));
}

IfacePtr
IfaceMgr::getIface(const PktPtr& pkt) {
    if (pkt->indexSet()) {
        return (getIface(pkt->getIndex()));
    } else {
        return (getIface(pkt->getIface()));
    }
}

void
IfaceMgr::clearIfaces() {
    ifaces_.clear();
}

void
IfaceMgr::clearBoundAddresses() {
    bound_address_.clear();
}

void
IfaceMgr::collectBoundAddresses() {
    for (IfacePtr iface : ifaces_) {
        for (SocketInfo sock : iface->getSockets()) {
            const IOAddress& addr = sock.addr_;
            if (!addr.isV4()) {
                continue;
            }
            if (bound_address_.count(addr.toUint32()) == 0) {
                bound_address_.insert(addr);
            }
        }
    }
}

void
IfaceMgr::clearUnicasts() {
    for (IfacePtr iface : ifaces_) {
        iface->clearUnicasts();
    }
}

int IfaceMgr::openSocket(const std::string& ifname, const IOAddress& addr,
                         const uint16_t port, const bool receive_bcast,
                         const bool send_bcast) {
    IfacePtr iface = getIface(ifname);
    if (!iface) {
        isc_throw(BadValue, "There is no " << ifname << " interface present.");
    }
    if (addr.isV4()) {
        return openSocket4(*iface, addr, port, receive_bcast, send_bcast);

    } else if (addr.isV6()) {
        return openSocket6(*iface, addr, port, receive_bcast);

    } else {
        isc_throw(BadValue, "Failed to detect family of address: "
                  << addr);
    }
}

int IfaceMgr::openSocketFromIface(const std::string& ifname,
                                  const uint16_t port,
                                  const uint8_t family) {
    // Search for specified interface among detected interfaces.
    for (IfacePtr iface : ifaces_) {
        if ((iface->getFullName() != ifname) &&
            (iface->getName() != ifname)) {
            continue;
        }

        // Interface is now detected. Search for address on interface
        // that matches address family (v6 or v4).
        Iface::AddressCollection addrs = iface->getAddresses();
        Iface::AddressCollection::iterator addr_it = addrs.begin();
        while (addr_it != addrs.end()) {
            if (addr_it->get().getFamily() == family) {
                // We have interface and address so let's open socket.
                // This may cause isc::Unexpected exception.
                return (openSocket(iface->getName(), *addr_it, port, false));
            }
            ++addr_it;
        }
        // If we are at the end of address collection it means that we found
        // interface but there is no address for family specified.
        if (addr_it == addrs.end()) {
            // Stringify the family value to append it to exception string.
            std::string family_name("AF_INET");
            if (family == AF_INET6) {
                family_name = "AF_INET6";
            }
            // We did not find address on the interface.
            isc_throw(SocketConfigError, "There is no address for interface: "
                      << ifname << ", port: " << port << ", address "
                      " family: " << family_name);
        }
    }
    // If we got here it means that we had not found the specified interface.
    // Otherwise we would have returned from previous exist points.
    isc_throw(BadValue, "There is no " << ifname << " interface present.");
}

int IfaceMgr::openSocketFromAddress(const IOAddress& addr,
                                    const uint16_t port) {
    // Search through detected interfaces and addresses to match
    // local address we got.
    for (IfacePtr iface : ifaces_) {
        for (Iface::Address a : iface->getAddresses()) {

            // Local address must match one of the addresses
            // on detected interfaces. If it does, we have
            // address and interface detected so we can open
            // socket.
            if (a.get() == addr) {
                // Open socket using local interface, address and port.
                // This may cause isc::Unexpected exception.
                return (openSocket(iface->getName(), a, port, false));
            }
        }
    }
    // If we got here it means that we did not find specified address
    // on any available interface.
    isc_throw(BadValue, "There is no such address " << addr);
}

int IfaceMgr::openSocketFromRemoteAddress(const IOAddress& remote_addr,
                                          const uint16_t port) {
    try {
        // Get local address to be used to connect to remote location.
        IOAddress local_address(getLocalAddress(remote_addr, port));
        return openSocketFromAddress(local_address, port);
    } catch (const Exception& e) {
        isc_throw(SocketConfigError, e.what());
    }
}

isc::asiolink::IOAddress
IfaceMgr::getLocalAddress(const IOAddress& remote_addr, const uint16_t port) {
    // Create remote endpoint, we will be connecting to it.
    boost::scoped_ptr<const UDPEndpoint>
        remote_endpoint(static_cast<const UDPEndpoint*>
                        (UDPEndpoint::create(IPPROTO_UDP, remote_addr, port)));
    if (!remote_endpoint) {
        isc_throw(Unexpected, "Unable to create remote endpoint");
    }

    // Create socket that will be used to connect to remote endpoint.
    boost::asio::io_service io_service;
    boost::asio::ip::udp::socket sock(io_service);

    boost::system::error_code err_code;
    // If remote address is broadcast address we have to
    // allow this on the socket.
    if (remote_addr.isV4() &&
        (remote_addr == IOAddress(DHCP_IPV4_BROADCAST_ADDRESS))) {
        // Socket has to be open prior to setting the broadcast
        // option. Otherwise set_option will complain about
        // bad file descriptor.

        // @todo: We don't specify interface in any way here. 255.255.255.255
        // We can very easily end up with a socket working on a different
        // interface.

        // zero out the errno to be safe
        errno = 0;

        sock.open(boost::asio::ip::udp::v4(), err_code);
        if (err_code) {
            const char* errstr = strerror(errno);
            isc_throw(Unexpected, "failed to open UDPv4 socket, reason:"
                      << errstr);
        }
        sock.set_option(boost::asio::socket_base::broadcast(true), err_code);
        if (err_code) {
            sock.close();
            isc_throw(Unexpected, "failed to enable broadcast on the socket");
        }
    }

    // Try to connect to remote endpoint and check if attempt is successful.
    sock.connect(remote_endpoint->getASIOEndpoint(), err_code);
    if (err_code) {
        sock.close();
        isc_throw(Unexpected, "failed to connect to remote endpoint.");
    }

    // Once we are connected socket object holds local endpoint.
    boost::asio::ip::udp::socket::endpoint_type local_endpoint =
        sock.local_endpoint();
    boost::asio::ip::address local_address(local_endpoint.address());

    // Close the socket.
    sock.close();

    // Return address of local endpoint.
    return IOAddress(local_address);
}

int
IfaceMgr::openSocket4(Iface& iface, const IOAddress& addr, const uint16_t port,
                      const bool receive_bcast, const bool send_bcast) {
    // Assuming that packet filter is not null, because its modifier checks it.
    SocketInfo info = packet_filter_->openSocket(iface, addr, port,
                                                 receive_bcast, send_bcast);
    iface.addSocket(info);

    return (info.sockfd_);
}

bool
IfaceMgr::send(const Pkt6Ptr& pkt) {
    IfacePtr iface = getIface(pkt);
    if (!iface) {
        isc_throw(BadValue, "Unable to send DHCPv6 message. Invalid interface ("
                  << pkt->getIface() << ") specified.");
    }

    // Assuming that packet filter is not null, because its modifier checks it.
    // The packet filter returns an int but in fact it either returns 0 or throws.
    return (packet_filter6_->send(*iface, getSocket(pkt), pkt) == 0);
}

bool
IfaceMgr::send(const Pkt4Ptr& pkt) {
    IfacePtr iface = getIface(pkt);
    if (!iface) {
        isc_throw(BadValue, "Unable to send DHCPv4 message. Invalid interface ("
                  << pkt->getIface() << ") specified.");
    }

    // Assuming that packet filter is not null, because its modifier checks it.
    // The packet filter returns an int but in fact it either returns 0 or throws.
    return (packet_filter_->send(*iface, getSocket(pkt).sockfd_, pkt) == 0);
}

Pkt4Ptr IfaceMgr::receive4(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */) {
    if (isDHCPReceiverRunning()) {
        return (receive4Indirect(timeout_sec, timeout_usec));
    }

    return (receive4Direct(timeout_sec, timeout_usec));
}

Pkt4Ptr IfaceMgr::receive4Indirect(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */) {
    // Sanity check for microsecond timeout.
    if (timeout_usec >= 1000000) {
        isc_throw(BadValue, "fractional timeout must be shorter than"
                  " one million microseconds");
    }

    fd_set sockets;
    int maxfd = 0;

    FD_ZERO(&sockets);

    // if there are any callbacks for external sockets registered...
    {
        std::lock_guard<std::mutex> lock(callbacks_mutex_);
        if (!callbacks_.empty()) {
            for (SocketCallbackInfo s : callbacks_) {
                // Add this socket to listening set
                addFDtoSet(s.socket_, maxfd, &sockets);
            }
        }
    }

    // Add Receiver ready watch socket
    addFDtoSet(dhcp_receiver_->getWatchFd(WatchedThread::READY), maxfd, &sockets);

    // Add Receiver error watch socket
    addFDtoSet(dhcp_receiver_->getWatchFd(WatchedThread::ERROR), maxfd, &sockets);

    // Set timeout for our next select() call.  If there are
    // no DHCP packets to read, then we'll wait for a finite
    // amount of time for an IO event.  Otherwise, we'll
    // poll (timeout = 0 secs).  We need to poll, even if
    // DHCP packets are waiting so we don't starve external
    // sockets under heavy DHCP load.
    struct timeval select_timeout;
    if (getPacketQueue4()->empty()) {
        select_timeout.tv_sec = timeout_sec;
        select_timeout.tv_usec = timeout_usec;
    } else {
        select_timeout.tv_sec = 0;
        select_timeout.tv_usec = 0;
    }

    // zero out the errno to be safe
    errno = 0;

    int result = select(maxfd + 1, &sockets, 0, 0, &select_timeout);

    if ((result == 0) && getPacketQueue4()->empty()) {
        // nothing received and timeout has been reached
        return (Pkt4Ptr());
    } else if (result < 0) {
        // In most cases we would like to know whether select() returned
        // an error because of a signal being received  or for some other
        // reason. This is because DHCP servers use signals to trigger
        // certain actions, like reconfiguration or graceful shutdown.
        // By catching a dedicated exception the caller will know if the
        // error returned by the function is due to the reception of the
        // signal or for some other reason.
        if (errno == EINTR) {
            isc_throw(SignalInterruptOnSelect, strerror(errno));
        } else if (errno == EBADF) {
            int cnt = purgeBadSockets();
            isc_throw(SocketReadError,
                      "SELECT interrupted by one invalid sockets, purged "
                       << cnt << " socket descriptors");
        } else {
            isc_throw(SocketReadError, strerror(errno));
        }
    }

    // We only check external sockets if select detected an event.
    if (result > 0) {
        // Check for receiver thread read errors.
        if (dhcp_receiver_->isReady(WatchedThread::ERROR)) {
            string msg = dhcp_receiver_->getLastError();
            dhcp_receiver_->clearReady(WatchedThread::ERROR);
            isc_throw(SocketReadError, msg);
        }

        // Let's find out which external socket has the data
        SocketCallbackInfo ex_sock;
        bool found = false;
        {
            std::lock_guard<std::mutex> lock(callbacks_mutex_);
            for (SocketCallbackInfo s : callbacks_) {
                if (!FD_ISSET(s.socket_, &sockets)) {
                    continue;
                }
                found = true;

                // something received over external socket
                if (s.callback_) {
                    // Note the external socket to call its callback without
                    // the lock taken so it can be deleted.
                    ex_sock = s;
                    break;
                }
            }
        }

        if (ex_sock.callback_) {
            // Calling the external socket's callback provides its service
            // layer access without integrating any specific features
            // in IfaceMgr
            ex_sock.callback_(ex_sock.socket_);
        }
        if (found) {
            return (Pkt4Ptr());
        }
    }

    // If we're here it should only be because there are DHCP packets waiting.
    Pkt4Ptr pkt = getPacketQueue4()->dequeuePacket();
    if (!pkt) {
        dhcp_receiver_->clearReady(WatchedThread::READY);
    }

    return (pkt);
}

Pkt4Ptr IfaceMgr::receive4Direct(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */) {
    // Sanity check for microsecond timeout.
    if (timeout_usec >= 1000000) {
        isc_throw(BadValue, "fractional timeout must be shorter than"
                  " one million microseconds");
    }
    boost::scoped_ptr<SocketInfo> candidate;
    fd_set sockets;
    int maxfd = 0;

    FD_ZERO(&sockets);

    /// @todo: marginal performance optimization. We could create the set once
    /// and then use its copy for select(). Please note that select() modifies
    /// provided set to indicated which sockets have something to read.
    for (IfacePtr iface : ifaces_) {
        for (SocketInfo s : iface->getSockets()) {
            // Only deal with IPv4 addresses.
            if (s.addr_.isV4()) {
                // Add this socket to listening set
                addFDtoSet(s.sockfd_, maxfd, &sockets);
            }
        }
    }

    // if there are any callbacks for external sockets registered...
    {
        std::lock_guard<std::mutex> lock(callbacks_mutex_);
        if (!callbacks_.empty()) {
            for (SocketCallbackInfo s : callbacks_) {
                // Add this socket to listening set
                addFDtoSet(s.socket_, maxfd, &sockets);
            }
        }
    }

    struct timeval select_timeout;
    select_timeout.tv_sec = timeout_sec;
    select_timeout.tv_usec = timeout_usec;

    // zero out the errno to be safe
    errno = 0;

    int result = select(maxfd + 1, &sockets, 0, 0, &select_timeout);

    if (result == 0) {
        // nothing received and timeout has been reached
        return (Pkt4Ptr()); // null

    } else if (result < 0) {
        // In most cases we would like to know whether select() returned
        // an error because of a signal being received  or for some other
        // reason. This is because DHCP servers use signals to trigger
        // certain actions, like reconfiguration or graceful shutdown.
        // By catching a dedicated exception the caller will know if the
        // error returned by the function is due to the reception of the
        // signal or for some other reason.
        if (errno == EINTR) {
            isc_throw(SignalInterruptOnSelect, strerror(errno));
        } else if (errno == EBADF) {
            int cnt = purgeBadSockets();
            isc_throw(SocketReadError,
                      "SELECT interrupted by one invalid sockets, purged "
                       << cnt << " socket descriptors");
        } else {
            isc_throw(SocketReadError, strerror(errno));
        }
    }

    // Let's find out which socket has the data
    SocketCallbackInfo ex_sock;
    bool found = false;
    {
        std::lock_guard<std::mutex> lock(callbacks_mutex_);
        for (SocketCallbackInfo s : callbacks_) {
            if (!FD_ISSET(s.socket_, &sockets)) {
                continue;
            }
            found = true;

            // something received over external socket
            if (s.callback_) {
                // Note the external socket to call its callback without
                // the lock taken so it can be deleted.
                ex_sock = s;
                break;
            }
        }
    }

    if (ex_sock.callback_) {
        // Calling the external socket's callback provides its service
        // layer access without integrating any specific features
        // in IfaceMgr
        ex_sock.callback_(ex_sock.socket_);
    }
    if (found) {
        return (Pkt4Ptr());
    }

    // Let's find out which interface/socket has the data
    IfacePtr recv_if;
    for (IfacePtr iface : ifaces_) {
        for (SocketInfo s : iface->getSockets()) {
            if (FD_ISSET(s.sockfd_, &sockets)) {
                candidate.reset(new SocketInfo(s));
                break;
            }
        }
        if (candidate) {
            recv_if = iface;
            break;
        }
    }

    if (!candidate || !recv_if) {
        isc_throw(SocketReadError, "received data over unknown socket");
    }

    // Now we have a socket, let's get some data from it!
    // Assuming that packet filter is not null, because its modifier checks it.
    return (packet_filter_->receive(*recv_if, *candidate));
}

Pkt6Ptr
IfaceMgr::receive6(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */) {
    if (isDHCPReceiverRunning()) {
        return (receive6Indirect(timeout_sec, timeout_usec));
    }

    return (receive6Direct(timeout_sec, timeout_usec));
}

void
IfaceMgr::addFDtoSet(int fd, int& maxfd, fd_set* sockets) {
    if (!sockets) {
        isc_throw(BadValue, "addFDtoSet: sockets can't be null");
    }

    FD_SET(fd, sockets);
    if (maxfd < fd) {
        maxfd = fd;
    }
}

Pkt6Ptr
IfaceMgr::receive6Direct(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */ ) {
    // Sanity check for microsecond timeout.
    if (timeout_usec >= 1000000) {
        isc_throw(BadValue, "fractional timeout must be shorter than"
                  " one million microseconds");
    }

    boost::scoped_ptr<SocketInfo> candidate;
    fd_set sockets;
    int maxfd = 0;

    FD_ZERO(&sockets);

    /// @todo: marginal performance optimization. We could create the set once
    /// and then use its copy for select(). Please note that select() modifies
    /// provided set to indicated which sockets have something to read.
    for (IfacePtr iface : ifaces_) {
        for (SocketInfo s : iface->getSockets()) {
            // Only deal with IPv6 addresses.
            if (s.addr_.isV6()) {
                // Add this socket to listening set
                addFDtoSet(s.sockfd_, maxfd, &sockets);
            }
        }
    }

    // if there are any callbacks for external sockets registered...
    {
        std::lock_guard<std::mutex> lock(callbacks_mutex_);
        if (!callbacks_.empty()) {
            for (SocketCallbackInfo s : callbacks_) {
                // Add this socket to listening set
                addFDtoSet(s.socket_, maxfd, &sockets);
            }
        }
    }

    struct timeval select_timeout;
    select_timeout.tv_sec = timeout_sec;
    select_timeout.tv_usec = timeout_usec;

    // zero out the errno to be safe
    errno = 0;

    int result = select(maxfd + 1, &sockets, 0, 0, &select_timeout);

    if (result == 0) {
        // nothing received and timeout has been reached
        return (Pkt6Ptr()); // null

    } else if (result < 0) {
        // In most cases we would like to know whether select() returned
        // an error because of a signal being received  or for some other
        // reason. This is because DHCP servers use signals to trigger
        // certain actions, like reconfiguration or graceful shutdown.
        // By catching a dedicated exception the caller will know if the
        // error returned by the function is due to the reception of the
        // signal or for some other reason.
        if (errno == EINTR) {
            isc_throw(SignalInterruptOnSelect, strerror(errno));
        } else if (errno == EBADF) {
            int cnt = purgeBadSockets();
            isc_throw(SocketReadError,
                      "SELECT interrupted by one invalid sockets, purged "
                       << cnt << " socket descriptors");
        } else {
            isc_throw(SocketReadError, strerror(errno));
        }
    }

    // Let's find out which socket has the data
    SocketCallbackInfo ex_sock;
    bool found = false;
    {
        std::lock_guard<std::mutex> lock(callbacks_mutex_);
        for (SocketCallbackInfo s : callbacks_) {
            if (!FD_ISSET(s.socket_, &sockets)) {
                continue;
            }
            found = true;

            // something received over external socket
            if (s.callback_) {
                // Note the external socket to call its callback without
                // the lock taken so it can be deleted.
                ex_sock = s;
                break;
            }
        }
    }

    if (ex_sock.callback_) {
        // Calling the external socket's callback provides its service
        // layer access without integrating any specific features
        // in IfaceMgr
        ex_sock.callback_(ex_sock.socket_);
    }
    if (found) {
        return (Pkt6Ptr());
    }

    // Let's find out which interface/socket has the data
    for (IfacePtr iface : ifaces_) {
        for (SocketInfo s : iface->getSockets()) {
            if (FD_ISSET(s.sockfd_, &sockets)) {
                candidate.reset(new SocketInfo(s));
                break;
            }
        }
        if (candidate) {
            break;
        }
    }

    if (!candidate) {
        isc_throw(SocketReadError, "received data over unknown socket");
    }
    // Assuming that packet filter is not null, because its modifier checks it.
    return (packet_filter6_->receive(*candidate));
}

Pkt6Ptr
IfaceMgr::receive6Indirect(uint32_t timeout_sec, uint32_t timeout_usec /* = 0 */ ) {
    // Sanity check for microsecond timeout.
    if (timeout_usec >= 1000000) {
        isc_throw(BadValue, "fractional timeout must be shorter than"
                  " one million microseconds");
    }

    fd_set sockets;
    int maxfd = 0;

    FD_ZERO(&sockets);

    // if there are any callbacks for external sockets registered...
    {
        std::lock_guard<std::mutex> lock(callbacks_mutex_);
        if (!callbacks_.empty()) {
            for (SocketCallbackInfo s : callbacks_) {
                // Add this socket to listening set
                addFDtoSet(s.socket_, maxfd, &sockets);
            }
        }
    }

    // Add Receiver ready watch socket
    addFDtoSet(dhcp_receiver_->getWatchFd(WatchedThread::READY), maxfd, &sockets);

    // Add Receiver error watch socket
    addFDtoSet(dhcp_receiver_->getWatchFd(WatchedThread::ERROR), maxfd, &sockets);

    // Set timeout for our next select() call.  If there are
    // no DHCP packets to read, then we'll wait for a finite
    // amount of time for an IO event.  Otherwise, we'll
    // poll (timeout = 0 secs).  We need to poll, even if
    // DHCP packets are waiting so we don't starve external
    // sockets under heavy DHCP load.
    struct timeval select_timeout;
    if (getPacketQueue6()->empty()) {
        select_timeout.tv_sec = timeout_sec;
        select_timeout.tv_usec = timeout_usec;
    } else {
        select_timeout.tv_sec = 0;
        select_timeout.tv_usec = 0;
    }

    // zero out the errno to be safe
    errno = 0;

    int result = select(maxfd + 1, &sockets, 0, 0, &select_timeout);

    if ((result == 0) && getPacketQueue6()->empty()) {
        // nothing received and timeout has been reached
        return (Pkt6Ptr());
    } else if (result < 0) {
        // In most cases we would like to know whether select() returned
        // an error because of a signal being received  or for some other
        // reason. This is because DHCP servers use signals to trigger
        // certain actions, like reconfiguration or graceful shutdown.
        // By catching a dedicated exception the caller will know if the
        // error returned by the function is due to the reception of the
        // signal or for some other reason.
        if (errno == EINTR) {
            isc_throw(SignalInterruptOnSelect, strerror(errno));
        } else if (errno == EBADF) {
            int cnt = purgeBadSockets();
            isc_throw(SocketReadError,
                      "SELECT interrupted by one invalid sockets, purged "
                       << cnt << " socket descriptors");
        } else {
            isc_throw(SocketReadError, strerror(errno));
        }
    }

    // We only check external sockets if select detected an event.
    if (result > 0) {
        // Check for receiver thread read errors.
        if (dhcp_receiver_->isReady(WatchedThread::ERROR)) {
            string msg = dhcp_receiver_->getLastError();
            dhcp_receiver_->clearReady(WatchedThread::ERROR);
            isc_throw(SocketReadError, msg);
        }

        // Let's find out which external socket has the data
        SocketCallbackInfo ex_sock;
        bool found = false;
        {
            std::lock_guard<std::mutex> lock(callbacks_mutex_);
            for (SocketCallbackInfo s : callbacks_) {
                if (!FD_ISSET(s.socket_, &sockets)) {
                    continue;
                }
                found = true;

                // something received over external socket
                if (s.callback_) {
                    // Note the external socket to call its callback without
                    // the lock taken so it can be deleted.
                    ex_sock = s;
                    break;
                }
            }
        }

        if (ex_sock.callback_) {
            // Calling the external socket's callback provides its service
            // layer access without integrating any specific features
            // in IfaceMgr
            ex_sock.callback_(ex_sock.socket_);
        }
        if (found) {
            return (Pkt6Ptr());
        }
    }

    // If we're here it should only be because there are DHCP packets waiting.
    Pkt6Ptr pkt = getPacketQueue6()->dequeuePacket();
    if (!pkt) {
        dhcp_receiver_->clearReady(WatchedThread::READY);
    }

    return (pkt);
}

void
IfaceMgr::receiveDHCP4Packets() {
    fd_set sockets;
    int maxfd = 0;

    FD_ZERO(&sockets);

    // Add terminate watch socket.
    addFDtoSet(dhcp_receiver_->getWatchFd(WatchedThread::TERMINATE), maxfd, &sockets);

    // Add Interface sockets.
    for (IfacePtr iface : ifaces_) {
        for (SocketInfo s : iface->getSockets()) {
            // Only deal with IPv4 addresses.
            if (s.addr_.isV4()) {
                // Add this socket to listening set.
                addFDtoSet(s.sockfd_, maxfd, &sockets);
            }
        }
    }

    for (;;) {
        // Check the watch socket.
        if (dhcp_receiver_->shouldTerminate()) {
            return;
        }

        fd_set rd_set;
        FD_COPY(&sockets, &rd_set);

        // zero out the errno to be safe.
        errno = 0;

        // Select with null timeouts to wait indefinitely an event
        int result = select(maxfd + 1, &rd_set, 0, 0, 0);

        // Re-check the watch socket.
        if (dhcp_receiver_->shouldTerminate()) {
            return;
        }

        if (result == 0) {
            // nothing received?
            continue;

        } else if (result < 0) {
            // This thread should not get signals?
            if (errno != EINTR) {
                // Signal the error to receive4.
                dhcp_receiver_->setError(strerror(errno));
                // We need to sleep in case of the error condition to
                // prevent the thread from tight looping when result
                // gets negative.
                sleep(1);
            }
            continue;
        }

        // Let's find out which interface/socket has data.
        for (IfacePtr iface : ifaces_) {
            for (SocketInfo s : iface->getSockets()) {
                if (FD_ISSET(s.sockfd_, &sockets)) {
                    receiveDHCP4Packet(*iface, s);
                    // Can take time so check one more time the watch socket.
                    if (dhcp_receiver_->shouldTerminate()) {
                        return;
                    }
                }
            }
        }
    }

}

void
IfaceMgr::receiveDHCP6Packets() {
    fd_set sockets;
    int maxfd = 0;

    FD_ZERO(&sockets);

    // Add terminate watch socket.
    addFDtoSet(dhcp_receiver_->getWatchFd(WatchedThread::TERMINATE), maxfd, &sockets);

    // Add Interface sockets.
    for (IfacePtr iface : ifaces_) {
        for (SocketInfo s : iface->getSockets()) {
            // Only deal with IPv6 addresses.
            if (s.addr_.isV6()) {
                // Add this socket to listening set.
                addFDtoSet(s.sockfd_ , maxfd, &sockets);
            }
        }
    }

    for (;;) {
        // Check the watch socket.
        if (dhcp_receiver_->shouldTerminate()) {
            return;
        }

        fd_set rd_set;
        FD_COPY(&sockets, &rd_set);

        // zero out the errno to be safe.
        errno = 0;

        // Note we wait until something happen.
        int result = select(maxfd + 1, &rd_set, 0, 0, 0);

        // Re-check the watch socket.
        if (dhcp_receiver_->shouldTerminate()) {
            return;
        }

        if (result == 0) {
            // nothing received?
            continue;
        } else if (result < 0) {
            // This thread should not get signals?
            if (errno != EINTR) {
                // Signal the error to receive6.
                dhcp_receiver_->setError(strerror(errno));
                // We need to sleep in case of the error condition to
                // prevent the thread from tight looping when result
                // gets negative.
                sleep(1);
            }
            continue;
        }

        // Let's find out which interface/socket has data.
        for (IfacePtr iface : ifaces_) {
            for (SocketInfo s : iface->getSockets()) {
                if (FD_ISSET(s.sockfd_, &sockets)) {
                    receiveDHCP6Packet(s);
                    // Can take time so check one more time the watch socket.
                    if (dhcp_receiver_->shouldTerminate()) {
                        return;
                    }
                }
            }
        }
    }
}

void
IfaceMgr::receiveDHCP4Packet(Iface& iface, const SocketInfo& socket_info) {
    int len;

    int result = ioctl(socket_info.sockfd_, FIONREAD, &len);
    if (result < 0) {
        // Signal the error to receive4.
        dhcp_receiver_->setError(strerror(errno));
        return;
    }
    if (len == 0) {
        // Nothing to read.
        return;
    }

    Pkt4Ptr pkt;

    try {
        pkt = packet_filter_->receive(iface, socket_info);
    } catch (const std::exception& ex) {
        dhcp_receiver_->setError(strerror(errno));
    } catch (...) {
        dhcp_receiver_->setError("packet filter receive() failed");
    }

    if (pkt) {
        getPacketQueue4()->enqueuePacket(pkt, socket_info);
        dhcp_receiver_->markReady(WatchedThread::READY);
    }
}

void
IfaceMgr::receiveDHCP6Packet(const SocketInfo& socket_info) {
    int len;

    int result = ioctl(socket_info.sockfd_, FIONREAD, &len);
    if (result < 0) {
        // Signal the error to receive6.
        dhcp_receiver_->setError(strerror(errno));
        return;
    }
    if (len == 0) {
        // Nothing to read.
        return;
    }

    Pkt6Ptr pkt;

    try {
        pkt = packet_filter6_->receive(socket_info);
    } catch (const std::exception& ex) {
        dhcp_receiver_->setError(ex.what());
    } catch (...) {
        dhcp_receiver_->setError("packet filter receive() failed");
    }

    if (pkt) {
        getPacketQueue6()->enqueuePacket(pkt, socket_info);
        dhcp_receiver_->markReady(WatchedThread::READY);
    }
}

uint16_t
IfaceMgr::getSocket(const isc::dhcp::Pkt6Ptr& pkt) {
    IfacePtr iface = getIface(pkt);
    if (!iface) {
        isc_throw(IfaceNotFound, "Tried to find socket for non-existent interface");
    }


    const Iface::SocketCollection& socket_collection = iface->getSockets();

    Iface::SocketCollection::const_iterator candidate = socket_collection.end();

    Iface::SocketCollection::const_iterator s;
    for (s = socket_collection.begin(); s != socket_collection.end(); ++s) {

        // We should not merge those conditions for debugging reasons.

        // V4 sockets are useless for sending v6 packets.
        if (s->family_ != AF_INET6) {
            continue;
        }

        // Sockets bound to multicast address are useless for sending anything.
        if (s->addr_.isV6Multicast()) {
            continue;
        }

        if (s->addr_ == pkt->getLocalAddr()) {
            // This socket is bound to the source address. This is perfect
            // match, no need to look any further.
            return (s->sockfd_);
        }

        // If we don't have any other candidate, this one will do
        if (candidate == socket_collection.end()) {
            candidate = s;
        } else {
            // If we want to send something to link-local and the socket is
            // bound to link-local or we want to send to global and the socket
            // is bound to global, then use it as candidate
            if ( (pkt->getRemoteAddr().isV6LinkLocal() &&
                s->addr_.isV6LinkLocal()) ||
                 (!pkt->getRemoteAddr().isV6LinkLocal() &&
                  !s->addr_.isV6LinkLocal()) ) {
                candidate = s;
            }
        }
    }

    if (candidate != socket_collection.end()) {
        return (candidate->sockfd_);
    }

    isc_throw(SocketNotFound, "Interface " << iface->getFullName()
              << " does not have any suitable IPv6 sockets open.");
}

SocketInfo
IfaceMgr::getSocket(const isc::dhcp::Pkt4Ptr& pkt) {
    IfacePtr iface = getIface(pkt);
    if (!iface) {
        isc_throw(IfaceNotFound, "Tried to find socket for non-existent interface");
    }

    const Iface::SocketCollection& socket_collection = iface->getSockets();
    // A candidate being an end of the iterator marks that it is a beginning of
    // the socket search and that the candidate needs to be set to the first
    // socket found.
    Iface::SocketCollection::const_iterator candidate = socket_collection.end();
    Iface::SocketCollection::const_iterator s;
    for (s = socket_collection.begin(); s != socket_collection.end(); ++s) {
        if (s->family_ == AF_INET) {
            if (s->addr_ == pkt->getLocalAddr()) {
                return (*s);
            }

            if (candidate == socket_collection.end()) {
                candidate = s;
            }
        }
    }

    if (candidate == socket_collection.end()) {
        isc_throw(SocketNotFound, "Interface " << iface->getFullName()
                  << " does not have any suitable IPv4 sockets open.");
    }

    return (*candidate);
}

bool
IfaceMgr::configureDHCPPacketQueue(uint16_t family, data::ConstElementPtr queue_control) {
    if (isDHCPReceiverRunning()) {
        isc_throw(InvalidOperation, "Cannot reconfigure queueing"
                                    " while DHCP receiver thread is running");
    }

    bool enable_queue = false;
    if (queue_control) {
        try {
            enable_queue = data::SimpleParser::getBoolean(queue_control, "enable-queue");
        } catch (...) {
            // @todo - for now swallow not found errors.
            // if not present we assume default
        }
    }

    if (enable_queue) {
        // Try to create the queue as configured.
        if (family == AF_INET) {
            packet_queue_mgr4_->createPacketQueue(queue_control);
        } else {
            packet_queue_mgr6_->createPacketQueue(queue_control);
        }
    } else {
        // Destroy the current queue (if one), this inherently disables threading.
        if (family == AF_INET) {
            packet_queue_mgr4_->destroyPacketQueue();
        } else {
            packet_queue_mgr6_->destroyPacketQueue();
        }
    }

    return(enable_queue);
}

void
Iface::addError(std::string const& message) {
    errors_.push_back(message);
}

void
Iface::clearErrors() {
    errors_.clear();
}

Iface::ErrorBuffer const&
Iface::getErrors() const {
    return errors_;
}

} // end of namespace isc::dhcp
} // end of namespace isc