aboutsummaryrefslogtreecommitdiffstats
path: root/hicn-light/src/hicn/socket/ops_linux.c
blob: 8bfc438f346c292bf4916240ca29f037405c740b (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
#include <sys/ioctl.h>   // ioctl
#include <sys/socket.h>  // needed by linux/if.h
#include <errno.h>
#include <fcntl.h>  // ''
#include <linux/if_tun.h>
#include <linux/limits.h>  // PATH_MAX
#include <stdio.h>         // fprintf
#include <string.h>        // memset
#include <sys/stat.h>      // open
#include <sys/uio.h>       // writev
#include <unistd.h>        // close

#include "error.h"
#include "ops.h"

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))

/******************************************************************************
 * netlink.h
 ******************************************************************************/

#ifndef HICN_NETLINK_H
#define HICN_NETLINK_H

#include <stdint.h>
#include <stdlib.h>

/* Public interface */

/**
 * Get the interface ID of an interface by its name
 *
 * @return 32-bit interface identifier in case of success, or 0.
 *
 * @see if_nametoindex
 *
 */
uint32_t _nl_get_ifid(const char *ifname);

/**
 * Retrieve the output interface corresponding to the specified IP address.
 *
 * @param [in] addr IP(v6) address in presentation form.
 * @param [out] Identifier of the corresponding output interface.
 * @return int 0 in case of success, -1 otherwise
 */
int _nl_get_output_ifid(const char *ip_address, uint8_t address_family,
                        uint32_t *interface_id);

/**
 * Retrieve the first IP address of an interface (identified by its id) which
 * has a netmask < 128.
 *
 * @param [in] s File descriptor of the netlink socket (deprecated).
 * @param [in] interface_id Identifier of the interface for which to retrieve
 *      the IP address.
 * @param [out] addr IP(v6) address in binary form.
 * @return int 0 in case of success, -1 otherwise
 *
 * @see getifaddrs
 */
int _nl_get_ip_addr(uint32_t interface_id, uint8_t address_family,
                    ip_prefix_t *ip_address);

int _nl_set_ip_addr(uint32_t interface_id, ip_prefix_t *ip_address);

int _nl_up_if(uint32_t interface_id);

int _nl_add_in_route_table(const ip_prefix_t *prefix,
                           const uint32_t interface_id, const uint8_t table_id);
int _nl_add_in_route_table_s(const char *prefix, const uint32_t interface_id,
                             const uint8_t table_id);
int _nl_add_in_route_s(const char *prefix, const uint32_t interface_id);

int _nl_add_out_route(const char *gateway, const uint8_t address_family,
                      const uint8_t table_idi, int default_route);
int _nl_del_out_route(const char *gateway, const uint8_t address_family,
                      const uint8_t table_id);

int _nl_del_lo_route(const ip_prefix_t *ip_address);

int _nl_add_rule(const char *interface_name, const uint8_t address_family,
                 const uint8_t table_id);
int _nl_del_rule(const char *interface_name, const uint8_t address_family,
                 const uint8_t table_id);

int _nl_add_neigh_proxy(const ip_prefix_t *ip_address,
                        const uint32_t interface_id);

int _nl_add_prio_rule(const ip_prefix_t *ip_address,
                      const uint8_t address_family, const uint32_t priority,
                      const uint8_t table_id);
int _nl_add_lo_prio_rule(const ip_prefix_t *ip_address,
                         const uint8_t address_family, const uint32_t priority);
int _nl_del_prio_rule(const ip_prefix_t *ip_address,
                      const uint8_t address_family, const uint32_t priority,
                      const uint8_t table_id);
int _nl_del_lo_prio_rule(const ip_prefix_t *ip_address,
                         const uint8_t address_family, const uint32_t priority);

#endif /* HICN_NETLINK_H */

/******************************************************************************
 * netlink.c
 ******************************************************************************/

/*
 * This module offers an interface to the Netlink API appropriate for
 * implementing punting as required by hICN (1).
 *
 * More specifically, it consists of the following functionalities:
 *  - LINK
 *     . map interface name to ID
 *     . set and interface up
 *  - ADDR
 *     . get and set ip addresses on a given interface ID
 *  - ROUTE
 *     . get output interface id towards IP (ip route get IP > interface_id)
 *     . add input route (ip route add PREFIX dev INTERFACE) for punting
 *     interests . add output route (ip route add default GATEWAY table TABLE)
 *     for routing interests (2, 3)
 *     . delete local route towards IP (ip route del IP table local)
 *  - RULE
 *     . add output rule (ip rule add iif interface table TABLE) for routing
 *     interests (2, 3) - ND PROXY
 *     . enable NDP proxy functionality for IP on interface ID (ip -6 neigh add
 *     proxy IP dev INTERFACE) for allowing the TUN to be reachable on the
 *     reverse data path
 *
 * Implementation notes:
 *  (1) We have not been using the libnl library because it requires
 *      manipulating too many function and data structures for a simple purpose.
 *      Currently, many parts of the code are somehow repetitive, but this might
 *      be improved by a proper API in a future release.
 *  (2) allows load balancing over different interfaces = multihoming. Please
 *      note that it is not possible to have load balancing over two faces using
 *      the same output interface as we are using the underlying IP network !
 *      This might be mitigated with the use of SR however.
 *  (3) The implementation of punting heavily uses the policy routing
 *      functionalities, as we need to hook through a TUN into user space a
 *      whole prefix used as a destination (for interests) or source (for data
 *      packets). We thus combine the use of rules to assign routing table IDs,
 *      and routes inside those tables. As there is no easy way to allocate
 *      which routing tables we use, we made the choice to index them by the ID
 *      of the interface, assuming there is no external conflict. This might be
 *      improved in the future.
 *
 *      This hICN implementation uses TUNs in two different ways:
 *       - a main TUN interface, which receives all punted interests,
 *       demultiplex them before assigning them an input face (eventually
 *       dynamically creating it);
 *       - a set of output TUN interfaces, aka faces, used for routing of
 *       interests, and for receiving the corresponding data packets on the way
 *       back. Punting of data packets if based of their destination IP, which
 *       is the IP of the physical output interface used for the interest, which
 *       is unique (cf (2)).
 *
 *      The corresponding routing tables IDs are :
 *       MAIN_TUN_ID -> used for punting of data packets
 *       OUTPUT_TUN_ID_i -> used for routing of interests towards next hop
 *       (bypassing local IP routing table)
 *
 *      Note that punting of interests is done just through a route, and routing
 *      of data packets is done just through the regular IP routing table on the
 *      note after the address translation done in the forwarder.
 *
 *   - Forging netlink packets
 *
 *     A previous implementation used function calls with pointers to populate
 *     the various header parts in a buffer in order to build a netlink packet.
 *     A newer implementation uses nested structs and iovecs to build the whole
 *     packet in a single write call. This should allow a simpler evolution
 *     towards a cleaner API.
 */

