aboutsummaryrefslogtreecommitdiffstats
path: root/ctrl/facemgr/src/api.c
blob: 45273013457d1f9e2a2fd91f961b4c4d0a86f3f0 (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
/*
 * Copyright (c) 2017-2019 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * \file facemgr.c
 * \brief Implementation of Face manager library interface
 */

#ifdef __ANDROID__
//#define WITH_ANDROID_UTILITY
#endif /* __ANDROID__ */

#include <assert.h>
#include <stdio.h>
#include <string.h>

#include <hicn/facemgr/api.h>
#include <hicn/facemgr/cfg.h>
#include <hicn/facemgr/facelet.h>
#include <hicn/util/log.h>

#ifdef __APPLE__
#include "interfaces/network_framework/network_framework.h"
#endif /* __APPLE__ */

#ifdef __linux__
#include "interfaces/bonjour/bonjour.h"
#endif /* __linux__ */

#ifdef WITH_ANDROID_UTILITY
#include <hicn/android_utility/android_utility.h>
#endif /* WITH_ANDROID_UTILITY */

#include <hicn/ctrl/face.h>
#include <hicn/facemgr/facelet.h>
#include "common.h"
#include "facelet_array.h"
#include "interface.h"
#include "util/map.h"
#include "util/set.h"

#define RAND_NAME_LEN 5

#define DEFAULT_PORT 9695

#define DEFAULT_REATTEMPT_DELAY_MS 250
#define MAX_FDS 10

typedef struct {
    interface_t * interface;
    int fds[MAX_FDS];
    size_t num_fds;
} interface_map_data_t;

TYPEDEF_SET_H(facelet_set, facelet_t *);
TYPEDEF_SET(facelet_set, facelet_t *, facelet_cmp, facelet_snprintf);

TYPEDEF_MAP_H(interface_map, const char *, interface_map_data_t *);
TYPEDEF_MAP(interface_map, const char *, interface_map_data_t *, strcmp, string_snprintf, generic_snprintf);

TYPEDEF_MAP_H(bonjour_map, netdevice_t *, interface_t *);
TYPEDEF_MAP(bonjour_map, netdevice_t *, interface_t *, netdevice_cmp, generic_snprintf, generic_snprintf);

/* TODO automatically register interfaces */

#ifdef __APPLE__
extern interface_ops_t network_framework_ops;
#endif
#ifdef __linux__
extern interface_ops_t netlink_ops;
extern interface_ops_t bonjour_ops;
#endif
#ifdef WITH_ANDROID_UTILITY
extern interface_ops_t android_utility_ops;
#endif /* WITH_ANDROID_UTILITY */
#ifdef WITH_EXAMPLE_DUMMY
extern interface_ops_t dummy_ops;
#endif
#ifdef WITH_EXAMPLE_UPDOWN
extern interface_ops_t updown_ops;
#endif
extern interface_ops_t hicn_light_ops;


int
facemgr_overlay_snprintf(char * s, size_t size, const facemgr_overlay_t * overlay)
{
    return -1;
}

struct facemgr_s {
    /**************************************************/
    /* Configuration parameters (exposed through API) */

    facemgr_cfg_t * cfg;

#ifdef __ANDROID__
    /*
     * Those two pointers are needed to call java functions from the face
     * manager.
     */
    JavaVM *jvm;
#endif /* __ANDROID__ */

    /* Callback */
    facemgr_cb_t callback;
    void * callback_owner;

    /****************************/
    /* Internal data structures */

    /* Map of interfaces index by name */
    interface_map_t * interface_map;

    /* Faces under construction */
    facelet_set_t * facelet_cache;

    /* Static facelets */
    facelet_array_t * static_facelets;

    /********************************************************/
    /* Interfaces - Those should be fully replaced by a map */

    interface_t * hl;

#ifdef WITH_ANDROID_UTILITY
    interface_t * au; /* android_utility */
#endif /* WITH_ANDROID_UTILITY */

#ifdef __APPLE__
    interface_t * nf; /* network_framework */
#endif /* __APPLE__ */

#ifdef __linux__
    interface_t * nl; /* netlink */

    /*
     * We maintain a map of dynamically created bonjour interfaces, one for each
     * found netdevice
     */
    bonjour_map_t * bonjour_map;
#endif /* __linux__ */

#ifdef WITH_EXAMPLE_DUMMY
    interface_t * dummy;
#endif
#ifdef WITH_EXAMPLE_UPDOWN
    interface_t * updown;
#endif
    int timer_fd; /* Timer used for reattempts */
};

int
facemgr_initialize(facemgr_t * facemgr)
{
    facemgr->interface_map = interface_map_create();
    if (!facemgr->interface_map) {
        ERROR("[facemgr_initialize] Error creating interface map");
        goto ERR_INTERFACE_MAP;
    }

    facemgr->facelet_cache = facelet_set_create();
    if (!facemgr->facelet_cache) {
        ERROR("[facemgr_initialize] Error creating interface map");
        goto ERR_FACE_CACHE_PENDING;
    }

    facemgr->static_facelets = facelet_array_create();
    if (!facemgr->static_facelets) {
        ERROR("[facemgr_initialize] Error creating interface map");
        goto ERR_STATIC;
    }

#ifdef __linux__
    facemgr->bonjour_map = bonjour_map_create();
    if (!facemgr->bonjour_map) {
        ERROR("[facemgr_initialize] Error creating bonjour map");
        goto ERR_BJ;
    }
#endif /* __linux */

    facemgr->cfg = facemgr_cfg_create();
    if (!facemgr->cfg) {
        ERROR("[facemgr_initialize] Error creating face manager configuration");
        goto ERR_CFG;
    }

    facemgr->timer_fd = 0;

    return 0;

ERR_CFG:
#ifdef __linux__
    bonjour_map_free(facemgr->bonjour_map);
ERR_BJ:
#endif /* __linux__ */
    facelet_array_free(facemgr->static_facelets);
ERR_STATIC:
    facelet_set_free(facemgr->facelet_cache);
ERR_FACE_CACHE_PENDING:
    interface_map_free(facemgr->interface_map);
ERR_INTERFACE_MAP:
    return -1;
}

int
facemgr_finalize(facemgr_t * facemgr)
{
    int ret = 0;
    int rc;

    if (facemgr->timer_fd) {
        rc = facemgr->callback(facemgr->callback_owner,
                FACEMGR_CB_TYPE_UNREGISTER_TIMER, &facemgr->timer_fd);
        if (rc < 0) {
            ERROR("[facemgr_finalize] Error unregistering timer");
            ret = -1;
        }
        facemgr->timer_fd = 0;
    }

    interface_map_free(facemgr->interface_map);

    /* Free all facelets from cache */
    facelet_t ** facelet_array;
    int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
    if (n < 0) {
        ERROR("[facemgr_finalize] Could not retrieve facelets in cache");
    } else {
        for (unsigned i = 0; i < n; i++) {
            facelet_t * facelet = facelet_array[i];
            if (facelet_set_remove(facemgr->facelet_cache, facelet, NULL)) {
                ERROR("[facemgr_finalize] Could not purge facelet from cache");
            }
            facelet_free(facelet);
        }
        free(facelet_array);
    }

    facelet_set_free(facemgr->facelet_cache);

    /* Free all facelets from static array */
    for (unsigned i = 0; i < facelet_array_len(facemgr->static_facelets); i++) {
        facelet_t * facelet;
        if (facelet_array_get_index(facemgr->static_facelets, i, &facelet) < 0) {
            ERROR("[facemgr_cfg_finalize] Error getting facelet in array");
            continue;
        }
        if (facelet_array_remove_index(facemgr->static_facelets, i, NULL) < 0) {
            ERROR("[facemgr_finalize] Could not purge facelet from static array");
        }
        facelet_free(facelet);
    }

    facelet_array_free(facemgr->static_facelets);

#ifdef __linux__
    bonjour_map_free(facemgr->bonjour_map);
#endif /* __linux__ */

    interface_unregister_all();

    return ret;
}

AUTOGENERATE_CREATE_FREE(facemgr);

int
facemgr_set_config(facemgr_t * facemgr, facemgr_cfg_t * cfg)
{
    if (facemgr->cfg) {
        facemgr_cfg_free(facemgr->cfg);
    }
    facemgr->cfg = cfg;

    /* Populate the initial list of static facelets */
    facelet_t ** facelet_array;
    int n = facemgr_cfg_get_static_facelet_array(cfg, &facelet_array);
    if (n < 0) {
        ERROR("[facemgr_finalize] Could not retrieve static facelets from cfg");
    } else {
        for (unsigned i = 0; i < n; i++) {
            facelet_t * facelet = facelet_dup(facelet_array[i]);
            facelet_set_status(facelet, FACELET_STATUS_CLEAN);
            if (facelet_array_add(facemgr->static_facelets, facelet)) {
                ERROR("[facemgr_finalize] Could not add static facelet to face manager");
            }
        }
    }

    return 0;
}

int facemgr_reset_config(facemgr_t * facemgr)
{
    assert(facemgr->cfg);
    facemgr_cfg_free(facemgr->cfg);
    facemgr->cfg = facemgr_cfg_create();
    if (!facemgr->cfg)
        return -1;
    return 0;
}

facemgr_t *
facemgr_create_with_config(facemgr_cfg_t * cfg)
{
    facemgr_t * facemgr = facemgr_create();
    if (!facemgr)
        return NULL;
    int rc = facemgr_set_config(facemgr, cfg);
    if (rc < 0) {
        free(facemgr);
        return NULL;
    }
    return facemgr;
}

/*
 * \brief Heuristics to determine face type based on name, until a better
 * solution is found
 */
netdevice_type_t
facemgr_get_netdevice_type(const facemgr_t * facemgr, const char * interface_name)
{
    if (strncmp(interface_name, "lo", 2) == 0) {
        return NETDEVICE_TYPE_LOOPBACK;
    }
    if ((strncmp(interface_name, "eth", 3) == 0) ||
            (strncmp(interface_name, "en", 2) == 0)) {
        /* eth* en* enx* */
        return NETDEVICE_TYPE_WIRED;
    }
    if (strncmp(interface_name, "wl", 2) == 0) {
        /* wlan* wlp* wlx* */
        return NETDEVICE_TYPE_WIFI;
    }
    if (strncmp(interface_name, "rmnet_ipa", 9) == 0) {
        /* Qualcomm IPA driver */
        return NETDEVICE_TYPE_UNDEFINED;
    }
    if ((strncmp(interface_name, "rmnet", 5) == 0) ||
            (strncmp(interface_name, "rev_rmnet", 9) == 0) ||
            (strncmp(interface_name, "ccmni", 5) == 0)) {
        /*
         * rmnet* (Qualcomm) ccmni* (MediaTek)
         */
        return NETDEVICE_TYPE_CELLULAR;
    }
    /* usb0 might be cellular (eg Zenfone2) */
    /* what about tethering */
    /* tun* dummy* ... */
    /* bnet* pan* hci* for bluetooth */
    return NETDEVICE_TYPE_UNDEFINED;
}

int facemgr_callback(facemgr_t * facemgr, interface_cb_type_t type, void * data);

int
facemgr_create_interface(facemgr_t * facemgr, const char * name, const char * type, void * cfg, interface_t ** pinterface)
{
    char rand_name[RAND_NAME_LEN+1];
    interface_t * interface;

    if (!name) {
        /*
         * We can manipulate the name on the stack as it will be strdup'ed by
         * interface_create
         */
        rand_str(rand_name, RAND_NAME_LEN);
        name = rand_name;
    }

    INFO("Creating interface %s [%s]...", name, type);
    interface = interface_create(name, type);
    if (!interface) {
        ERROR("Error creating interface %s [%s]", name, type);
        goto ERR_CREATE;
    }
    interface_set_callback(interface, facemgr, facemgr_callback);

    interface_map_data_t * interface_map_data = malloc(sizeof(interface_map_data_t));
    if (!interface_map_data)
        goto ERR_MAP_DATA;

    *interface_map_data = (interface_map_data_t) {
        .interface = interface,
        .fds = {0},
        .num_fds = 0,
    };

    if (interface_map_add(facemgr->interface_map, interface->name, interface_map_data) < 0)
        goto ERR_MAP_ADD;

    /*
     * This should be called _after_ the interface_map is initialized otherwise
     * it will be impossible to register fds from *_initialize
     */
    if (interface_initialize(interface, cfg) < 0) {
        ERROR("[facemgr_create_interface] Error initializing interface");
        goto ERR_INIT;
    }

    DEBUG("Interface %s created successfully.", name);
    if (pinterface)
        *pinterface = interface;
    return 0;

ERR_MAP_ADD:
    free(interface_map_data);
ERR_MAP_DATA:
    interface_finalize(interface);
ERR_INIT:
    interface_free(interface);
ERR_CREATE:
    if (pinterface)
        *pinterface = NULL;
    return -1;
}

int
facemgr_delete_interface(facemgr_t * facemgr, interface_t * interface)
{
    int rc;

    interface_map_data_t * interface_map_data = NULL;

    DEBUG("Removing interface %s", interface->name);
    rc = interface_map_remove(facemgr->interface_map, interface->name, &interface_map_data);
    if (rc < 0)
        return -1;

    if (!interface_map_data)
        return -1;

    for (unsigned i = 0; i < interface_map_data->num_fds; i++) {
        int fd = interface_map_data->fds[i];
        fd_callback_data_t fd_callback_data = {
            .fd = fd,
            .owner = facemgr,
            .callback = NULL,
            .data = NULL,
        };
        facemgr->callback(facemgr->callback_owner, FACEMGR_CB_TYPE_UNREGISTER_FD, &fd_callback_data);
        if (rc < 0)
            WARN("[facemgr_delete_interface] Error unregistering fd %d for interface", fd);
    }

    free(interface_map_data);

    interface_finalize(interface);
    interface_free(interface);

    return 0;
}

#ifdef __linux__
int facemgr_query_bonjour(facemgr_t * facemgr, netdevice_t * netdevice)
{
    interface_t * bj = NULL;

    int rc = bonjour_map_get(facemgr->bonjour_map, netdevice, &bj);
    if (rc < 0)
        return rc;

    if (!bj) {
        /* Create a new bonjour interface */
        bonjour_cfg_t bj_cfg = {
            .netdevice = *netdevice,
        };
        rc = facemgr_create_interface(facemgr, NULL, "bonjour", &bj_cfg, &bj);
        if (rc < 0) {
            ERROR("Error creating 'Bonjour' interface for '%s'\n", netdevice->name);
            return -1;
        }
    }

    DEBUG("sending event to bonjour interface");

    /* Send an event to the interface (GET ?) */
    return interface_on_event(bj, NULL);
}
#endif /* __linux__ */

#ifdef WITH_ANDROID_UTILITY
int facemgr_query_android_utility(facemgr_t * facemgr, netdevice_t netdevice)
{
    /* Send an event to the interface */
    facelet_t * facelet = facelet_create();
    if (!facelet)
        goto ERR_MALLOC;

    int rc = facelet_set_netdevice(facelet, netdevice);
    if (rc < 0)
        goto ERR_ND;

    rc = interface_on_event(facemgr->au, facelet);
    if (rc < 0)
        goto ERR_EVENT;

    return 0;

ERR_EVENT:
ERR_ND:
    facelet_free(facelet);
ERR_MALLOC:
    return -1;
}
#endif /* WITH_ANDROID_UTILITY */


/**
 * \brief Performs a cache lookup to find matching facelets
 * \param [in] facelet_cache - Facelet cache on which to perform lookup
 * \param [in] facelet - Facelet to lookup
 * \param [out] cached_facelet - Pointer used to return a newly allocated
 *      facelet array corresponding to the result of the cache lookup.
 * \return The number of entries in the array in case of success (positive
 *      value), or -1 in case of error.
 */
int
facelet_cache_lookup(const facelet_set_t * facelet_cache, facelet_t * facelet,
        facelet_t ***cached_facelets)
{
#if 0 // key is no more sufficient now that we support multiple faces per interface
    /*
     * If the facelet is uniquely identified by its key, it is used to perform
     * an efficient lookup directly...
     */
    if (facelet_has_key(facelet)) {
        facelet_t * found = NULL;
        if (facelet_set_get(facelet_cache, facelet, &found) < 0) {
            ERROR("[facelet_cache_lookup] Error during cache lookup");
            return -1;
        }
        if (!found)
            return 0;
        *cached_facelets = malloc(sizeof(facelet_t*));
        *cached_facelets[0] = found;
        return 1;
    }
#endif

    /* ...otherwise, we iterate over the facelet
     * cache to find matching elements.
     */
    facelet_t ** facelet_array;
    int n = facelet_set_get_array(facelet_cache, &facelet_array);
    if (n < 0) {
        ERROR("[facelet_cache_lookup] Error during cache match");
        return -1;
    }
    *cached_facelets = malloc(n * sizeof(facelet_t*));

    int num_match = 0;
    for (unsigned i = 0; i < n; i++) {
        if (!facelet_match(facelet_array[i], facelet)) {
            continue;
        }
        (*cached_facelets)[num_match++] = facelet_array[i];
    }
    free(facelet_array);
    return num_match;
}


/**
 * \brief Checks whether the facelet satisfies face creation rules
 * \param [in] facemgr - Pointer to the face manager instance
 * \param [in] facelet - Pointer to the facelet to process
 * \return 0 in case of success, -2 if we don't have enough information to
 * decide, -3 if the face does not satisfy rules, and -1 in case of error
 */
int
facemgr_facelet_satisfy_rules(facemgr_t * facemgr, facelet_t * facelet)
{
    /* As key, netdevice and family should always be present */
    netdevice_t netdevice = NETDEVICE_EMPTY;
    int rc = facelet_get_netdevice(facelet, &netdevice);
    if (rc < 0) {
        ERROR("[facemgr_facelet_satisfy_rules] Error retrieving netdevice from facelet");
        return -1;
    }

    int family = AF_UNSPEC;
    if (facelet_has_family(facelet)) {
        if (facelet_get_family(facelet, &family) < 0) {
            ERROR("[facemgr_facelet_satisfy_rules] Error retrieving family from facelet");
            return -1;
        }
    }

    netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
#ifndef WITH_ANDROID_UTILITY
    /*
     * In addition to netdevice, netdevice_type should be present to correctly
     * apply rules
     */
    rc = facelet_get_netdevice_type(facelet, &netdevice_type);
    if (rc < 0) {
        ERROR("[facemgr_facelet_satisfy_rules] Error retrieving netdevice_type from facelet");
        return -2;
    }
#endif /* WITH_ANDROID_UTILITY */

    /* Ignore */
    bool ignore;
    if (facemgr_cfg_get_ignore(facemgr->cfg, &netdevice, netdevice_type,
                &ignore) < 0)
        return -1;
    if (ignore) {
        DEBUG("Ignored interface '%s/%s'...", netdevice.name,
                netdevice_type_str[netdevice_type]);
        return -3;
    }

    switch(family) {
        case AF_INET:
        {
            bool ipv4;
            if (facemgr_cfg_get_ipv4(facemgr->cfg, &netdevice, netdevice_type,
                        &ipv4) < 0)
                return -1;
            if (!ipv4) {
                DEBUG("Ignored IPv4 facelet...");
                return -3;
            }
            break;
        }

        case AF_INET6:
        {
            bool ipv6;
            if (facemgr_cfg_get_ipv6(facemgr->cfg, &netdevice, netdevice_type,
                        &ipv6) < 0)
                return -1;
            if (!ipv6) {
                DEBUG("Ignored IPv6 facelet...");
                return -3;
            }
            break;
        }

        default:
            DEBUG("Ignored facelet with unknown family");
            return -2;
    }

    return 0;
}

#ifdef WITH_ANDROID_UTILITY
/**
 * \brief Complements facelet information through Android Utility interface
 * \return 0 if request was successful, -1 in case of error, and -2 if the
 *      interface is not applicable
 *
 * This function returnds _after_ completion.
 */
int
facemgr_complement_facelet_au(facemgr_t * facemgr, facelet_t * facelet)
{

    if (facelet_has_netdevice_type(facelet))
        return -2;

    if (facelet_is_au_done(facelet))
        return -2;

    netdevice_t netdevice = NETDEVICE_EMPTY;
    int rc = facelet_get_netdevice(facelet, &netdevice);
    if (rc < 0) {
        ERROR("[facemgr_complement_facelet_bj] Error retrieving netdevice from facelet");
        return -1;
    }

    DEBUG("Querying android utility...");

    /* /!\ Synchronous code here /!\ */
    if (facemgr_query_android_utility(facemgr, netdevice) < 0) {
        return -1;
    }

    facelet_set_au_done(facelet);
    return 0;
}
#endif /* WITH_ANDROID_UTILITY */

#ifdef __linux__
/**
 * \brief Complements facelet information through Bonjour interface.
 * \return 0 if request was successful, -1 in case of error, and -2 if the
 *      interface is not applicable
 *
 * This function returnds _before_ completion as bonjour querying is
 * asynchronous.
 */
int
facemgr_complement_facelet_bj(facemgr_t * facemgr, facelet_t * facelet)
{
    netdevice_t netdevice = NETDEVICE_EMPTY;
    int rc = facelet_get_netdevice(facelet, &netdevice);
    if (rc < 0) {
        ERROR("[facemgr_complement_facelet_bj] Error retrieving netdevice from facelet");
        return -1;
    }

    netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
#ifndef WITH_ANDROID_UTILITY
    /*
     * In addition to netdevice, netdevice_type should be present to correctly
     * apply rules
     */
    rc = facelet_get_netdevice_type(facelet, &netdevice_type);
    if (rc < 0) {
        ERROR("[facemgr_complement_facelet_bj] Error retrieving netdevice_type from facelet");
        return -2;
    }
#endif /* WITH_ANDROID_UTILITY */

    bool discovery;
    if (facemgr_cfg_get_discovery(facemgr->cfg, &netdevice, netdevice_type,
                &discovery) < 0)
        return -2;

    DEBUG("Discovery: %s", discovery ? "ON" : "OFF");

    if (!discovery)
        return -2;

    facemgr_face_type_t face_type = FACEMGR_FACE_TYPE_UNDEFINED;
    if (facelet_get_face_type(facelet, &face_type) < 0) {
        ERROR("[facemgr_complement_facelet_bj] Error retrieving face type from facelet");
        return -1;
    }

    bool discovery_needed = (face_type.layer == FACE_TYPE_LAYER_4) &&
        ((!facelet_has_remote_addr(facelet)) || (!facelet_has_remote_port(facelet)));

    DEBUG("Discovery needed: %s", discovery ? "ON" : "OFF");

    if (!discovery_needed) {
        return -2;
    }

    if (!facelet_has_local_addr(facelet)) {
        DEBUG("No discovery possible without local address");
        return -2;
    }

    if (facelet_is_bj_done(facelet)) {
        DEBUG("Bonjour already queried");
        return -2;
    }

    facelet_set_bj_done(facelet);
    return facemgr_query_bonjour(facemgr, &netdevice);
}
#endif /* __linux__ */

/**
 * \brief Complements facelet information through Manual settings.
 * \return 0 if request was successful, -1 in case of error, and -2 if the
 *      interface is not applicable
 *
 * This function returnds _before_ completion as bonjour querying is
 * asynchronous.
 */
int
facemgr_complement_facelet_manual(facemgr_t * facemgr, facelet_t * facelet)
{

    netdevice_t netdevice = NETDEVICE_EMPTY;
    int rc = facelet_get_netdevice(facelet, &netdevice);
    if (rc < 0) {
        ERROR("[facemgr_complement_facelet_manual] Error retrieving netdevice from facelet");
        return -1;
    }

    netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
#ifndef WITH_ANDROID_UTILITY
    /*
     * In addition to netdevice, netdevice_type should be present to correctly
     * apply rules
     */
    rc = facelet_get_netdevice_type(facelet, &netdevice_type);
    if (rc < 0) {
        ERROR("[facemgr_complement_facelet_manual] Error retrieving netdevice_type from facelet");
        return -2;
    }
#endif /* WITH_ANDROID_UTILITY */

    int family = AF_UNSPEC;
    if (facelet_has_family(facelet)) {
        if (facelet_get_family(facelet, &family) < 0) {
            ERROR("[facemgr_complement_facelet_manual] Error retrieving family from facelet");
            return -1;
        }
    }

    /* Do not query manual is there is a change to go through bonjour */
    bool discovery;
    if (facemgr_cfg_get_discovery(facemgr->cfg, &netdevice, netdevice_type,
                &discovery) < 0)
        return -2;

    facemgr_face_type_t face_type = FACEMGR_FACE_TYPE_UNDEFINED;
    if (facelet_get_face_type(facelet, &face_type) < 0) {
        ERROR("[facemgr_complement_facelet_manual] Error retrieving face type from facelet");
        return -1;
    }

#if 0 /* Wrong if we need to complement local addr / port */
    bool discovery_needed = (face_type.layer == FACE_TYPE_LAYER_4) &&
        ((!facelet_has_remote_addr(facelet)) || (!facelet_has_remote_port(facelet)));

    if (!discovery_needed) {
        DEBUG("manual settings not considered as no discovery is needed");
        return -2;
    }
#endif

    if (discovery && !facelet_is_bj_done(facelet)) {
        DEBUG("manual settings not considered as discovery is enabled and Bonjour has not yet been done");
        return -2;
    }

    DEBUG("Applying manual settings...");
    /*
     * Manual overlay specification (remote addr/port)
     * We never override a result we have obtained through bonjour
     */
    if (!facelet_has_remote_addr(facelet)) {
        ip_address_t remote_addr;
        if (facemgr_cfg_get_overlay_remote_addr(facemgr->cfg,
                &netdevice, netdevice_type, family, &remote_addr) < 0) {
            ERROR("[facemgr_complement_facelet_manual] Error getting remote addr information from cfg");
            return -1;
        }
        if (ip_address_empty(&remote_addr)) {
            ERROR("[facemgr_complement_facelet_manual] Got empty remote addr information from cfg");
        } else {
            DEBUG(" - remote address");
            facelet_set_remote_addr(facelet, remote_addr);
        }
    }

    if (!facelet_has_remote_port(facelet)) {
        uint16_t remote_port;
        int rc = facemgr_cfg_get_overlay_remote_port(facemgr->cfg,
                &netdevice, netdevice_type, family, &remote_port);
        if (rc < 0) {
            ERROR("[facemgr_complement_facelet_manual] Error getting remote port information from cfg");
            return -1;
        }
        DEBUG(" - remote port");
        facelet_set_remote_port(facelet, remote_port);
    }

    /*
     * Complementing local addr/port XXX this should be done somewhere
     * else : manual settings have the lowest priority
     *
     * Local IP address is specific as it allows to override the source
     * address just before creating the face... we would need to check
     * whether this is an address that belong to us... it might be used
     * to arbitrate amongst several IP addresses instead...
     */
    ip_address_t local_addr;
    if (facemgr_cfg_get_overlay_local_addr(facemgr->cfg, &netdevice,
            netdevice_type, family, &local_addr) < 0) {
        ERROR("[facemgr_complement_facelet_manual] Error getting local addr information from cfg");
        return -1;
    }
    if (ip_address_empty(&local_addr)) {
        ERROR("[facemgr_complement_facelet_manual] Got empty local addr information from cfg");
    } else {
        DEBUG(" - local addres");
        facelet_set_local_addr(facelet, local_addr);
    }

    /* Sets a default local port, so far nobody sets it */
    uint16_t local_port;
    if (facemgr_cfg_get_overlay_local_port(facemgr->cfg,
            &netdevice, netdevice_type, family, &local_port) < 0) {
        ERROR("[facemgr_complement_facelet_manual] Error getting local port information from cfg");
        return -1;
    }
    DEBUG(" - local port");
    facelet_set_local_port(facelet, local_port);
    return 0;
}

int
facemgr_complement_facelet(facemgr_t * facemgr, facelet_t * facelet)
{
    int rc;

    if (!facelet_has_key(facelet))
        return -2;

#ifdef WITH_ANDROID_UTILITY
    rc = facemgr_complement_facelet_au(facemgr, facelet);
    if (rc != -2)
        return rc;
#endif /* WITH_ANDROID_UTILITY */

#if 0
    if (!facelet_has_netdevice_type(facelet)) {
        netdevice_t netdevice = NETDEVICE_EMPTY;
        rc = facelet_get_netdevice(facelet, &netdevice);
        if (rc < 0) {
            ERROR("[facemgr_complement_facelet] Error retrieving netdevice from facelet");
            return -1;
        }
        facelet_set_netdevice_type(facelet, facemgr_get_netdevice_type(facemgr, netdevice.name));
    }
#endif

    /* We continue only if the current call was not applicable. In the current
     * setting we have no interface that can be requested in parallel, and no
     * need to. This might evolve in future releases.
     */

#ifdef __linux__
    rc = facemgr_complement_facelet_bj(facemgr, facelet);
    if (rc != -2)
        return rc;
#endif /* __linux__ */

    DEBUG("Complement manual");

    rc = facemgr_complement_facelet_manual(facemgr, facelet);
    if (rc != -2)
        return rc;

    INFO("[facemgr_complement_facelet] No more interfaces to query... incomplete face");
    return 0;
}

int facemgr_assign_face_type(facemgr_t * facemgr, facelet_t * facelet)
{
    /* As key, netdevice and family should always be present */
    netdevice_t netdevice = NETDEVICE_EMPTY;
    int rc = facelet_get_netdevice(facelet, &netdevice);
    if (rc < 0) {
        ERROR("[facemgr_facelet_satisfy_rules] Error retrieving netdevice from facelet");
        return -1;
    }

    netdevice_type_t netdevice_type = NETDEVICE_TYPE_UNDEFINED;
#ifndef WITH_ANDROID_UTILITY
    /*
     * In addition to netdevice, netdevice_type should be present to correctly
     * apply rules
     */
    rc = facelet_get_netdevice_type(facelet, &netdevice_type);
    if (rc < 0) {
        ERROR("[facemgr_facelet_satisfy_rules] Error retrieving netdevice_type from facelet");
        return -2;
    }
#endif /* WITH_ANDROID_UTILITY */

    facemgr_face_type_t face_type = FACEMGR_FACE_TYPE_UNDEFINED;
    if (facemgr_cfg_get_face_type(facemgr->cfg, &netdevice, netdevice_type, &face_type) < 0)
        return rc;
    facelet_set_face_type(facelet, face_type);
    return 0;
}

/*
 * This function performs one step of the state machine associated to the
 * facelet, from initial creation, to synchronization with the forwarder.
 *
 * We assume the facelet is already present in the cache
 */
int
facemgr_process_facelet(facemgr_t * facemgr, facelet_t * facelet)
{
    int rc;

    switch(facelet_get_status(facelet)) {
        case FACELET_STATUS_UNCERTAIN:
            /*
             * All new faces are marked UNCERTAIN. We need to check whether we
             * have sufficient information to check rules, if not proceed,
             * otherwise possibly mark the face as IGNORED. Otherwise, we verify
             * the completeness of the information we have, and continue towards
             * being able to mark the face as CREATE.
             */
            rc = facemgr_facelet_satisfy_rules(facemgr, facelet);
            switch(rc) {
                case -3:
                    /* Does not satisfy rules */
                    facelet_set_status(facelet, FACELET_STATUS_IGNORED);
                    return 0;

                case -2:
                    /* Not enough information: AU in fact */
                    if (facemgr_complement_facelet(facemgr, facelet) < 0) {
                        ERROR("[facemgr_process_facelet] Error while attempting to complement face for fields required by face creation");
                        goto ERR;
                    }
                    return 0;

                case 0:
                    /* Ok pass rules */
                    break;

                default:
                    /* -1 - Error */
                    goto ERR;
            }

            if (facemgr_assign_face_type(facemgr, facelet) < 0) {
                ERROR("[facemgr_process_facelet] Could not assign face type");
                goto ERR;
            }
            facelet_set_status(facelet, FACELET_STATUS_INCOMPLETE);
            /* Continue in case facelet satisfies rules */

        case FACELET_STATUS_INCOMPLETE:
            if (!facelet_validate_face(facelet)) {
                /* We need additional information */
                if (facemgr_complement_facelet(facemgr, facelet) < 0) {
                    ERROR("[facemgr_process_facelet] Error while attempting to complement face for fields required by face creation");
                    goto ERR;
                }
            }
            if (!facelet_validate_face(facelet))
                return 0;

            facelet_set_status(facelet, FACELET_STATUS_CREATE);
            /* Continue in case we need to proceed to creation */

        case FACELET_STATUS_CREATE:
            facelet_set_event(facelet, FACELET_EVENT_CREATE);
            if (interface_on_event(facemgr->hl, facelet) < 0) {
                ERROR("[facemgr_process_facelet] Failed to create face");
                goto ERR;
            }

            /* This works assuming the call to hicn-light is blocking */
            facelet_set_status(facelet, FACELET_STATUS_CLEAN);
            break;


        case FACELET_STATUS_UPDATE:
            facelet_set_event(facelet, FACELET_EVENT_UPDATE);
            if (interface_on_event(facemgr->hl, facelet) < 0) {
                ERROR("[facemgr_process_facelet] Failed to update face");
                goto ERR;
            }

            /* This works assuming the call to hicn-light is blocking */
            facelet_set_status(facelet, FACELET_STATUS_CLEAN);
            break;

        case FACELET_STATUS_DELETE:
            facelet_set_event(facelet, FACELET_EVENT_DELETE);
            if (interface_on_event(facemgr->hl, facelet) < 0) {
                ERROR("[facemgr_process_facelet] Failed to delete face");
                goto ERR;
            }

            /* This works assuming the call to hicn-light is blocking */
            DEBUG("[facemgr_process_facelet] Cleaning cached data");
            facelet_unset_local_addr(facelet);
            facelet_unset_local_port(facelet);
            facelet_unset_remote_addr(facelet);
            facelet_unset_remote_port(facelet);
            facelet_unset_bj_done(facelet);
#ifdef WITH_ANDROID_UTILITY
            facelet_unset_au_done(facelet);
#endif /* WITH_ANDROID_UTILITY */

            facelet_set_status(facelet, FACELET_STATUS_DELETED);
            break;

        case FACELET_STATUS_CLEAN:
        case FACELET_STATUS_IGNORED:
        case FACELET_STATUS_DELETED:
            /* Nothing to do */
            break;

        case FACELET_STATUS_UNDEFINED:
        case FACELET_STATUS_N:
            ERROR("[facemgr_process_facelet] Unexpected facelet status");
            goto ERR;
    }

    facelet_set_status_error(facelet, false);
    return 0;

ERR:
    facelet_set_status_error(facelet, true);
    return -1;
}

int
facemgr_reattempt_timeout(facemgr_t * facemgr, int fd, void * data)
{
    bool has_error = false;

    assert(data == NULL);

    /* Free all facelets from cache */
    facelet_t ** facelet_array;
    int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
    if (n < 0) {
        ERROR("[facemgr_reattempt_timeout] Could not retrieve facelets in cache");
    } else {
        for (unsigned i = 0; i < n; i++) {
            facelet_t * facelet = facelet_array[i];

            if (!facelet_get_status_error(facelet))
                continue;

            char buf[MAXSZ_FACELET];
            facelet_snprintf(buf, MAXSZ_FACELET, facelet);
            DEBUG("Reattempt to process failed facelet %s", buf);
            if (facemgr_process_facelet(facemgr, facelet) < 0) {
                ERROR("[facemgr_reattempt_timeout] Error processing facelet");
                has_error = true;
                continue;
            }
            facelet_set_status_error(facelet, false);
        }
        free(facelet_array);
    }

    if (has_error)
        return 0;

    DEBUG("Cancelling timer");
    if (facemgr->callback(facemgr->callback_owner,
            FACEMGR_CB_TYPE_UNREGISTER_TIMER, &facemgr->timer_fd) < 0) {
        ERROR("[facemgr_reattempt_timeout] Error unregistering reattempt timer");
        return -1;
    }
    facemgr->timer_fd = 0;
    return 0;
}

int
facemgr_start_reattempts(facemgr_t * facemgr)
{
    if (facemgr->timer_fd > 0)
        return 0;

    timer_callback_data_t timer_callback = {
        .delay_ms = DEFAULT_REATTEMPT_DELAY_MS,
        .owner = facemgr,
        .callback = (fd_callback_t)facemgr_reattempt_timeout,
        .data = NULL,
    };
    facemgr->timer_fd = facemgr->callback(facemgr->callback_owner,
            FACEMGR_CB_TYPE_REGISTER_TIMER, &timer_callback);
    return (facemgr->timer_fd > 0);
}

/**
 * \brief Process facelet CREATE event
 * \param [in] facemgr - Pointer to the face manager instance
 * \param [in] facelet - Pointer to the facelet event to process
 * \return 0 if everything went correctly, or -1 in case of error.
 *         -2 means we ignored the face purposedly
 */
int
facemgr_process_facelet_create(facemgr_t * facemgr, facelet_t * facelet)
{
    switch(facelet_get_status(facelet)) {
        case FACELET_STATUS_UNCERTAIN:
        case FACELET_STATUS_INCOMPLETE:
        case FACELET_STATUS_CREATE:
            /* No change */
            break;
        case FACELET_STATUS_UPDATE:
        case FACELET_STATUS_DELETE:
            /*
             * Unlikely. The face had been created and is planned to
             * be deleted. Schedule for creation (we should have all
             * needed information), but make sure to handle errors
             * correctly if the face is still present.
             * TODO What if some fields have been updated ?
             */
            facelet_set_status(facelet, FACELET_STATUS_CREATE);
            break;
        case FACELET_STATUS_CLEAN:
        case FACELET_STATUS_IGNORED:
            /*
             * We should have nothing to do unless some fields have
             * been updated.
             */
            break;

        case FACELET_STATUS_DELETED:
            /*
             * Unless rules have changed, we only need to recover
             * missing information, and proceed to face creation.
             * Rule changes should be handled separately.
             */
            facelet_set_status(facelet, FACELET_STATUS_INCOMPLETE);
            break;
        case FACELET_STATUS_UNDEFINED:
        case FACELET_STATUS_N:
            ERROR("[facemgr_process_facelet_create] Unexpected facelet status");
            return -1;
    }

    if (facemgr_process_facelet(facemgr, facelet) < 0) {
        ERROR("[facemgr_process_facelet_create] Error processing facelet");
        return -1;
    }

    return 0;
}

/**
 * \brief Process facelet GET event
 * \param [in] facemgr - Pointer to the face manager instance
 * \param [in] facelet - Pointer to the facelet event to process
 * \return 0 if everything went correctly, or -1 in case of error.
 *         -2 means we ignored the face purposedly
 */
int
facemgr_process_facelet_get(facemgr_t * facemgr, facelet_t * facelet)
{
    if (facelet_has_netdevice(facelet)) {
        netdevice_t netdevice;
        if (facelet_get_netdevice(facelet, &netdevice) < 0)
            return -1;
        if (!IS_VALID_NETDEVICE(netdevice))
            return -2;
        facelet_set_status(facelet, FACELET_STATUS_CLEAN);
        return facelet_set_add(facemgr->facelet_cache, facelet);
    }
    return -2;
}

/**
 * \brief Process facelet UPDATE event
 * \param [in] facemgr - Pointer to the face manager instance
 * \param [in] facelet - Pointer to the facelet event to process
 * \return 0 if everything went correctly, or -1 in case of error.
 *         -2 means we ignored the face purposedly
 */
int
facemgr_process_facelet_update(facemgr_t * facemgr, facelet_t * facelet)
{
    switch(facelet_get_status(facelet)) {
        case FACELET_STATUS_UNCERTAIN:
        case FACELET_STATUS_INCOMPLETE:
        case FACELET_STATUS_CREATE:
        case FACELET_STATUS_UPDATE:
            /* No change */
            break;
        case FACELET_STATUS_CLEAN:
            facelet_set_status(facelet, FACELET_STATUS_UPDATE);
            break;
        case FACELET_STATUS_DELETE:
        case FACELET_STATUS_DELETED:
        case FACELET_STATUS_IGNORED:
            /* Reconsider face creation in light of new information */
            facelet_set_status(facelet, FACELET_STATUS_UNCERTAIN);
            break;
        case FACELET_STATUS_UNDEFINED:
        case FACELET_STATUS_N:
            ERROR("[facemgr_process_facelet_update] Unexpected facelet status");
            return -1;
    }

    if (facemgr_process_facelet(facemgr, facelet) < 0) {
        ERROR("[facemgr_process_facelet_update] Error processing facelet");
        return -1;
    }

    return 0;
}

/**
 * \brief Process facelet DELETE event
 * \param [in] facemgr - Pointer to the face manager instance
 * \param [in] facelet - Pointer to the facelet event to process
 * \return 0 if everything went correctly, or -1 in case of error.
 *         -2 means we ignored the face purposedly
 */
int
facemgr_process_facelet_delete(facemgr_t * facemgr, facelet_t * facelet)
{
    switch(facelet_get_status(facelet)) {
        case FACELET_STATUS_UNCERTAIN:
        case FACELET_STATUS_INCOMPLETE:
        case FACELET_STATUS_CREATE:
            facelet_unset_local_addr(facelet);
            facelet_unset_local_port(facelet);
            facelet_unset_remote_addr(facelet);
            facelet_unset_remote_port(facelet);
            facelet_unset_bj_done(facelet);
#ifdef WITH_ANDROID_UTILITY
            facelet_unset_au_done(facelet);
#endif /* WITH_ANDROID_UTILITY */
            facelet_set_status(facelet, FACELET_STATUS_DELETED);
            break;
        case FACELET_STATUS_UPDATE:
        case FACELET_STATUS_CLEAN:
            facelet_set_status(facelet, FACELET_STATUS_DELETE);
            break;
        case FACELET_STATUS_DELETE:
        case FACELET_STATUS_IGNORED:
        case FACELET_STATUS_DELETED:
            /* Nothing to do */
            DEBUG("%s\n", facelet_status_str[facelet_get_status(facelet)]);
            break;
        case FACELET_STATUS_UNDEFINED:
        case FACELET_STATUS_N:
            ERROR("[facemgr_process_facelet_delete] Unexpected facelet status");
            return -1;
    }

    if (facemgr_process_facelet(facemgr, facelet) < 0) {
        ERROR("[facemgr_process_facelet_delete] Error processing facelet");
        return -1;
    }

    return 0;
}

int facemgr_process_facelet_first_time(facemgr_t * facemgr, facelet_t * facelet)
{
    facelet_set_status(facelet, FACELET_STATUS_UNCERTAIN);

    if (facelet_set_add(facemgr->facelet_cache, facelet) < 0) {
        ERROR("[facemgr_process_facelet_first_time] Error adding facelet to cache");
        goto ERR_CACHE;
    }

    if (facemgr_process_facelet_create(facemgr, facelet) < 0) {
        ERROR("[facemgr_process_facelet_first_time] Error processing facelet CREATE event");
        goto ERR_CREATE;
    }

    return 0;

ERR_CREATE:
    if (facelet_set_remove(facemgr->facelet_cache, facelet, NULL) < 0) {
        ERROR("[facemgr_process_facelet_first_time] Error removing failed facelet from cache");
    }
ERR_CACHE:
    return -1;
}

/**
 * \brief Process incoming events from interfaces
 *
 * Implementation notes:
 *  - Any event or timeout due to an interface triggers either a local cache
 *  update, as well a face operations needed to resync the state.
 */
int
facemgr_on_event(facemgr_t * facemgr, facelet_t * facelet_in)
{
    bool remove_facelet = true;
    int ret = 0;
    int rc;
    assert(facelet_in);

    char facelet_s[MAXSZ_FACELET];
    facelet_snprintf(facelet_s, MAXSZ_FACELET, facelet_in);
    DEBUG("EVENT %s", facelet_s);

    facelet_t ** cached_facelets = NULL;
    int n = facelet_cache_lookup(facemgr->facelet_cache, facelet_in, &cached_facelets);
    if (n < 0) {
        ERROR("[facemgr_on_event] Error during cache lookup");
        free(facelet_in);
        return -1;
    }
    if (n == 0) {
        /* This is a new facelet...  we expect a CREATE event. */
        switch(facelet_get_event(facelet_in)) {
            case FACELET_EVENT_CREATE:
            {
                /*
                 * This is the first time we hear about a facelet, it will
                 * likely not have an address family
                 *
                 * Assumption: we should always see the link before the address
                 * assignment
                 */
                assert(!facelet_has_family(facelet_in));

                if (!facelet_has_netdevice_type(facelet_in)) {
                    netdevice_t netdevice = NETDEVICE_EMPTY;
                    rc = facelet_get_netdevice(facelet_in, &netdevice);
                    if (rc < 0) {
                        ERROR("[facemgr_complement_facelet] Error retrieving netdevice from facelet");
                        return -1;
                    }
                    facelet_set_netdevice_type(facelet_in, facemgr_get_netdevice_type(facemgr, netdevice.name));
                }

                /* Create default v4 and v6 facelets */
                facelet_t * facelet_v4 = facelet_dup(facelet_in);
                if (!facelet_v4) {
                    ERROR("[facemgr_on_event] Error allocating default IPv4 face");
                    facelet_free(facelet_v4);
                } else {
                    facelet_set_family(facelet_v4, AF_INET);
                    facelet_set_status(facelet_v4, FACELET_STATUS_CLEAN);
                    if (facemgr_process_facelet_first_time(facemgr, facelet_v4) < 0) {
                        ERROR("[facemgr_on_event] Error creating default IPv4 face");
                        facelet_free(facelet_v4);
                    }
                }

                facelet_t * facelet_v6 = facelet_dup(facelet_in);
                if (!facelet_v6) {
                    ERROR("[facemgr_on_event] Error allocating default IPv6 face");
                    facelet_free(facelet_v4);
                } else {
                    facelet_set_family(facelet_v6, AF_INET6);
                    facelet_set_status(facelet_v6, FACELET_STATUS_CLEAN);
                    if (facemgr_process_facelet_first_time(facemgr, facelet_v6) < 0) {
                        ERROR("[facemgr_on_event] Error creating default IPv6 face");
                        facelet_free(facelet_v6);
                    }
                }

                /* Create additional connections
                 *
                 * This is where we spawn multiple facelets based on the
                 * configured "static routes" in addition to the default
                 * routes managed by the face manager.
                 */
                for (unsigned i = 0; i < facelet_array_len(facemgr->static_facelets); i++) {
                    facelet_t * static_facelet;
                    if (facelet_array_get_index(facemgr->static_facelets, i, &static_facelet) < 0) {
                        ERROR("[facemgr_on_event] Error getting static facelet");
                        goto ERR;
                    }

                    /*
                     * We don't enforce any present or absent fields. A match
                     * operation will be performed deciding whether to create
                     * the facelet (if it bring additional information to the
                     * ingress one) or not.
                     */
                    /* We try to apply static_facelet over facelet_in */
                    if (!facelet_match(facelet_in, static_facelet)) {
                        continue;
                    }

                    facelet_t * facelet_new = facelet_dup(facelet_in);
                    if (!facelet_new) {
                        ERROR("[facemgr_on_event] Error allocating static facelet");
                        goto ERR;
                    } else {
                        if (facelet_merge(facelet_new, static_facelet) < 0) {
                            ERROR("[facemgr_on_event] Error merging facelets");
                            continue;
                        }
                        /* The id must be different than 0 */
                        facelet_set_id(facelet_new, i+1);
                        facelet_set_status(facelet_new, FACELET_STATUS_CLEAN);

                        char buf[MAXSZ_FACELET];
                        facelet_snprintf(buf, MAXSZ_FACELET, facelet_new);
                        if (facemgr_process_facelet_first_time(facemgr, facelet_new) < 0) {
                            ERROR("[facemgr_on_event] Error creating default IPv6 face");
                            facelet_free(facelet_v6);
                        }
                    }
                }

                /*
                 * We always remove the original facelet here, no need to
                 * preserve it
                 */
                break;
            }

            case FACELET_EVENT_GET:
                /* Insert new facelet in cached */
                rc = facemgr_process_facelet_get(facemgr, facelet_in);
                if (rc == 0)
                    remove_facelet = false;
                if (rc == -1) {
                    ERROR("[facemgr_on_event] Error processing GET event");
                    goto ERR;
                }
                break;

            case FACELET_EVENT_UPDATE:
                /* Might be because we previously ignored the facelet... */
                //ERROR("[facemgr_on_event] Unexpected UPDATE... face does not exist");
                //goto ERR;
                INFO("Ignored UPDATE for non-existing face");
                break;

            case FACELET_EVENT_DELETE:
                ERROR("[facemgr_on_event] Unexpected DELETE... face does not exist");
                goto ERR;

            case FACELET_EVENT_UNDEFINED:
                ERROR("[facemgr_on_event] Unexpected UNDEFINED event.");
                goto ERR;

            default: /* XXX Some events should be deprecated */
                ERROR("[facemgr_on_event] Deprecated event");
                goto ERR;
        }
        goto DUMP_CACHE;
    }

    /*
     * From now on, it should not make any difference whether we have one or
     * more facelet.
     */
    for (unsigned i = 0; i < n; i ++) {
        /*
         * We merge each cached facelet with incoming one, and perform state
         * reconciliation by sending appropriate updates to the forwarder
         */
        facelet_t * facelet = cached_facelets[i];
        switch(facelet_get_event(facelet_in)) {
            case FACELET_EVENT_CREATE:
                // This case will occur when we try to re-create existing faces,
                // eg. in the situation of a forwarder restarting.
                // likely this occurs when the interface receives a (potentially new) address
                if (facelet_merge(facelet, facelet_in) < 0) {
                    ERROR("[facemgr_on_event] Error merging facelets");
                    continue;
                }

                if (facemgr_process_facelet_create(facemgr, facelet_in) < 0) {
                    ERROR("[facemgr_on_event] Error processing facelet CREATE event");
                    ret = -1;
                }

                continue;

            case FACELET_EVENT_GET: /* should be an INFORM message */
                // FIXME, this might occur if the forwarder restarts and we
                // resync faces...
                ERROR("[facemgr_on_event] GET event for a face that already exists...");
                ret = -1;
                continue;

            case FACELET_EVENT_UPDATE:
                if (facelet_merge(facelet, facelet_in) < 0) {
                    ERROR("[facemgr_on_event] Error merging facelets");
                    continue;
                }
                if (facemgr_process_facelet_update(facemgr, facelet) < 0) {
                    ERROR("[facemgr_on_event] Error processing facelet UPDATE event");
                    ret = -1;
                }
                continue;

            case FACELET_EVENT_DELETE:
                if (facelet_merge(facelet, facelet_in) < 0) {
                    ERROR("[facemgr_on_event] Error merging facelets");
                    continue;
                }
                if (facemgr_process_facelet_delete(facemgr, facelet) < 0) {
                        ERROR("[facemgr_on_event] Error processing facelet DELETE event");
                    ret = -1;
                }
                continue;

            default: /* XXX Some events should be deprecated */
                ERROR("[facemgr_on_event] Deprecated event");
                ret = -1;
        }

    }
    goto DUMP_CACHE;

ERR:
    ret = -1;

DUMP_CACHE:
#if 1
    DEBUG("    <CACHE>");
    facelet_set_dump(facemgr->facelet_cache);
    DEBUG("    </CACHE>");
    DEBUG("</EVENT ret=%d>", ret);
    DEBUG("----------------------------------");
#endif

    free(cached_facelets);

    if (remove_facelet)
        facelet_free(facelet_in);

    if (ret == -1)
        facemgr_start_reattempts(facemgr);

    return ret;
}

int facemgr_callback(facemgr_t * facemgr, interface_cb_type_t type, void * data)
{
    switch(type) {
        case INTERFACE_CB_TYPE_RAISE_EVENT:
            return facemgr_on_event(facemgr, data);

        case INTERFACE_CB_TYPE_REGISTER_FD:
        {
            /* Remember fd for further release */
            fd_callback_data_t * fd_callback_data = data;
            interface_t * interface = (interface_t*)(fd_callback_data->owner);

            interface_map_data_t * interface_map_data = NULL;
            if (interface_map_get(facemgr->interface_map, interface->name, &interface_map_data) < 0) {
                ERROR("[facemgr_callback] Error getting interface map data");
                return -1;
            }
            if (!interface_map_data) {
                ERROR("[facemgr_callback] No entry in interface map data");
                return -1;
            }
            interface_map_data->fds[interface_map_data->num_fds++] = fd_callback_data->fd;

            return facemgr->callback(facemgr->callback_owner,
                    FACEMGR_CB_TYPE_REGISTER_FD, data);
        }

        case INTERFACE_CB_TYPE_UNREGISTER_FD:
        {
            fd_callback_data_t * fd_callback_data = data;
            interface_t * interface = (interface_t*)(fd_callback_data->owner);

            interface_map_data_t * interface_map_data = NULL;
            if (interface_map_get(facemgr->interface_map, interface->name, &interface_map_data) < 0) {
                ERROR("[facemgr_callback] Error getting interface map data");
                return -1;
            }
            if (!interface_map_data) {
                ERROR("[facemgr_callback] No entry in interface map data");
                return -1;
            }

            for (unsigned i = 0; i < interface_map_data->num_fds; i++) {
                if (interface_map_data->fds[i] == fd_callback_data->fd) {
                    interface_map_data->fds[i] = interface_map_data->fds[--interface_map_data->num_fds];
                    break;
                }
            }

            return facemgr->callback(facemgr->callback_owner,
                    FACEMGR_CB_TYPE_UNREGISTER_FD, data);
        }

        case INTERFACE_CB_TYPE_REGISTER_TIMER:
            return facemgr->callback(facemgr->callback_owner,
                    FACEMGR_CB_TYPE_REGISTER_TIMER, data);

        case INTERFACE_CB_TYPE_UNREGISTER_TIMER:
            return facemgr->callback(facemgr->callback_owner,
                    FACEMGR_CB_TYPE_UNREGISTER_TIMER, data);

    }
    return -1;
}

int
facemgr_bootstrap(facemgr_t * facemgr)
{
    int rc;

    DEBUG("Registering interfaces...");
    rc = interface_register(&hicn_light_ops);
    if (rc < 0) {
        ERROR("Could not register interfaces");
        goto ERR_REGISTER;
    }

#ifdef __APPLE__
    rc = interface_register(&network_framework_ops);
    if (rc < 0)
        goto ERR_REGISTER;
#endif /* __APPLE__ */

#ifdef __linux__
    rc = interface_register(&netlink_ops);
    if (rc < 0)
        goto ERR_REGISTER;
    rc = interface_register(&bonjour_ops);
    if (rc < 0)
        goto ERR_REGISTER;
#endif /* __linux__ */

#ifdef WITH_ANDROID_UTILITY
    rc = interface_register(&android_utility_ops);
    if (rc < 0)
        goto ERR_REGISTER;
#endif /* WITH_ANDROID_UTILITY */

#ifdef WITH_EXAMPLE_DUMMY
    rc = interface_register(&dummy_ops);
    if (rc < 0)
        goto ERR_REGISTER;
#endif

#ifdef WITH_EXAMPLE_UPDOWN
    rc = interface_register(&updown_ops);
    if (rc < 0)
        goto ERR_REGISTER;
#endif

    rc = facemgr_create_interface(facemgr, "hl", "hicn_light", NULL, &facemgr->hl);
    if (rc < 0) {
        ERROR("Error creating 'hICN forwarder (hicn-light)' interface\n");
        goto ERR_HL_CREATE;
    }

#ifdef __APPLE__
    network_framework_cfg_t nf_cfg = {
    };
    rc = facemgr_create_interface(facemgr, "nf", "network_framework", &nf_cfg, &facemgr->nf);
    if (rc < 0) {
        ERROR("Error creating 'Apple Network Framework' interface\n");
        goto ERR_NF_CREATE;
    }
#endif /* __APPLE__ */

#ifdef __linux__
    rc = facemgr_create_interface(facemgr, "nl", "netlink", NULL, &facemgr->nl);
    if (rc < 0) {
        ERROR("Error creating 'Netlink' interface\n");
        goto ERR_NL_CREATE;
    }
#endif /* __linux__ */

#ifdef WITH_ANDROID_UTILITY
    android_utility_cfg_t au_cfg = {
        .jvm = facemgr->jvm,
    };
    rc = facemgr_create_interface(facemgr, "au", "android_utility", &au_cfg, &facemgr->au);
    if (rc < 0) {
        ERROR("Error creating 'Android Utility' interface\n");
        goto ERR_AU_CREATE;
    }
#endif /* WITH_ANDROID_UTILITY */

#ifdef WITH_EXAMPLE_DUMMY
    rc = facemgr_create_interface(facemgr, "dummy0", "dummy", NULL, &facemgr->dummy);
    if (rc < 0) {
        ERROR("Error creating 'dummy' interface\n");
        goto ERR_DUMMY_CREATE;
    }
#endif

#ifdef WITH_EXAMPLE_UPDOWN
    rc = facemgr_create_interface(facemgr, "updown0", "updown", NULL, &facemgr->updown);
    if (rc < 0) {
        ERROR("Error creating 'updown' interface\n");
        goto ERR_UPDOWN_CREATE;
    }
#endif

    DEBUG("Facemgr successfully initialized...");

    return 0;

    /* FIXME facemgr_delete_interface */
#ifdef WITH_EXAMPLE_UPDOWN
    facemgr_delete_interface(facemgr, facemgr->updown);
ERR_UPDOWN_CREATE:
#endif
#ifdef WITH_EXAMPLE_DUMMY
    facemgr_delete_interface(facemgr, facemgr->dummy);
ERR_DUMMY_CREATE:
#endif
#ifdef WITH_ANDROID_UTILITY
    facemgr_delete_interface(facemgr, facemgr->au);
ERR_AU_CREATE:
#endif /* WITH_ANDROID_UTILITY */
#ifdef __linux__
    facemgr_delete_interface(facemgr, facemgr->nl);
ERR_NL_CREATE:
#endif /* __linux__ */
#ifdef __APPLE__
    facemgr_delete_interface(facemgr, facemgr->nf);
ERR_NF_CREATE:
#endif /* __APPLE__ */
    facemgr_delete_interface(facemgr, facemgr->hl);
ERR_HL_CREATE:
ERR_REGISTER:
    interface_unregister_all();
    return -1;
}

void facemgr_stop(facemgr_t * facemgr)
{
    // FIXME we should iterate on interface map

#ifdef __APPLE__
    facemgr_delete_interface(facemgr, facemgr->nf);
#endif /* __APPLE__ */


#ifdef __linux__
    facemgr_delete_interface(facemgr, facemgr->nl);

    /* Delete all bonjour interfaces */
    interface_t ** bonjour_array = NULL;
    int n = bonjour_map_get_value_array(facemgr->bonjour_map, &bonjour_array);
    if (n >= 0) {
        netdevice_t ** netdevice_array = NULL;
        int m = bonjour_map_get_key_array(facemgr->bonjour_map, &netdevice_array);
        if (m >= 0) {
            assert(m == n);
            for (int i = 0; i < n; i++) { /* Fail silently */
                DEBUG("Deleting bonjour interface associated to %s (%p)",
                        netdevice_array[i]->name, bonjour_array[i]);
                facemgr_delete_interface(facemgr, bonjour_array[i]);
            }
            free(netdevice_array);
        }
        free(bonjour_array);
    }
#endif /* __linux__ */

#ifdef WITH_ANDROID_UTILITY
    facemgr_delete_interface(facemgr, facemgr->au);
#endif /* WITH_ANDROID_UTILITY */

    facemgr_delete_interface(facemgr, facemgr->hl);

#ifdef WITH_EXAMPLE_DUMMY
    facemgr_delete_interface(facemgr, facemgr->dummy);
#endif

#ifdef WITH_EXAMPLE_UPDOWN
    facemgr_delete_interface(facemgr, facemgr->updown);
#endif
}

#ifdef __ANDROID__
void facemgr_set_jvm(facemgr_t * facemgr, JavaVM *jvm)
{
    facemgr->jvm = jvm;
}
#endif /* __ANDROID__ */

void
facemgr_set_callback(facemgr_t * facemgr, void * callback_owner, facemgr_cb_t callback)
{
    facemgr->callback = callback;
    facemgr->callback_owner = callback_owner;
}

void facemgr_list_facelets(const facemgr_t * facemgr, facemgr_list_facelets_cb_t cb, void * user_data)
{
    facelet_t ** facelet_array;
    if (!cb)
        return;
    int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
    if (n < 0) {
        ERROR("[facemgr_list_facelets] Could not retrieve facelets in cache");
        return;
    }
    for (unsigned i = 0; i < n; i++) {
        facelet_t * facelet = facelet_array[i];
        cb(facemgr, facelet, user_data);
    }
    free(facelet_array);
}

int
facemgr_list_facelets_json(const facemgr_t * facemgr, char ** buffer)
{
    char * cur;
    char * s;
    int rc;

    facelet_t ** facelet_array;
    int n = facelet_set_get_array(facemgr->facelet_cache, &facelet_array);
    if (n < 0) {
        ERROR("[facemgr_list_facelets_json] Could not retrieve facelets in cache");
        return -1;
    }
    /* This should be enough for JSON overhead, refine later */
    size_t size = 2 * n * MAXSZ_FACELET;
    *buffer = malloc(size);
    if (!buffer) {
        ERROR("[facemgr_list_facelets_json] Could not allocate JSON s");
        free(facelet_array);
        return -1;
    }
    s = *buffer;
    cur = s;

    rc = snprintf(cur, s + size - cur, "{\"facelets\": [\n");
    if (rc < 0)
        goto ERR;
    cur += rc;
    if (size != 0 && cur >= s + size)
        goto END;

    for (unsigned i = 0; i < n; i++) {
        facelet_t * facelet = facelet_array[i];

        rc = facelet_snprintf_json(cur, s + size - cur, facelet, /* indent */ 1);
        if (rc < 0)
            goto ERR;
        cur += rc;
        if (size != 0 && cur >= s + size)
            goto END;

        rc = snprintf(cur, s + size - cur, (i == n-1) ? "\n" : ",\n");
        if (rc < 0)
            goto ERR;
        cur += rc;
        if (size != 0 && cur >= s + size)
            goto END;
    }
    free(facelet_array);

    rc = snprintf(cur, s + size - cur, "]}\n");
    if (rc < 0)
        goto ERR;
    cur += rc;
    if (size != 0 && cur >= s + size)
        goto END;

END:
    free(facelet_array);
    return cur - s;

ERR:
    free(facelet_array);
    return rc;
}