#include <arpa/inet.h>        // inet_pton
#include <errno.h>            // errno
#include <linux/fib_rules.h>  // fib_rule_hdr, FRA_*
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <net/if.h>      // IFF_UP
#include <netinet/in.h>  // in6addr
#include <stdio.h>       // perror
#include <string.h>
#include <sys/socket.h>  // ''
#include <sys/types.h>   // socket
#include <unistd.h>      // read

#include <sys/socket.h>  // ''
#include <sys/types.h>   // send, recv

#define BUFSIZE 4096
#define FLAGS_CREATE NLM_F_REQUEST | NLM_F_CREATE | NLM_F_ACK
#define FLAGS_CREATE_MATCH \
  NLM_F_REQUEST | NLM_F_CREATE | NLM_F_ACK | NLM_F_MATCH

#define FLAGS_GET NLM_F_REQUEST
#define FLAGS_GET_ROOT (NLM_F_REQUEST | NLM_F_ROOT)

#define FLAGS_LIST NLM_F_REQUEST | NLM_F_DUMP

#ifndef __ANDROID__
#define IF_NAMESIZE 16
#endif
#define FR_ACT_TO_TBL 1
#define NLMSG_BOTTOM(nlmsg) \
  ((struct rtattr *)(((void *)(nlmsg)) + NLMSG_ALIGN((nlmsg)->nlmsg_len)))

int seq = 1;

static inline size_t iov_length(const struct iovec *iov,
                                unsigned long nr_segs) {
  unsigned long seg;
  size_t ret = 0;

  for (seg = 0; seg < nr_segs; seg++) ret += iov[seg].iov_len;
  return ret;
}

typedef struct {
  struct nlmsghdr hdr;
  struct nlmsgerr payload;
} nl_err_hdr_t;

/* Low level : nl header */

int _nl_get_socket() { return socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); }

int _nl_header(int request, uint8_t *buffer, size_t len, uint32_t flags) {
  struct nlmsghdr *nl = (struct nlmsghdr *)buffer;

  nl->nlmsg_len = 0;  // NLMSG_LENGTH(sizeof(struct ifinfomsg));
  nl->nlmsg_type = request;
  nl->nlmsg_flags = flags;
  nl->nlmsg_seq = seq++;  //
  nl->nlmsg_pid = 0;      // getpid();

  return 0;
}

/* Low level : nl protocols */

/* Low level : attributes */

int addAttr(struct nlmsghdr *nl, int maxlen, int type, void *data,
            int attr_len) {
  struct rtattr *rta;
  int len = RTA_LENGTH(attr_len);

  if (NLMSG_ALIGN(nl->nlmsg_len) + len > maxlen) {
    exit(EXIT_FAILURE);
  }

  rta = (struct rtattr *)((char *)nl + NLMSG_ALIGN(nl->nlmsg_len));
  rta->rta_type = type;
  rta->rta_len = len;
  memcpy(RTA_DATA(rta), data, attr_len);
  nl->nlmsg_len = NLMSG_ALIGN(nl->nlmsg_len) + len;
  return 0;
}

int _nl_payload_rule(uint8_t table_id, uint8_t address_family, uint8_t *buffer,
                     size_t len) {
  struct nlmsghdr *nl = (struct nlmsghdr *)buffer;
  struct fib_rule_hdr *frh = (struct fib_rule_hdr *)(NLMSG_DATA(buffer));

  memset(frh, 0, sizeof(struct fib_rule_hdr));
  frh->family = address_family;
  frh->table = table_id;
  frh->action = FR_ACT_TO_TBL,
  frh->flags = NLM_F_REPLACE;  // 0
  frh->tos = 0;

  nl->nlmsg_len += NLMSG_LENGTH(sizeof(struct fib_rule_hdr));

  return 0;
}

int _nl_payload_link(uint32_t ifindex, uint8_t *buffer, size_t len) {
  struct nlmsghdr *nl = (struct nlmsghdr *)buffer;
  struct ifinfomsg *ifi = (struct ifinfomsg *)(NLMSG_DATA(buffer));

  memset(ifi, 0, sizeof(struct ifinfomsg));
  ifi->ifi_family = AF_UNSPEC;
  // ifi->ifi_type = 0;
  ifi->ifi_index =
      ifindex;  // new interface, could be specified since linux 3.7
  ifi->ifi_flags = 0;
  // ifi->ifi_change = 0xffffffff;

  nl->nlmsg_len += NLMSG_LENGTH(sizeof(struct ifinfomsg));

  return 0;
}

int _nl_payload_addr(uint32_t ifindex, uint8_t *buffer, size_t len) {
  struct nlmsghdr *nl = (struct nlmsghdr *)buffer;
  struct ifaddrmsg *addr = (struct ifaddrmsg *)(NLMSG_DATA(buffer));

  memset(addr, 0, sizeof(struct ifaddrmsg));
  addr->ifa_family = AF_UNSPEC;  // INET6;
  /*
     addr->ifa_prefixlen = 128;
     addr->ifa_flags = 0;
     addr->ifa_scope = RT_SCOPE_LINK; //IFA_ADDRESS;
     addr->ifa_index = ifindex;
     */

  nl->nlmsg_len += NLMSG_LENGTH(sizeof(struct ifaddrmsg)) - 4;

  return 0;
}

int _nl_payload_route(uint8_t table_id, uint8_t addr_family, uint8_t dst_len,
                      uint8_t *buffer, size_t len) {
  struct nlmsghdr *nl = (struct nlmsghdr *)buffer;
  struct rtmsg *raddr = (struct rtmsg *)(NLMSG_DATA(buffer));

  raddr->rtm_family = addr_family;
  raddr->rtm_dst_len = dst_len;
  raddr->rtm_src_len = 0;
  raddr->rtm_tos = 0;

  raddr->rtm_table = table_id;
  raddr->rtm_protocol = RTPROT_BOOT;
  raddr->rtm_scope = RT_SCOPE_UNIVERSE;
  raddr->rtm_type = RTN_UNICAST;

  raddr->rtm_flags = 0;

  nl->nlmsg_len += NLMSG_LENGTH(sizeof(struct rtmsg));

  return 0;
}

uint32_t _nl_get_ifid(const char *interface_name) {
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
  size_t n;
  int fd;
  size_t len = interface_name ? strlen(interface_name) + 1 : 0;
  uint8_t padding[RTA_ALIGNTO] = {0, 0, 0, 0};

  if (len == 0) {
    goto ERR_IF;
  }

  struct {
    struct nlmsghdr hdr;
    struct ifinfomsg payload;
  } msg = {//.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)),
           .hdr.nlmsg_type = RTM_GETLINK,
           .hdr.nlmsg_flags = FLAGS_GET,
           .payload.ifi_family = AF_UNSPEC,
           .payload.ifi_index = 0};
  struct rtattr a_ifname = {RTA_LENGTH(strlen(interface_name) + 1),
                            IFLA_IFNAME};

  struct iovec iov[] = {{&msg, sizeof(msg)},
                        {&a_ifname, sizeof(a_ifname)},
                        {(char *)interface_name, len},
                        {padding, RTA_SPACE(len) - RTA_LENGTH(len)}};
  msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));

  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR_SOCKET;
  }
  n = writev(fd, (struct iovec *)&iov, ARRAY_SIZE(iov));
  if (n == -1) {
    goto ERR_SEND;
  }
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR_RECV;
  }

  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR_NL;
    }
    return 0; /* Unexpected */
  }

  for (; NLMSG_OK(hdr, n); hdr = NLMSG_NEXT(hdr, n)) {
    struct ifinfomsg *payload = (struct ifinfomsg *)NLMSG_DATA(hdr);
    return payload->ifi_index;
  }
  return 0;

ERR_NL:
ERR_RECV:
ERR_SEND:
ERR_SOCKET:
ERR_IF:
  return 0;
}

int _nl_get_output_ifid(const char *ip_address, uint8_t family_address,
                        uint32_t *interface_id) {
  int rc;

  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
  size_t n;
  int fd;

  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR;
  }

  if (family_address == AF_INET6) {
    struct in6_addr addr;  // V6SPECIFIC

    struct {
      struct nlmsghdr hdr;
      struct rtmsg payload;
    } msg = {
        .hdr.nlmsg_type = RTM_GETROUTE,
        .hdr.nlmsg_flags = NLM_F_REQUEST,
        .hdr.nlmsg_seq = seq++,
        .payload.rtm_family = AF_INET6,
        .payload.rtm_dst_len = IPV6_ADDR_LEN_BITS,
        .payload.rtm_src_len = 0,
        .payload.rtm_tos = 0,
        .payload.rtm_table = RT_TABLE_UNSPEC,
        .payload.rtm_protocol = RTPROT_UNSPEC,
        .payload.rtm_scope = RT_SCOPE_UNIVERSE,
        .payload.rtm_type = RTN_UNSPEC,
        .payload.rtm_flags = 0  // RTM_F_NOTIFY in 'ip route get'
    };

    /* Convert the IP address to binary form */
    rc = inet_pton(AF_INET6, ip_address, &addr);
    if (rc <= 0) {
      goto ERR;
    }

    /* Set attribute = length/type/value */
    struct rtattr a_dst = {RTA_LENGTH(16), RTA_DST};
    struct iovec iov[] = {
        {&msg, sizeof(msg)},
        {&a_dst, sizeof(a_dst)},  // attribute
        {&addr, sizeof(addr)}     // value
    };
    msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));

    n = writev(fd, (struct iovec *)&iov, ARRAY_SIZE(iov));
    if (n == -1) {
      goto ERR;
    }
  } else if (family_address == AF_INET) {
    struct in_addr addr;

    struct {
      struct nlmsghdr hdr;
      struct rtmsg payload;
    } msg = {
        .hdr.nlmsg_type = RTM_GETROUTE,
        .hdr.nlmsg_flags = NLM_F_REQUEST,
        .hdr.nlmsg_seq = seq++,
        .payload.rtm_family = AF_INET,
        .payload.rtm_dst_len = IPV4_ADDR_LEN_BITS,
        .payload.rtm_src_len = 0,
        .payload.rtm_tos = 0,
        .payload.rtm_table = RT_TABLE_UNSPEC,
        .payload.rtm_protocol = RTPROT_UNSPEC,
        .payload.rtm_scope = RT_SCOPE_UNIVERSE,
        .payload.rtm_type = RTN_UNSPEC,
        .payload.rtm_flags = 0  // RTM_F_NOTIFY in 'ip route get'
    };

    /* Convert the IP address to binary form */
    rc = inet_pton(AF_INET, ip_address, &addr);
    if (rc <= 0) {
      goto ERR;
    }

    /* Set attribute = length/type/value */
    struct rtattr a_dst = {RTA_LENGTH(4), RTA_DST};
    struct iovec iov[] = {
        {&msg, sizeof(msg)},
        {&a_dst, sizeof(a_dst)},  // attribute
        {&addr, sizeof(addr)}     // value
    };
    msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));

    n = writev(fd, (struct iovec *)&iov, ARRAY_SIZE(iov));
    if (n == -1) {
      goto ERR;
    }
  } else {
    goto ERR;
  }

  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR;
  }

  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR;
    }
    return HICN_SOCKET_ERROR_UNEXPECTED; /* Unexpected */
  }

  for (; NLMSG_OK(hdr, n); hdr = NLMSG_NEXT(hdr, n)) {
    struct rtmsg *rtm = (struct rtmsg *)NLMSG_DATA(hdr);
    int attrlen = RTM_PAYLOAD(hdr);
    struct rtattr *rta;
    for (rta = RTM_RTA(rtm); RTA_OK(rta, attrlen);
         rta = RTA_NEXT(rta, attrlen)) {
      if (rta->rta_type == RTA_OIF) {
        *interface_id = *(uint32_t *)RTA_DATA(rta);
        return HICN_SOCKET_ERROR_NONE;
      }
    }
  }

  return HICN_SOCKET_ERROR_NONE;

ERR:
  return HICN_SOCKET_ERROR_UNSPEC;
}

int _nl_get_ip_addr(uint32_t interface_id, uint8_t address_family,
                    ip_prefix_t *prefix) {
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
  size_t n;
  int fd;

  struct {
    struct nlmsghdr hdr;
    struct ifaddrmsg payload;
  } msg = {.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifaddrmsg)),
           .hdr.nlmsg_type = RTM_GETADDR,
           .hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_ROOT,  // | NLM_F_MATCH,
           .payload.ifa_family = address_family,
           .payload.ifa_index = 0};

  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR_SOCKET;
  }

  n = send(fd, &msg, sizeof(msg), 0);
  if (n == -1) {
    goto ERR_SEND;
  }
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR_RECV;
  }

  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR_NL;
    }
    return -99; /* Unexpected */
  }

  for (; NLMSG_OK(hdr, n); hdr = NLMSG_NEXT(hdr, n)) {
    struct ifaddrmsg *payload = (struct ifaddrmsg *)NLMSG_DATA(hdr);

    if (address_family == AF_INET6) {
      if ((payload->ifa_index == interface_id) &&
          (payload->ifa_prefixlen < IPV6_ADDR_LEN * 8)) {
        memcpy(prefix->address.v6.buffer, RTA_DATA(payload + 1), IPV6_ADDR_LEN);
        prefix->family = AF_INET6;
        prefix->len = IPV6_ADDR_LEN_BITS;
        return HICN_SOCKET_ERROR_NONE;
      }
    } else if (address_family == AF_INET) {
      if ((payload->ifa_index == interface_id) &&
          (payload->ifa_prefixlen < IPV4_ADDR_LEN * 8)) {
        memcpy(prefix->address.v4.buffer, RTA_DATA(payload + 1), IPV4_ADDR_LEN);
        prefix->family = AF_INET;
        prefix->len = IPV4_ADDR_LEN_BITS;
        return HICN_SOCKET_ERROR_NONE;
      }
    } else {
      return -99;
    }
  }

ERR_NL:
ERR_RECV:
ERR_SEND:
ERR_SOCKET:
  return HICN_SOCKET_ERROR_UNSPEC;
}

int _nl_set_ip_addr(uint32_t interface_id, ip_prefix_t *prefix) {
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
  size_t n;
  int fd;

  struct {
    struct nlmsghdr hdr;
    struct ifaddrmsg payload;
  } msg = {
      .hdr.nlmsg_type = RTM_NEWADDR,
      .hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_MATCH | NLM_F_ATOMIC,
      .hdr.nlmsg_seq = seq++,
      .payload.ifa_family = prefix->family,
      .payload.ifa_prefixlen = prefix->len,
      .payload.ifa_flags = 0,
      .payload.ifa_scope = RT_SCOPE_UNIVERSE,
      .payload.ifa_index = interface_id};

  /* Set attributes = length/type/value */
  struct rtattr ifa_address = {RTA_LENGTH(ip_address_len(prefix->family)),
                               IFA_ADDRESS};
  const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
  if (!address)
      goto ERR_ADDRESS;
  const struct iovec iov[] = {
      {&msg, sizeof(msg)},
      {&ifa_address, sizeof(ifa_address)},
      {(void*)address, ip_address_len(prefix->family)},
  };
  msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));

  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR_SOCKET;
  }

  // hicn_packet_dump_iov(iov, ARRAY_SIZE(iov));

  n = writev(fd, (struct iovec *)&iov, ARRAY_SIZE(iov));
  if (n == -1) {
    goto ERR_SEND;
  }
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR_RECV;
  }

  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR_NL;
    }
  }

  return 0;

ERR_NL:
ERR_RECV:
ERR_SEND:
ERR_SOCKET:
ERR_ADDRESS:
  return -1;
}

int _nl_up_if(uint32_t interface_id) {
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
  size_t n;
  int fd;

  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR_SOCKET;
  }

  struct {
    struct nlmsghdr hdr;
    struct ifinfomsg payload;
  } msg = {
      .hdr.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)),
      .hdr.nlmsg_type = RTM_NEWLINK,
      .hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK,
      .payload.ifi_family = AF_UNSPEC,
      .payload.ifi_index = interface_id,
      .payload.ifi_flags = IFF_UP,
      .payload.ifi_change = IFF_UP  // 0xffffffff
  };

  n = send(fd, &msg, sizeof(msg), 0);
  if (n == -1) {
    goto ERR_SEND;
  }
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR_RECV;
  }

  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR_NL;
    }
    return 0;
  }

ERR_NL:
ERR_RECV:
ERR_SEND:
ERR_SOCKET:
  return -1;
}

struct route_info {
  char *dst_addr;
  char *src_addr;
  char *gateway;
  char ifName[IF_NAMESIZE];
};

/*
 * ip -6 route add PREFIX dev INTERFACE_NAME
 */
#if 0
int _nl_add_in_route(const char * prefix, const uint32_t interface_id)
{
    char buffer[BUFSIZE];
    struct nlmsghdr * hdr = (struct nlmsghdr *)buffer;
    size_t n;
    int fd;

    int pton_fd;
    unsigned char dst[sizeof(struct in6_addr)];
    char * p;
    char * eptr;
    char addr[strlen(prefix)];
    uint32_t dst_len;

    strncpy(addr, prefix, strlen(prefix));

    p = strchr(addr, '/');
    if (!p) {
        dst_len = IPV6_ADDR_LEN;
    } else {
        dst_len = strtoul(p + 1, &eptr, 10);
        if (dst_len > IPV6_ADDR_LEN * 8) {
            printf("E: Netmask > IPV6_ADDR_LEN");
            return -1;
        }
        *p = 0;
    }

    pton_fd = inet_pton(AF_INET6, addr, dst);
    if (pton_fd <= 0) {
        if (pton_fd == 0)
            ;//ERROR("Not in presentation format");
        else
            perror("inet_pton");
        return -2;
    }

    _nl_header(RTM_NEWROUTE, (uint8_t *)buffer, BUFSIZE, FLAGS_CREATE_MATCH);
    _nl_payload_route(RT_TABLE_MAIN, dst_len, (uint8_t *)buffer, BUFSIZE);

    addAttr(hdr, BUFSIZE, RTA_DST, dst, IPV6_ADDR_LEN);
    addAttr(hdr, BUFSIZE, RTA_OIF, (void*)&interface_id, sizeof(uint32_t));

    fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
    if (fd < 0) {
        goto ERR_SOCKET;
    }

    n = send(fd, buffer, hdr->nlmsg_len, 0);
    if (n == -1) {
        goto ERR_SEND;
    }
    n = recv(fd, buffer, BUFSIZE, 0);
    if (n == -1) {
        goto ERR_RECV;
    }

    if (hdr->nlmsg_type == NLMSG_ERROR) {
        struct nlmsgerr * err = (struct nlmsgerr *)NLMSG_DATA(hdr);
        if (err->error < 0) {
            errno = -err->error;
            goto ERR_NL;
        }
        return 0;
    }

ERR_NL:
ERR_RECV:
ERR_SEND:
ERR_SOCKET:
    return -1;

}
#endif

/*
 * ip -6 route add local default via GATEWAY_IP table TABLE_ID
 */
int _nl_add_out_route(const char *gateway, uint8_t address_family,
                      const uint8_t table_id, int default_route) {
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
  size_t n;
  int fd;

  int pton_fd;

  if (address_family == AF_INET) {
    struct in_addr gw;

    pton_fd = inet_pton(AF_INET, gateway, (struct in_addr *)&gw);
    if (pton_fd < 0) {
      return -1;
    }

    _nl_header(RTM_NEWROUTE, (uint8_t *)buffer, BUFSIZE,
               NLM_F_REQUEST | NLM_F_ACK | NLM_F_MATCH | NLM_F_ATOMIC);
    _nl_payload_route(table_id, address_family, 0, (uint8_t *)buffer, BUFSIZE);

    /* gw */
    addAttr(hdr, BUFSIZE, RTA_GATEWAY, &gw, sizeof(gw));

  } else if (address_family == AF_INET6) {
    struct in6_addr gw;

    pton_fd = inet_pton(AF_INET6, gateway, (struct in6_addr *)&gw);
    if (pton_fd < 0) {
      return -1;
    }

    _nl_header(RTM_NEWROUTE, (uint8_t *)buffer, BUFSIZE,
               NLM_F_REQUEST | NLM_F_ACK | NLM_F_MATCH | NLM_F_ATOMIC);
    _nl_payload_route(table_id, address_family, 0, (uint8_t *)buffer, BUFSIZE);

    /* gw */
    addAttr(hdr, BUFSIZE, RTA_GATEWAY, &gw, sizeof(gw));
    if (default_route != -1) {
      addAttr(hdr, BUFSIZE, RTA_OIF, &default_route, sizeof(default_route));
    }

  } else {
    return -1;
  }

  // For more than 255 tables
  // addAttr(msg, BUFSIZE, RTA_TABLE, &table_id, sizeof(uint32_t));

  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR_SOCKET;
  }

  n = send(fd, buffer, hdr->nlmsg_len, 0);
  if (n == -1) {
    goto ERR_SEND;
  }
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR_RECV;
  }

  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR_NL;
    }
    return 0;
  }

ERR_NL:
ERR_RECV:
ERR_SEND:
ERR_SOCKET:
  return -1;
}

/*
 * ip -6 route del local default via GATEWAY_IP table TABLE_ID
 */
int _nl_del_out_route(const char *gateway, const uint8_t address_family,
                      const uint8_t table_id) {
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
  size_t n;
  int fd;

  int pton_fd;

  if (address_family == AF_INET) {
    struct in_addr gw;

    pton_fd = inet_pton(AF_INET, gateway, (struct in_addr *)&gw);
    if (pton_fd < 0) {
      return -1;
    }

    _nl_header(RTM_DELROUTE, (uint8_t *)buffer, BUFSIZE,
               NLM_F_REQUEST | NLM_F_ACK | NLM_F_MATCH | NLM_F_ATOMIC);
    _nl_payload_route(table_id, address_family, 0, (uint8_t *)buffer, BUFSIZE);

    /* gw */
    addAttr(hdr, BUFSIZE, RTA_GATEWAY, &gw, sizeof(gw));

  } else if (address_family == AF_INET6) {
    struct in6_addr gw;

    pton_fd = inet_pton(AF_INET6, gateway, (struct in6_addr *)&gw);
    if (pton_fd < 0) {
      return -1;
    }

    _nl_header(RTM_DELROUTE, (uint8_t *)buffer, BUFSIZE,
               NLM_F_REQUEST | NLM_F_ACK | NLM_F_MATCH | NLM_F_ATOMIC);
    _nl_payload_route(table_id, address_family, 0, (uint8_t *)buffer, BUFSIZE);

    /* gw */
    addAttr(hdr, BUFSIZE, RTA_GATEWAY, &gw, sizeof(gw));

  } else {
    return -1;
  }

  // For more than 255 tables
  // addAttr(msg, BUFSIZE, RTA_TABLE, &table_id, sizeof(uint32_t));

  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR_SOCKET;
  }

  n = send(fd, buffer, hdr->nlmsg_len, 0);
  if (n == -1) {
    goto ERR_SEND;
  }
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR_RECV;
  }

  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR_NL;
    }
    return 0;
  }

ERR_NL:
ERR_RECV:
ERR_SEND:
ERR_SOCKET:
  return -1;
}

/*
 * ip route del 1:2::2 dev lo table local
 *
 */
int _nl_del_lo_route(const ip_prefix_t *prefix) {
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
  size_t n;
  int fd;

  struct {
    struct nlmsghdr hdr;
    struct rtmsg payload;
  } msg = {
      .hdr.nlmsg_type = RTM_DELROUTE,
      .hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK,
      .hdr.nlmsg_seq = seq++,
      .payload.rtm_family = prefix->family,
      .payload.rtm_dst_len = prefix->len,
      .payload.rtm_src_len = 0,
      .payload.rtm_tos = 0,
      .payload.rtm_table = RT_TABLE_LOCAL,
      .payload.rtm_protocol = RTPROT_UNSPEC,
      .payload.rtm_scope = RT_SCOPE_UNIVERSE,
      .payload.rtm_type = RTN_UNSPEC,
      .payload.rtm_flags = 0  // RTM_F_NOTIFY in 'ip route get'
  };

  /* Set attribute = length/type/value */
  uint32_t one = 1;
  struct rtattr a_dst = {RTA_LENGTH(ip_address_len(prefix->family)), RTA_DST};
  struct rtattr a_ifid_lo = {RTA_LENGTH(sizeof(uint32_t)), RTA_OIF};
  const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
  if (!address)
      goto ERR;
  const struct iovec iov[] = {
      {&msg, sizeof(msg)},
      /* Ip address */
      {&a_dst, sizeof(a_dst)},
      {(void*)address, ip_address_len(prefix->family)},
      /* Interface id */
      {&a_ifid_lo, sizeof(a_ifid_lo)},
      {&one, sizeof(one)}};
  msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));

  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR;
  }

  n = writev(fd, (struct iovec *)&iov, ARRAY_SIZE(iov));
  if (n == -1) {
    goto ERR;
  }
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR;
  }

  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR;
    }
    return 0;
  }

  return HICN_SOCKET_ERROR_NONE;
ERR:
  return HICN_SOCKET_ERROR_UNSPEC;
}

/*
 * ip -6 rule add iif INTERFACE_NAME lookup TABLE_ID
 */
int _nl_add_rule(const char *interface_name, uint8_t address_family,
                 const uint8_t table_id) {
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
  size_t n;
  int fd;

  _nl_header(RTM_NEWRULE, (uint8_t *)buffer, BUFSIZE, FLAGS_CREATE);
  _nl_payload_rule(table_id, address_family, (uint8_t *)buffer, BUFSIZE);

  addAttr(hdr, BUFSIZE, FRA_IIFNAME, (void *)interface_name,
          strlen(interface_name));

  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR_SOCKET;
  }

  n = send(fd, buffer, hdr->nlmsg_len, 0);
  if (n == -1) {
    goto ERR_SEND;
  }
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR_RECV;
  }

  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR_NL;
    }
    return 0;
  }

ERR_NL:
ERR_RECV:
ERR_SEND:
ERR_SOCKET:
  return -1;
}

/*
 * ip -6 rule del iif INTERFACE_NAME //lookup TABLE_ID
 */
int _nl_del_rule(const char *interface_name, uint8_t address_family,
                 const uint8_t table_id) {
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;
  size_t n;
  int fd;

  _nl_header(RTM_DELRULE, (uint8_t *)buffer, BUFSIZE, FLAGS_CREATE);
  _nl_payload_rule(table_id, address_family, (uint8_t *)buffer, BUFSIZE);

  addAttr(hdr, BUFSIZE, FRA_IIFNAME, (void *)interface_name,
          strlen(interface_name));

  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR_SOCKET;
  }

  n = send(fd, buffer, hdr->nlmsg_len, 0);
  if (n == -1) {
    goto ERR_SEND;
  }

  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR_RECV;
  }

  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR_NL;
    }
    return 0;
  }

ERR_NL:
ERR_RECV:
ERR_SEND:
ERR_SOCKET:
  return -1;
}

/*
 * ip -6 neigh add proxy 1:2::2 dev hicnc-cons-eth0 2>&1 | grep nei
 *
 */
int _nl_add_neigh_proxy(const ip_prefix_t *prefix,
                        const uint32_t interface_id) {
  /* Buffer for holding the response, with appropriate casting on the header */
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;

  /* Used for send and receive operations on netlink socket */
  int fd;
  size_t n;

  /* Packet header */
  struct {
    struct nlmsghdr hdr;
    struct ndmsg payload;
  } msg = {
      .hdr.nlmsg_type = RTM_NEWNEIGH,
      .hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_ACK | NLM_F_EXCL,
      .hdr.nlmsg_seq = seq++,
      .payload.ndm_family = prefix->family,
      .payload.ndm_ifindex = interface_id,
      .payload.ndm_state = NUD_PERMANENT,
      .payload.ndm_flags = NTF_PROXY,
  };

  /* Message attributes = length/type/value */
  struct rtattr a_dst = {RTA_LENGTH(ip_address_len(prefix->family)), NDA_DST};

  const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
  if (!address)
      goto ERR;

  /* Iovec describing the packets */
  const struct iovec iov[] = {
      {&msg, sizeof(msg)},
      /* Ip address */
      {&a_dst, sizeof(a_dst)},
      {(void*)address, ip_address_len(prefix->family)},
  };
  msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));

  /* Open netlink socket */
  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR;
  }

  /* Send packet */
  n = writev(fd, (struct iovec *)&iov, ARRAY_SIZE(iov));
  if (n == -1) {
    goto ERR;
  }

  /* Receive answer */
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR;
  }

  /* Parse answer */
  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR;
    }
  }

  return HICN_SOCKET_ERROR_NONE;
ERR:
  return HICN_SOCKET_ERROR_UNSPEC;
}

/* ip -6 route add 0:1::/64 dev hicn-if0 table 100 */
/* ip -6 route add 0:2::/64 dev hicn-if1 table 100 */
int _nl_add_in_route_table(const ip_prefix_t *prefix,
                           const uint32_t interface_id,
                           const uint8_t table_id) {
  /* Buffer for holding the response, with appropriate casting on the header */
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;

  /* Used for send and receive operations on netlink socket */
  int fd;
  size_t n;

  /* Packet header */
  struct {
    struct nlmsghdr hdr;
    struct rtmsg payload;
  } msg = {
      .hdr.nlmsg_type = RTM_NEWROUTE,
      .hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_ACK | NLM_F_EXCL,
      .hdr.nlmsg_seq = seq++,
      .payload.rtm_family = prefix->family,
      .payload.rtm_dst_len = prefix->len,
      .payload.rtm_src_len = 0,
      .payload.rtm_tos = 0,
      .payload.rtm_table = table_id, /* RT_TABLE_MAIN, etc. */
      .payload.rtm_protocol = RTPROT_BOOT,
      .payload.rtm_scope =
          prefix->family == AF_INET6 ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK,
      .payload.rtm_type = RTN_UNICAST,
      .payload.rtm_flags = 0,
  };

  /* Message attributes = length/type/value */
  struct rtattr a_dst = {RTA_LENGTH(ip_address_len(prefix->family)), RTA_DST};
  struct rtattr a_oif = {RTA_LENGTH(sizeof(uint32_t)), RTA_OIF};

  const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
  if (!address)
      goto ERR;

  /* Iovec describing the packets */
  const struct iovec iov[] = {
      {&msg, sizeof(msg)},
      /* Destination prefix / ip address */
      {&a_dst, sizeof(a_dst)},
      {(void*)address, ip_address_len(prefix->family)},
      /* Output interface */
      {&a_oif, sizeof(a_oif)},
      {(void *)&interface_id, sizeof(uint32_t)},
  };
  msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));

  /* Open netlink socket */
  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR;
  }

  /* Send packet */
  n = writev(fd, (struct iovec *)&iov, ARRAY_SIZE(iov));
  if (n == -1) {
    goto ERR;
  }

  /* Receive answer */
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR;
  }

  /* Parse answer */
  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR;
    }
  }

  return HICN_SOCKET_ERROR_NONE;
ERR:
  return HICN_SOCKET_ERROR_UNSPEC;
}

/* Additional helper functions */

int _nl_add_in_route_table_s(const char *prefix, const uint32_t interface_id,
                             const uint8_t table_id) {
  int rc;
  ip_prefix_t ip_address;

  rc = ip_prefix_pton(prefix, &ip_address);
  if (rc < 0) {
    return rc;
  }

  return _nl_add_in_route_table(&ip_address, interface_id, table_id);
}

int _nl_add_in_route_s(const char *prefix, const uint32_t interface_id) {
  return _nl_add_in_route_table_s(prefix, interface_id, RT_TABLE_MAIN);
}

/* ip -6 rule add from b001::/16 prio 0 table 100 */
int _nl_add_prio_rule(const ip_prefix_t *prefix, uint8_t address_family,
                      const uint32_t priority, const uint8_t table_id) {
  /* Buffer for holding the response, with appropriate casting on the header */
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;

  /* Used for send and receive operations on netlink socket */
  int fd;
  size_t n;

  /* Packet header */
  struct {
    struct nlmsghdr hdr;
    struct fib_rule_hdr payload;
  } msg = {
      .hdr.nlmsg_type = RTM_NEWRULE,
      .hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_ACK | NLM_F_EXCL,
      .hdr.nlmsg_seq = seq++,
      .payload.family = address_family,
      //.payload.dst_len = ,
      .payload.src_len = prefix ? prefix->len : 0,
      .payload.tos = 0,
      .payload.table = table_id,
      .payload.action = FR_ACT_TO_TBL,
      .payload.flags = NLM_F_REPLACE,  // 0
  };

  /* Open netlink socket */
  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR;
  }

  if (prefix) {
    /* Message attributes = length/type/value */
    struct rtattr a_src = {RTA_LENGTH(ip_address_len(prefix->family)), FRA_SRC};
    struct rtattr a_prio = {RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY};

    const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
    if (!address)
        goto ERR;
    /* Iovec describing the packets */
    const struct iovec iov[] = {
        {&msg, sizeof(msg)},
        /* Source prefix / prefix */
        {&a_src, sizeof(a_src)},
        {(void*)address, ip_address_len(prefix->family)},
        /* Priority */
        {&a_prio, sizeof(a_prio)},
        {(void *)&priority, sizeof(uint32_t)},
    };
    msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));

    /* Send packet */
    n = writev(fd, (struct iovec *)&iov, ARRAY_SIZE(iov));
    if (n == -1) {
      goto ERR;
    }
  } else {
    struct rtattr a_prio = {RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY};

    /* Iovec describing the packets */
    struct iovec iov[] = {
        {&msg, sizeof(msg)},
        /* Priority */
        {&a_prio, sizeof(a_prio)},
        {(void *)&priority, sizeof(uint32_t)},
    };
    msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));

    /* Send packet */
    n = writev(fd, (struct iovec *)&iov, ARRAY_SIZE(iov));
    if (n == -1) {
      goto ERR;
    }
  }

  /* Receive answer */
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR;
  }

  /* Parse answer */
  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0) {
      errno = -err->error;
      goto ERR;
    }
  }

  return HICN_SOCKET_ERROR_NONE;
ERR:
  return HICN_SOCKET_ERROR_UNSPEC;
}

int _nl_add_lo_prio_rule(const ip_prefix_t *prefix, uint8_t address_family,
                         const uint32_t priority) {
  return _nl_add_prio_rule(prefix, address_family, priority,
                           RT_TABLE_LOCAL);
}

/* ip -6 rule del from all prio 0 table local */
int _nl_del_prio_rule(const ip_prefix_t *prefix, uint8_t address_family,
                      const uint32_t priority, const uint8_t table_id) {
  /* Buffer for holding the response, with appropriate casting on the header */
  char buffer[BUFSIZE];
  struct nlmsghdr *hdr = (struct nlmsghdr *)buffer;

  /* Used for send and receive operations on netlink socket */
  int fd;
  size_t n;

  /* Packet header */
  struct {
    struct nlmsghdr hdr;
    struct fib_rule_hdr payload;
  } msg = {
      .hdr.nlmsg_type = RTM_DELRULE,
      .hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_ACK | NLM_F_EXCL,
      .hdr.nlmsg_seq = seq++,
      .payload.family = address_family,
      //.payload.dst_len = ,
      .payload.src_len = prefix ? prefix->len : 0,
      .payload.tos = 0,
      .payload.table = table_id,
      .payload.action = FR_ACT_TO_TBL,
      .payload.flags = NLM_F_REPLACE,  // 0
  };

  /* Open netlink socket */
  fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
  if (fd < 0) {
    goto ERR;
  }

  /* Message attributes = length/type/value */
  if (prefix) {
    struct rtattr a_src = {RTA_LENGTH(ip_address_len(prefix->family)), FRA_SRC};
    struct rtattr a_prio = {RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY};

    const void * address = ip_address_get_buffer(&prefix->address, prefix->family);
    if (!address)
        goto ERR;

    /* Iovec describing the packets */
    const struct iovec iov[] = {
        {&msg, sizeof(msg)},
        /* Source prefix / prefix */
        {&a_src, sizeof(a_src)},
        {(void*)address, ip_address_len(prefix->family)},
        /* Priority */
        {&a_prio, sizeof(a_prio)},
        {(void *)&priority, sizeof(uint32_t)},
    };
    msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));

    /* Send packet */
    n = writev(fd, (struct iovec *)&iov, ARRAY_SIZE(iov));
    if (n == -1) {
      goto ERR;
    }

  } else {
    struct rtattr a_prio = {RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY};

    /* Iovec describing the packets */
    struct iovec iov[] = {
        {&msg, sizeof(msg)},
        /* Priority */
        {&a_prio, sizeof(a_prio)},
        {(void *)&priority, sizeof(uint32_t)},
    };
    msg.hdr.nlmsg_len = iov_length(iov, ARRAY_SIZE(iov));

    /* Send packet */
    n = writev(fd, (struct iovec *)&iov, ARRAY_SIZE(iov));
    if (n == -1) {
      goto ERR;
    }
  }

  /* Receive answer */
  n = recv(fd, buffer, BUFSIZE, 0);
  if (n == -1) {
    goto ERR;
  }

  /* Parse answer */
  if (hdr->nlmsg_type == NLMSG_ERROR) {
    struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(hdr);
    if (err->error < 0 &&
        err->error != -2) {  //-2 is not such file or directory
      errno = -err->error;
      goto ERR;
    }
  }

  return HICN_SOCKET_ERROR_NONE;
ERR:
  return HICN_SOCKET_ERROR_UNSPEC;
}

int _nl_del_lo_prio_rule(const ip_prefix_t *ip_address, uint8_t address_family,
                         const uint32_t priority) {
  return _nl_del_prio_rule(ip_address, address_family, priority,
                           RT_TABLE_LOCAL);
}

/******************************************************************************/

// #include <net/if.h>
// duplicate declarations, in the meantime
#ifndef __ANDROID__
#define IF_NAMESIZE 16
#endif
//#define WITH_TUN_PI 1

#ifdef WITH_TUN_PI
#define TUN_FLAGS IFF_TUN
#else
#define TUN_FLAGS IFF_TUN | IFF_NO_PI
#endif

/*
 * Taken from Kernel Documentation/networking/tuntap.txt
 */

int tun_alloc(char *dev, int flags) {
  struct ifreq ifr;
  int fd, err;
  char *clonedev = "/dev/net/tun";

  /* Arguments taken by the function:
   *
   * char *dev: the name of an interface (or '\0'). MUST have enough
   *   space to hold the interface name if '\0' is passed
   * int flags: interface flags (eg, IFF_TUN etc.)
   */

  /* open the clone device */
  if ((fd = open(clonedev, O_RDWR)) < 0) {
    return fd;
  }

  /* preparation of the struct ifr, of type "struct ifreq" */
  memset(&ifr, 0, sizeof(ifr));

  ifr.ifr_flags = flags;

  if (*dev) {
    /* if a device name was specified, put it in the structure; otherwise,
     * the kernel will try to allocate the "next" device of the
     * specified type */
    strncpy(ifr.ifr_name, dev, IF_NAMESIZE - 1);
  }

  /* try to create the device */
  if ((err = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0) {
    close(fd);
    return err;
  }

  /* if the operation was successful, write back the name of the
   * interface to the variable "dev", so the caller can know
   * it. Note that the caller MUST reserve space in *dev (see calling
   * code below) */
  strcpy(dev, ifr.ifr_name);

  /* this is the special file descriptor that the caller will use to talk
   * with the virtual interface */
  return fd;
}

int linux_get_tun_name(const char *prefix, const char *identifier,
                       char *tun_name) {
  snprintf(tun_name, IF_NAMESIZE, "%s-%s", prefix,
           identifier ? identifier : "main");
  return 0;
}

int linux_tun_enable_offload(int fd) {
  unsigned int offload = 0, tso4 = 1, tso6 = 1, ecn = 1, ufo = 1, csum = 1;

  /* Check if our kernel supports TUNSETOFFLOAD */
  if (ioctl(fd, TUNSETOFFLOAD, 0) != 0 && errno == EINVAL) {
    goto ERR_TUN;
  }

  if (csum) {
    offload |= TUN_F_CSUM;
    if (tso4) offload |= TUN_F_TSO4;
    if (tso6) offload |= TUN_F_TSO6;
    if ((tso4 || tso6) && ecn) offload |= TUN_F_TSO_ECN;
    if (ufo) offload |= TUN_F_UFO;
  }

  if (ioctl(fd, TUNSETOFFLOAD, offload) != 0) {
    offload &= ~TUN_F_UFO;
    if (ioctl(fd, TUNSETOFFLOAD, offload) != 0) {
      fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n", strerror(errno));
    }
  }

  return 0;

ERR_TUN:
  return -1;
}

int linux_tun_create(char *name) {
  int fd, rc;

  fd = tun_alloc(name, TUN_FLAGS);
  if (fd < 0) {
    // ERROR("Error connecting to tun/tap interface %s!", name);
    errno = -2;
    goto ERR_TUN;
  }

  rc = linux_tun_enable_offload(fd);
  if (rc < 0) {
    // WARN("Could not enable hardware offload on TUN device");
  } else {
    // INFO("Enabled hardware offload on TUN device");
  }

  return fd;

ERR_TUN:
  return -1;
}

/*
 *
 * interface name can be NULL for all interfaces
 */
int linux_enable_proc(char *path) {
  int ret = 0;
  int fd;

  fd = open(path, O_WRONLY);
  if (fd < 0) {
    return -1;
  }

  if (write(fd, "1", 1) != 1) {
    ret = -2;
  }

  close(fd);
  return ret;
}

int linux_enable_v4_forwarding() {
  return linux_enable_proc("/proc/sys/net/ipv4/ip_forward");
}

int linux_enable_v6_forwarding(char *interface_name) {
  char path[PATH_MAX];
  snprintf(path, PATH_MAX, "/proc/sys/net/ipv6/conf/%s/forwarding",
           (interface_name) ? interface_name : "all");

  return linux_enable_proc(path);
}

int linux_enable_ndp_proxy() {
  return linux_enable_proc("/proc/sys/net/ipv6/conf/all/proxy_ndp");
}

const hicn_socket_ops_t ops = {
    .arch = "linux",
    .get_tun_name = linux_get_tun_name,
    .tun_create = linux_tun_create,
    .enable_v4_forwarding = linux_enable_v4_forwarding,
    .enable_v6_forwarding = linux_enable_v6_forwarding,
    .enable_ndp_proxy = linux_enable_ndp_proxy,
    .get_ifid = _nl_get_ifid,
    .get_output_ifid = _nl_get_output_ifid,
    .get_ip_addr = _nl_get_ip_addr,
    .set_ip_addr = _nl_set_ip_addr,
    .up_if = _nl_up_if,
    .add_in_route_table = _nl_add_in_route_table,
    .add_in_route_table_s = _nl_add_in_route_table_s,
    .add_in_route_s = _nl_add_in_route_s,
    .add_out_route = _nl_add_out_route,
    .del_out_route = _nl_del_out_route,
    .del_lo_route = _nl_del_lo_route,
    .add_rule = _nl_add_rule,
    .del_rule = _nl_del_rule,
    .add_neigh_proxy = _nl_add_neigh_proxy,
    .add_prio_rule = _nl_add_prio_rule,
    .add_lo_prio_rule = _nl_add_lo_prio_rule,
    .del_prio_rule = _nl_del_prio_rule,
    .del_lo_prio_rule = _nl_del_lo_prio_rule,
};