summaryrefslogtreecommitdiffstats
path: root/src/runmode-unix-socket.c
blob: 8b269900e7dd9e226eef2588818ded2e3f2cdf3c (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
/* Copyright (C) 2012 Open Information Security Foundation
 *
 * You can copy, redistribute or modify this Program under the terms of
 * the GNU General Public License version 2 as published by the Free
 * Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * version 2 along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include "suricata-common.h"
#include "tm-threads.h"
#include "conf.h"
#include "runmodes.h"
#include "runmode-pcap-file.h"
#include "output.h"
#include "output-json.h"

#include "util-debug.h"
#include "util-time.h"
#include "util-cpu.h"
#include "util-affinity.h"
#include "util-var-name.h"
#include "util-path.h"
#include "unix-manager.h"

#include "detect-engine.h"

#include "flow-manager.h"
#include "flow-timeout.h"
#include "flow-hash.h"
#include "stream-tcp.h"
#include "stream-tcp-reassemble.h"
#include "source-pcap-file-directory-helper.h"
#include "host.h"
#include "defrag.h"
#include "defrag-hash.h"
#include "ippair.h"
#include "app-layer.h"
#include "app-layer-htp-mem.h"
#include "host-bit.h"

#include "util-misc.h"
#include "util-profiling.h"

#include "conf-yaml-loader.h"

#include "datasets.h"
#include "runmode-unix-socket.h"

int unix_socket_mode_is_running = 0;

typedef struct PcapFiles_ {
    char *filename;
    char *output_dir;
    uint32_t tenant_id;
    time_t delay;
    time_t poll_interval;
    bool continuous;
    bool should_delete;
    TAILQ_ENTRY(PcapFiles_) next;
} PcapFiles;

typedef struct PcapCommand_ {
    TAILQ_HEAD(, PcapFiles_) files;
    int running;
    PcapFiles *current_file;
} PcapCommand;

typedef struct MemcapCommand_ {
    const char *name;
    int (*SetFunc)(uint64_t);
    uint64_t (*GetFunc)(void);
    uint64_t (*GetMemuseFunc)(void);
} MemcapCommand;

const char *RunModeUnixSocketGetDefaultMode(void)
{
    return "autofp";
}

#define MEMCAPS_MAX 7
static MemcapCommand memcaps[MEMCAPS_MAX] = {
    {
        "stream",
        StreamTcpSetMemcap,
        StreamTcpGetMemcap,
        StreamTcpMemuseCounter,
    },
    {
        "stream-reassembly",
        StreamTcpReassembleSetMemcap,
        StreamTcpReassembleGetMemcap,
        StreamTcpReassembleMemuseGlobalCounter
    },
    {
        "flow",
        FlowSetMemcap,
        FlowGetMemcap,
        FlowGetMemuse
    },
    {
        "applayer-proto-http",
        HTPSetMemcap,
        HTPGetMemcap,
        HTPMemuseGlobalCounter
    },
    {
        "defrag",
        DefragTrackerSetMemcap,
        DefragTrackerGetMemcap,
        DefragTrackerGetMemuse
    },
    {
        "ippair",
        IPPairSetMemcap,
        IPPairGetMemcap,
        IPPairGetMemuse
    },
    {
        "host",
        HostSetMemcap,
        HostGetMemcap,
        HostGetMemuse
    },
};

float MemcapsGetPressure(void)
{
    float percent = 0.0;
    for (int i = 0; i < 4; i++) { // only flow, streams, http
        uint64_t memcap = memcaps[i].GetFunc();
        if (memcap) {
            uint64_t memuse = memcaps[i].GetMemuseFunc();
            float p = (float)((double)memuse / (double)memcap);
            // SCLogNotice("%s: memuse %"PRIu64", memcap %"PRIu64" => %f%%",
            //    memcaps[i].name, memuse, memcap, (p * 100));
            percent = MAX(p, percent);
        }
    }
    return percent;
}

#ifdef BUILD_UNIX_SOCKET

static int RunModeUnixSocketMaster(void);
static int unix_manager_pcap_task_running = 0;
static int unix_manager_pcap_task_failed = 0;
static int unix_manager_pcap_task_interrupted = 0;
static struct timespec unix_manager_pcap_last_processed;
static SCCtrlMutex unix_manager_pcap_last_processed_mutex;

/**
 * \brief return list of files in the queue
 *
 * \retval 0 in case of error, 1 in case of success
 */
static TmEcode UnixSocketPcapFilesList(json_t *cmd, json_t* answer, void *data)
{
    PcapCommand *this = (PcapCommand *) data;
    int i = 0;
    PcapFiles *file;
    json_t *jdata;
    json_t *jarray;

    jdata = json_object();
    if (jdata == NULL) {
        json_object_set_new(answer, "message",
                            json_string("internal error at json object creation"));
        return TM_ECODE_FAILED;
    }
    jarray = json_array();
    if (jarray == NULL) {
        json_decref(jdata);
        json_object_set_new(answer, "message",
                            json_string("internal error at json object creation"));
        return TM_ECODE_FAILED;
    }
    TAILQ_FOREACH(file, &this->files, next) {
        json_array_append_new(jarray, SCJsonString(file->filename));
        i++;
    }
    json_object_set_new(jdata, "count", json_integer(i));
    json_object_set_new(jdata, "files", jarray);
    json_object_set_new(answer, "message", jdata);
    return TM_ECODE_OK;
}

static TmEcode UnixSocketPcapFilesNumber(json_t *cmd, json_t* answer, void *data)
{
    PcapCommand *this = (PcapCommand *) data;
    int i = 0;
    PcapFiles *file;

    TAILQ_FOREACH(file, &this->files, next) {
        i++;
    }
    json_object_set_new(answer, "message", json_integer(i));
    return TM_ECODE_OK;
}

static TmEcode UnixSocketPcapCurrent(json_t *cmd, json_t* answer, void *data)
{
    PcapCommand *this = (PcapCommand *) data;

    if (this->current_file != NULL && this->current_file->filename != NULL) {
        json_object_set_new(answer, "message",
                            json_string(this->current_file->filename));
    } else {
        json_object_set_new(answer, "message", json_string("None"));
    }
    return TM_ECODE_OK;
}

static TmEcode UnixSocketPcapLastProcessed(json_t *cmd, json_t *answer, void *data)
{
    json_int_t epoch_millis;
    SCCtrlMutexLock(&unix_manager_pcap_last_processed_mutex);
    epoch_millis = SCTimespecAsEpochMillis(&unix_manager_pcap_last_processed);
    SCCtrlMutexUnlock(&unix_manager_pcap_last_processed_mutex);

    json_object_set_new(answer, "message",
                        json_integer(epoch_millis));

    return TM_ECODE_OK;
}

static TmEcode UnixSocketPcapInterrupt(json_t *cmd, json_t *answer, void *data)
{
    unix_manager_pcap_task_interrupted = 1;

    json_object_set_new(answer, "message", json_string("Interrupted"));

    return TM_ECODE_OK;
}

static void PcapFilesFree(PcapFiles *cfile)
{
    if (cfile == NULL)
        return;
    if (cfile->filename)
        SCFree(cfile->filename);
    if (cfile->output_dir)
        SCFree(cfile->output_dir);
    SCFree(cfile);
}

/**
 * \brief Add file to file queue
 *
 * \param this a UnixCommand:: structure
 * \param filename absolute filename
 * \param output_dir absolute name of directory where log will be put
 * \param tenant_id Id of tenant associated with this file
 * \param continuous If file should be run in continuous mode
 * \param delete If file should be deleted when done
 * \param delay Delay required for file modified time before being processed
 * \param poll_interval How frequently directory mode polls for new files
 *
 * \retval 0 in case of error, 1 in case of success
 */
static TmEcode UnixListAddFile(PcapCommand *this, const char *filename, const char *output_dir,
        uint32_t tenant_id, bool continuous, bool should_delete, time_t delay, time_t poll_interval)
{
    PcapFiles *cfile = NULL;
    if (filename == NULL || this == NULL)
        return TM_ECODE_FAILED;
    cfile = SCMalloc(sizeof(PcapFiles));
    if (unlikely(cfile == NULL)) {
        SCLogError("Unable to allocate new file");
        return TM_ECODE_FAILED;
    }
    memset(cfile, 0, sizeof(PcapFiles));

    cfile->filename = SCStrdup(filename);
    if (unlikely(cfile->filename == NULL)) {
        SCFree(cfile);
        SCLogError("Unable to dup filename");
        return TM_ECODE_FAILED;
    }

    if (output_dir) {
        cfile->output_dir = SCStrdup(output_dir);
        if (unlikely(cfile->output_dir == NULL)) {
            SCFree(cfile->filename);
            SCFree(cfile);
            SCLogError("Unable to dup output_dir");
            return TM_ECODE_FAILED;
        }
    }

    cfile->tenant_id = tenant_id;
    cfile->continuous = continuous;
    cfile->should_delete = should_delete;
    cfile->delay = delay;
    cfile->poll_interval = poll_interval;

    TAILQ_INSERT_TAIL(&this->files, cfile, next);
    return TM_ECODE_OK;
}

/**
 * \brief Command to add a file to treatment list
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 * \param data pointer to data defining the context here a PcapCommand::
 * \param continuous If this should run in continuous mode
 */
static TmEcode UnixSocketAddPcapFileImpl(json_t *cmd, json_t* answer, void *data,
                                         bool continuous)
{
    PcapCommand *this = (PcapCommand *) data;
    const char *filename;
    const char *output_dir;
    uint32_t tenant_id = 0;
    bool should_delete = false;
    time_t delay = 30;
    time_t poll_interval = 5;
    SCStat st;

    json_t *jarg = json_object_get(cmd, "filename");
    if (!json_is_string(jarg)) {
        SCLogError("filename is not a string");
        json_object_set_new(answer, "message",
                            json_string("filename is not a string"));
        return TM_ECODE_FAILED;
    }
    filename = json_string_value(jarg);
    if (SCStatFn(filename, &st) != 0) {
        json_object_set_new(answer, "message",
                            json_string("filename does not exist"));
        return TM_ECODE_FAILED;
    }

    json_t *oarg = json_object_get(cmd, "output-dir");
    if (oarg != NULL) {
        if (!json_is_string(oarg)) {
            SCLogError("output-dir is not a string");

            json_object_set_new(answer, "message",
                                json_string("output-dir is not a string"));
            return TM_ECODE_FAILED;
        }
        output_dir = json_string_value(oarg);
    } else {
        SCLogError("can't get output-dir");

        json_object_set_new(answer, "message",
                            json_string("output-dir param is mandatory"));
        return TM_ECODE_FAILED;
    }

    if (SCStatFn(output_dir, &st) != 0) {
        json_object_set_new(answer, "message",
                            json_string("output-dir does not exist"));
        return TM_ECODE_FAILED;
    }

    json_t *targ = json_object_get(cmd, "tenant");
    if (targ != NULL) {
        if (!json_is_integer(targ)) {
            json_object_set_new(answer, "message",
                                json_string("tenant is not a number"));
            return TM_ECODE_FAILED;
        }
        tenant_id = json_number_value(targ);
    }

    json_t *delete_arg = json_object_get(cmd, "delete-when-done");
    if (delete_arg != NULL) {
        should_delete = json_is_true(delete_arg);
    }

    json_t *delay_arg = json_object_get(cmd, "delay");
    if (delay_arg != NULL) {
        if (!json_is_integer(delay_arg)) {
            SCLogError("delay is not a integer");
            json_object_set_new(answer, "message",
                                json_string("delay is not a integer"));
            return TM_ECODE_FAILED;
        }
        delay = json_integer_value(delay_arg);
    }

    json_t *interval_arg = json_object_get(cmd, "poll-interval");
    if (interval_arg != NULL) {
        if (!json_is_integer(interval_arg)) {
            SCLogError("poll-interval is not a integer");

            json_object_set_new(answer, "message",
                                json_string("poll-interval is not a integer"));
            return TM_ECODE_FAILED;
        }
        poll_interval = json_integer_value(interval_arg);
    }

    switch (UnixListAddFile(this, filename, output_dir, tenant_id, continuous,
                           should_delete, delay, poll_interval)) {
        case TM_ECODE_FAILED:
        case TM_ECODE_DONE:
            json_object_set_new(answer, "message",
                                json_string("Unable to add file to list"));
            return TM_ECODE_FAILED;
        case TM_ECODE_OK:
            SCLogInfo("Added file '%s' to list", filename);
            json_object_set_new(answer, "message",
                                json_string("Successfully added file to list"));
            return TM_ECODE_OK;
    }
    return TM_ECODE_OK;
}

/**
 * \brief Command to add a file to treatment list
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 * \param data pointer to data defining the context here a PcapCommand::
 */
static TmEcode UnixSocketAddPcapFile(json_t *cmd, json_t* answer, void *data)
{
    bool continuous = false;

    json_t *cont_arg = json_object_get(cmd, "continuous");
    if (cont_arg != NULL) {
        continuous = json_is_true(cont_arg);
    }

    return UnixSocketAddPcapFileImpl(cmd, answer, data, continuous);
}

/**
 * \brief Command to add a file to treatment list, forcing continuous mode
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 * \param data pointer to data defining the context here a PcapCommand::
 */
static TmEcode UnixSocketAddPcapFileContinuous(json_t *cmd, json_t* answer, void *data)
{
    return UnixSocketAddPcapFileImpl(cmd, answer, data, true);
}

/**
 * \brief Handle the file queue
 *
 * This function check if there is currently a file
 * being parse. If it is not the case, it will start to
 * work on a new file. This implies to start a new 'pcap-file'
 * running mode after having set the file and the output dir.
 * This function also handles the cleaning of the previous
 * running mode.
 *
 * \param this a UnixCommand:: structure
 * \retval 0 in case of error, 1 in case of success
 */
static TmEcode UnixSocketPcapFilesCheck(void *data)
{
    PcapCommand *this = (PcapCommand *) data;
    if (unix_manager_pcap_task_running == 1) {
        return TM_ECODE_OK;
    }
    if ((unix_manager_pcap_task_failed == 1) || (this->running == 1)) {
        if (unix_manager_pcap_task_failed) {
            SCLogInfo("Preceeding task failed, cleaning the running mode");
        }
        unix_manager_pcap_task_failed = 0;
        this->running = 0;

        SCLogInfo("Resetting engine state");
        PostRunDeinit(RUNMODE_PCAP_FILE, NULL /* no ts */);

        if (this->current_file) {
            PcapFilesFree(this->current_file);
        }
        this->current_file = NULL;
    }

    if (TAILQ_EMPTY(&this->files)) {
        // nothing to do
        return TM_ECODE_OK;
    }

    PcapFiles *cfile = TAILQ_FIRST(&this->files);
    TAILQ_REMOVE(&this->files, cfile, next);

    unix_manager_pcap_task_running = 1;
    this->running = 1;

    if (ConfSetFinal("pcap-file.file", cfile->filename) != 1) {
        SCLogError("Can not set working file to '%s'", cfile->filename);
        PcapFilesFree(cfile);
        return TM_ECODE_FAILED;
    }

    int set_res = 0;
    if (cfile->continuous) {
        set_res = ConfSetFinal("pcap-file.continuous", "true");
    } else {
        set_res = ConfSetFinal("pcap-file.continuous", "false");
    }
    if (set_res != 1) {
        SCLogError("Can not set continuous mode for pcap processing");
        PcapFilesFree(cfile);
        return TM_ECODE_FAILED;
    }
    if (cfile->should_delete) {
        set_res = ConfSetFinal("pcap-file.delete-when-done", "true");
    } else {
        set_res = ConfSetFinal("pcap-file.delete-when-done", "false");
    }
    if (set_res != 1) {
        SCLogError("Can not set delete mode for pcap processing");
        PcapFilesFree(cfile);
        return TM_ECODE_FAILED;
    }

    if (cfile->delay > 0) {
        char tstr[32];
        snprintf(tstr, sizeof(tstr), "%" PRIuMAX, (uintmax_t)cfile->delay);
        if (ConfSetFinal("pcap-file.delay", tstr) != 1) {
            SCLogError("Can not set delay to '%s'", tstr);
            PcapFilesFree(cfile);
            return TM_ECODE_FAILED;
        }
    }

    if (cfile->poll_interval > 0) {
        char tstr[32];
        snprintf(tstr, sizeof(tstr), "%" PRIuMAX, (uintmax_t)cfile->poll_interval);
        if (ConfSetFinal("pcap-file.poll-interval", tstr) != 1) {
            SCLogError("Can not set poll-interval to '%s'", tstr);
            PcapFilesFree(cfile);
            return TM_ECODE_FAILED;
        }
    }

    if (cfile->tenant_id > 0) {
        char tstr[16];
        snprintf(tstr, sizeof(tstr), "%u", cfile->tenant_id);
        if (ConfSetFinal("pcap-file.tenant-id", tstr) != 1) {
            SCLogError("Can not set working tenant-id to '%s'", tstr);
            PcapFilesFree(cfile);
            return TM_ECODE_FAILED;
        }
    } else {
        SCLogInfo("pcap-file.tenant-id not set");
    }

    if (cfile->output_dir) {
        if (ConfSetFinal("default-log-dir", cfile->output_dir) != 1) {
            SCLogError("Can not set output dir to '%s'", cfile->output_dir);
            PcapFilesFree(cfile);
            return TM_ECODE_FAILED;
        }
    }

    this->current_file = cfile;

    SCLogInfo("Starting run for '%s'", this->current_file->filename);

    PreRunInit(RUNMODE_PCAP_FILE);
    PreRunPostPrivsDropInit(RUNMODE_PCAP_FILE);
    RunModeDispatch(RUNMODE_PCAP_FILE, NULL, NULL, NULL);

    /* Un-pause all the paused threads */
    TmThreadWaitOnThreadInit();
    PacketPoolPostRunmodes();
    TmThreadContinueThreads();

    return TM_ECODE_OK;
}
#endif

void RunModeUnixSocketRegister(void)
{
#ifdef BUILD_UNIX_SOCKET
    /* a bit of a hack, but register twice to --list-runmodes shows both */
    RunModeRegisterNewRunMode(
            RUNMODE_UNIX_SOCKET, "single", "Unix socket mode", RunModeUnixSocketMaster, NULL);
    RunModeRegisterNewRunMode(
            RUNMODE_UNIX_SOCKET, "autofp", "Unix socket mode", RunModeUnixSocketMaster, NULL);
#endif
}

TmEcode UnixSocketPcapFile(TmEcode tm, struct timespec *last_processed)
{
#ifdef BUILD_UNIX_SOCKET
    if(last_processed) {
        SCCtrlMutexLock(&unix_manager_pcap_last_processed_mutex);
        unix_manager_pcap_last_processed.tv_sec = last_processed->tv_sec;
        unix_manager_pcap_last_processed.tv_nsec = last_processed->tv_nsec;
        SCCtrlMutexUnlock(&unix_manager_pcap_last_processed_mutex);
    }
    switch (tm) {
        case TM_ECODE_DONE:
            SCLogInfo("Marking current task as done");
            unix_manager_pcap_task_running = 0;
            return TM_ECODE_DONE;
        case TM_ECODE_FAILED:
            SCLogInfo("Marking current task as failed");
            unix_manager_pcap_task_running = 0;
            unix_manager_pcap_task_failed = 1;
            //if we return failed, we can't stop the thread and suricata will fail to close
            return TM_ECODE_FAILED;
        case TM_ECODE_OK:
            if (unix_manager_pcap_task_interrupted == 1) {
                SCLogInfo("Interrupting current run mode");
                unix_manager_pcap_task_interrupted = 0;
                return TM_ECODE_DONE;
            } else {
                return TM_ECODE_OK;
            }
    }
#endif
    return TM_ECODE_FAILED;
}

#ifdef BUILD_UNIX_SOCKET
/**
 * \brief Command to add data to a dataset
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 * \param data pointer to data defining the context here a PcapCommand::
 */
TmEcode UnixSocketDatasetAdd(json_t *cmd, json_t* answer, void *data)
{
    /* 1 get dataset name */
    json_t *narg = json_object_get(cmd, "setname");
    if (!json_is_string(narg)) {
        json_object_set_new(answer, "message", json_string("setname is not a string"));
        return TM_ECODE_FAILED;
    }
    const char *set_name = json_string_value(narg);

    /* 2 get the data type */
    json_t *targ = json_object_get(cmd, "settype");
    if (!json_is_string(targ)) {
        json_object_set_new(answer, "message", json_string("settype is not a string"));
        return TM_ECODE_FAILED;
    }
    const char *type = json_string_value(targ);

    /* 3 get value */
    json_t *varg = json_object_get(cmd, "datavalue");
    if (!json_is_string(varg)) {
        json_object_set_new(answer, "message", json_string("datavalue is not string"));
        return TM_ECODE_FAILED;
    }
    const char *value = json_string_value(varg);

    SCLogDebug("dataset-add: %s type %s value %s", set_name, type, value);

    enum DatasetTypes t = DatasetGetTypeFromString(type);
    if (t == DATASET_TYPE_NOTSET) {
        json_object_set_new(answer, "message", json_string("unknown settype"));
        return TM_ECODE_FAILED;
    }

    Dataset *set = DatasetFind(set_name, t);
    if (set == NULL) {
        json_object_set_new(answer, "message", json_string("set not found or wrong type"));
        return TM_ECODE_FAILED;
    }

    int r = DatasetAddSerialized(set, value);
    if (r == 1) {
        json_object_set_new(answer, "message", json_string("data added"));
        return TM_ECODE_OK;
    } else if (r == 0) {
        json_object_set_new(answer, "message", json_string("data already in set"));
        return TM_ECODE_OK;
    } else {
        json_object_set_new(answer, "message", json_string("failed to add data"));
        return TM_ECODE_FAILED;
    }
}

TmEcode UnixSocketDatasetRemove(json_t *cmd, json_t* answer, void *data)
{
    /* 1 get dataset name */
    json_t *narg = json_object_get(cmd, "setname");
    if (!json_is_string(narg)) {
        json_object_set_new(answer, "message", json_string("setname is not a string"));
        return TM_ECODE_FAILED;
    }
    const char *set_name = json_string_value(narg);

    /* 2 get the data type */
    json_t *targ = json_object_get(cmd, "settype");
    if (!json_is_string(targ)) {
        json_object_set_new(answer, "message", json_string("settype is not a string"));
        return TM_ECODE_FAILED;
    }
    const char *type = json_string_value(targ);

    /* 3 get value */
    json_t *varg = json_object_get(cmd, "datavalue");
    if (!json_is_string(varg)) {
        json_object_set_new(answer, "message", json_string("datavalue is not string"));
        return TM_ECODE_FAILED;
    }
    const char *value = json_string_value(varg);

    SCLogDebug("dataset-remove: %s type %s value %s", set_name, type, value);

    enum DatasetTypes t = DatasetGetTypeFromString(type);
    if (t == DATASET_TYPE_NOTSET) {
        json_object_set_new(answer, "message", json_string("unknown settype"));
        return TM_ECODE_FAILED;
    }

    Dataset *set = DatasetFind(set_name, t);
    if (set == NULL) {
        json_object_set_new(answer, "message", json_string("set not found or wrong type"));
        return TM_ECODE_FAILED;
    }

    int r = DatasetRemoveSerialized(set, value);
    if (r == 1) {
        json_object_set_new(answer, "message", json_string("data removed"));
        return TM_ECODE_OK;
    } else if (r == 0) {
        json_object_set_new(answer, "message", json_string("data is busy, try again"));
        return TM_ECODE_OK;
    } else {
        json_object_set_new(answer, "message", json_string("failed to remove data"));
        return TM_ECODE_FAILED;
    }
}

TmEcode UnixSocketDatasetDump(json_t *cmd, json_t *answer, void *data)
{
    SCEnter();
    SCLogDebug("Going to dump datasets");
    DatasetsSave();
    json_object_set_new(answer, "message", json_string("datasets dump done"));
    SCReturnInt(TM_ECODE_OK);
}

TmEcode UnixSocketDatasetClear(json_t *cmd, json_t *answer, void *data)
{
    /* 1 get dataset name */
    json_t *narg = json_object_get(cmd, "setname");
    if (!json_is_string(narg)) {
        json_object_set_new(answer, "message", json_string("setname is not a string"));
        return TM_ECODE_FAILED;
    }
    const char *set_name = json_string_value(narg);

    /* 2 get the data type */
    json_t *targ = json_object_get(cmd, "settype");
    if (!json_is_string(targ)) {
        json_object_set_new(answer, "message", json_string("settype is not a string"));
        return TM_ECODE_FAILED;
    }
    const char *type = json_string_value(targ);

    enum DatasetTypes t = DatasetGetTypeFromString(type);
    if (t == DATASET_TYPE_NOTSET) {
        json_object_set_new(answer, "message", json_string("unknown settype"));
        return TM_ECODE_FAILED;
    }

    Dataset *set = DatasetFind(set_name, t);
    if (set == NULL) {
        json_object_set_new(answer, "message", json_string("set not found or wrong type"));
        return TM_ECODE_FAILED;
    }

    THashCleanup(set->hash);

    json_object_set_new(answer, "message", json_string("dataset cleared"));
    return TM_ECODE_OK;
}

TmEcode UnixSocketDatasetLookup(json_t *cmd, json_t *answer, void *data)
{
    /* 1 get dataset name */
    json_t *narg = json_object_get(cmd, "setname");
    if (!json_is_string(narg)) {
        json_object_set_new(answer, "message", json_string("setname is not a string"));
        return TM_ECODE_FAILED;
    }
    const char *set_name = json_string_value(narg);

    /* 2 get the data type */
    json_t *targ = json_object_get(cmd, "settype");
    if (!json_is_string(targ)) {
        json_object_set_new(answer, "message", json_string("settype is not a string"));
        return TM_ECODE_FAILED;
    }
    const char *type = json_string_value(targ);

    /* 3 get value */
    json_t *varg = json_object_get(cmd, "datavalue");
    if (!json_is_string(varg)) {
        json_object_set_new(answer, "message", json_string("datavalue is not string"));
        return TM_ECODE_FAILED;
    }
    const char *value = json_string_value(varg);

    SCLogDebug("dataset-exist: %s type %s value %s", set_name, type, value);

    enum DatasetTypes t = DatasetGetTypeFromString(type);
    if (t == DATASET_TYPE_NOTSET) {
        json_object_set_new(answer, "message", json_string("unknown settype"));
        return TM_ECODE_FAILED;
    }

    Dataset *set = DatasetFind(set_name, t);
    if (set == NULL) {
        json_object_set_new(answer, "message", json_string("set not found or wrong type"));
        return TM_ECODE_FAILED;
    }

    if (DatasetLookupSerialized(set, value) > 0) {
        json_object_set_new(answer, "message", json_string("item found in set"));
        return TM_ECODE_OK;
    } else {
        json_object_set_new(answer, "message", json_string("item not found in set"));
        return TM_ECODE_FAILED;
    }
}

/**
 * \brief Command to add a tenant handler
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 * \param data pointer to data defining the context here a PcapCommand::
 */
TmEcode UnixSocketRegisterTenantHandler(json_t *cmd, json_t* answer, void *data)
{
    const char *htype;
    json_int_t traffic_id = -1;

    if (!(DetectEngineMultiTenantEnabled())) {
        SCLogInfo("error: multi-tenant support not enabled");
        json_object_set_new(answer, "message", json_string("multi-tenant support not enabled"));
        return TM_ECODE_FAILED;
    }

    /* 1 get tenant id */
    json_t *jarg = json_object_get(cmd, "id");
    if (!json_is_integer(jarg)) {
        SCLogInfo("error: command is not a string");
        json_object_set_new(answer, "message", json_string("id is not an integer"));
        return TM_ECODE_FAILED;
    }
    uint32_t tenant_id = json_integer_value(jarg);

    /* 2 get tenant handler type */
    jarg = json_object_get(cmd, "htype");
    if (!json_is_string(jarg)) {
        SCLogInfo("error: command is not a string");
        json_object_set_new(answer, "message", json_string("command is not a string"));
        return TM_ECODE_FAILED;
    }
    htype = json_string_value(jarg);

    SCLogDebug("add-tenant-handler: %d %s", tenant_id, htype);

    /* 3 get optional hargs */
    json_t *hargs = json_object_get(cmd, "hargs");
    if (hargs != NULL) {
        if (!json_is_integer(hargs)) {
            SCLogInfo("error: hargs not a number");
            json_object_set_new(answer, "message", json_string("hargs not a number"));
            return TM_ECODE_FAILED;
        }
        traffic_id = json_integer_value(hargs);
    }

    /* 4 add to system */
    int r = -1;
    if (strcmp(htype, "pcap") == 0) {
        r = DetectEngineTenantRegisterPcapFile(tenant_id);
    } else if (strcmp(htype, "vlan") == 0) {
        if (traffic_id < 0) {
            json_object_set_new(answer, "message", json_string("vlan requires argument"));
            return TM_ECODE_FAILED;
        }
        if (traffic_id > USHRT_MAX) {
            json_object_set_new(answer, "message", json_string("vlan argument out of range"));
            return TM_ECODE_FAILED;
        }

        SCLogInfo("VLAN handler: id %u maps to tenant %u", (uint32_t)traffic_id, tenant_id);
        r = DetectEngineTenantRegisterVlanId(tenant_id, (uint16_t)traffic_id);
    }
    if (r != 0) {
        json_object_set_new(answer, "message", json_string("handler setup failure"));
        return TM_ECODE_FAILED;
    }

    if (DetectEngineMTApply() < 0) {
        json_object_set_new(answer, "message", json_string("couldn't apply settings"));
        // TODO cleanup
        return TM_ECODE_FAILED;
    }

    json_object_set_new(answer, "message", json_string("handler added"));
    return TM_ECODE_OK;
}

/**
 * \brief Command to remove a tenant handler
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 * \param data pointer to data defining the context here a PcapCommand::
 */
TmEcode UnixSocketUnregisterTenantHandler(json_t *cmd, json_t* answer, void *data)
{
    const char *htype;
    json_int_t traffic_id = -1;

    if (!(DetectEngineMultiTenantEnabled())) {
        SCLogInfo("error: multi-tenant support not enabled");
        json_object_set_new(answer, "message", json_string("multi-tenant support not enabled"));
        return TM_ECODE_FAILED;
    }

    /* 1 get tenant id */
    json_t *jarg = json_object_get(cmd, "id");
    if (!json_is_integer(jarg)) {
        SCLogInfo("error: command is not a string");
        json_object_set_new(answer, "message", json_string("id is not an integer"));
        return TM_ECODE_FAILED;
    }
    uint32_t tenant_id = json_integer_value(jarg);

    /* 2 get tenant handler type */
    jarg = json_object_get(cmd, "htype");
    if (!json_is_string(jarg)) {
        SCLogInfo("error: command is not a string");
        json_object_set_new(answer, "message", json_string("command is not a string"));
        return TM_ECODE_FAILED;
    }
    htype = json_string_value(jarg);

    SCLogDebug("add-tenant-handler: %d %s", tenant_id, htype);

    /* 3 get optional hargs */
    json_t *hargs = json_object_get(cmd, "hargs");
    if (hargs != NULL) {
        if (!json_is_integer(hargs)) {
            SCLogInfo("error: hargs not a number");
            json_object_set_new(answer, "message", json_string("hargs not a number"));
            return TM_ECODE_FAILED;
        }
        traffic_id = json_integer_value(hargs);
    }

    /* 4 add to system */
    int r = -1;
    if (strcmp(htype, "pcap") == 0) {
        r = DetectEngineTenantUnregisterPcapFile(tenant_id);
    } else if (strcmp(htype, "vlan") == 0) {
        if (traffic_id < 0) {
            json_object_set_new(answer, "message", json_string("vlan requires argument"));
            return TM_ECODE_FAILED;
        }
        if (traffic_id > USHRT_MAX) {
            json_object_set_new(answer, "message", json_string("vlan argument out of range"));
            return TM_ECODE_FAILED;
        }

        SCLogInfo("VLAN handler: removing mapping of %u to tenant %u", (uint32_t)traffic_id, tenant_id);
        r = DetectEngineTenantUnregisterVlanId(tenant_id, (uint16_t)traffic_id);
    }
    if (r != 0) {
        json_object_set_new(answer, "message", json_string("handler unregister failure"));
        return TM_ECODE_FAILED;
    }

    /* 5 apply it */
    if (DetectEngineMTApply() < 0) {
        json_object_set_new(answer, "message", json_string("couldn't apply settings"));
        // TODO cleanup
        return TM_ECODE_FAILED;
    }

    json_object_set_new(answer, "message", json_string("handler removed"));
    return TM_ECODE_OK;
}

/**
 * \brief Command to add a tenant
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 * \param data pointer to data defining the context here a PcapCommand::
 */
TmEcode UnixSocketRegisterTenant(json_t *cmd, json_t* answer, void *data)
{
    const char *filename;
    SCStat st;

    if (!(DetectEngineMultiTenantEnabled())) {
        SCLogInfo("error: multi-tenant support not enabled");
        json_object_set_new(answer, "message", json_string("multi-tenant support not enabled"));
        return TM_ECODE_FAILED;
    }

    /* 1 get tenant id */
    json_t *jarg = json_object_get(cmd, "id");
    if (!json_is_integer(jarg)) {
        json_object_set_new(answer, "message", json_string("id is not an integer"));
        return TM_ECODE_FAILED;
    }
    uint32_t tenant_id = json_integer_value(jarg);

    /* 2 get tenant yaml */
    jarg = json_object_get(cmd, "filename");
    if (!json_is_string(jarg)) {
        json_object_set_new(answer, "message", json_string("command is not a string"));
        return TM_ECODE_FAILED;
    }
    filename = json_string_value(jarg);
    if (SCStatFn(filename, &st) != 0) {
        json_object_set_new(answer, "message", json_string("file does not exist"));
        return TM_ECODE_FAILED;
    }

    SCLogDebug("add-tenant: %d %s", tenant_id, filename);

    /* setup the yaml in this loop so that it's not done by the loader
     * threads. ConfYamlLoadFileWithPrefix is not thread safe. */
    char prefix[64];
    snprintf(prefix, sizeof(prefix), "multi-detect.%u", tenant_id);
    if (ConfYamlLoadFileWithPrefix(filename, prefix) != 0) {
        SCLogError("failed to load yaml %s", filename);
        json_object_set_new(answer, "message", json_string("failed to load yaml"));
        return TM_ECODE_FAILED;
    }

    /* 3 load into the system */
    if (DetectEngineLoadTenantBlocking(tenant_id, filename) != 0) {
        json_object_set_new(answer, "message", json_string("adding tenant failed"));
        return TM_ECODE_FAILED;
    }

    /* 4 apply to the running system */
    if (DetectEngineMTApply() < 0) {
        json_object_set_new(answer, "message", json_string("couldn't apply settings"));
        // TODO cleanup
        return TM_ECODE_FAILED;
    }

    json_object_set_new(answer, "message", json_string("adding tenant succeeded"));
    return TM_ECODE_OK;
}

static int reload_cnt = 1;
/**
 * \brief Command to reload a tenant
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 * \param data pointer to data defining the context here a PcapCommand::
 */
TmEcode UnixSocketReloadTenant(json_t *cmd, json_t* answer, void *data)
{
    const char *filename = NULL;
    SCStat st;

    if (!(DetectEngineMultiTenantEnabled())) {
        SCLogInfo("error: multi-tenant support not enabled");
        json_object_set_new(answer, "message", json_string("multi-tenant support not enabled"));
        return TM_ECODE_FAILED;
    }

    /* 1 get tenant id */
    json_t *jarg = json_object_get(cmd, "id");
    if (!json_is_integer(jarg)) {
        json_object_set_new(answer, "message", json_string("id is not an integer"));
        return TM_ECODE_FAILED;
    }
    uint32_t tenant_id = json_integer_value(jarg);

    /* 2 get tenant yaml */
    jarg = json_object_get(cmd, "filename");
    if (jarg) {
        if (!json_is_string(jarg)) {
            json_object_set_new(answer, "message", json_string("command is not a string"));
            return TM_ECODE_FAILED;
        }
        filename = json_string_value(jarg);
        if (SCStatFn(filename, &st) != 0) {
            json_object_set_new(answer, "message", json_string("file does not exist"));
            return TM_ECODE_FAILED;
        }
    }

    SCLogDebug("reload-tenant: %d %s", tenant_id, filename);

    /* 3 load into the system */
    if (DetectEngineReloadTenantBlocking(tenant_id, filename, reload_cnt) != 0) {
        json_object_set_new(answer, "message", json_string("reload tenant failed"));
        return TM_ECODE_FAILED;
    }

    reload_cnt++;

    /*  apply to the running system */
    if (DetectEngineMTApply() < 0) {
        json_object_set_new(answer, "message", json_string("couldn't apply settings"));
        // TODO cleanup
        return TM_ECODE_FAILED;
    }

    json_object_set_new(answer, "message", json_string("reloading tenant succeeded"));
    return TM_ECODE_OK;
}

/**
 * \brief Command to reload all tenants
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 * \param data pointer to data defining the context here a PcapCommand::
 */
TmEcode UnixSocketReloadTenants(json_t *cmd, json_t *answer, void *data)
{
    if (!(DetectEngineMultiTenantEnabled())) {
        SCLogInfo("error: multi-tenant support not enabled");
        json_object_set_new(answer, "message", json_string("multi-tenant support not enabled"));
        return TM_ECODE_FAILED;
    }

    if (DetectEngineReloadTenantsBlocking(reload_cnt) != 0) {
        json_object_set_new(answer, "message", json_string("reload tenants failed"));
        return TM_ECODE_FAILED;
    }

    reload_cnt++;

    /*  apply to the running system */
    if (DetectEngineMTApply() < 0) {
        json_object_set_new(answer, "message", json_string("couldn't apply settings"));
        // TODO cleanup
        return TM_ECODE_FAILED;
    }

    SCLogNotice("reload-tenants complete");

    json_object_set_new(answer, "message", json_string("reloading tenants succeeded"));
    return TM_ECODE_OK;
}

/**
 * \brief Command to remove a tenant
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 * \param data pointer to data defining the context here a PcapCommand::
 */
TmEcode UnixSocketUnregisterTenant(json_t *cmd, json_t* answer, void *data)
{
    if (!(DetectEngineMultiTenantEnabled())) {
        SCLogInfo("error: multi-tenant support not enabled");
        json_object_set_new(answer, "message", json_string("multi-tenant support not enabled"));
        return TM_ECODE_FAILED;
    }

    /* 1 get tenant id */
    json_t *jarg = json_object_get(cmd, "id");
    if (!json_is_integer(jarg)) {
        SCLogInfo("error: command is not a string");
        json_object_set_new(answer, "message", json_string("id is not an integer"));
        return TM_ECODE_FAILED;
    }
    uint32_t tenant_id = json_integer_value(jarg);

    SCLogInfo("remove-tenant: removing tenant %d", tenant_id);

    /* 2 remove it from the system */
    char prefix[64];
    snprintf(prefix, sizeof(prefix), "multi-detect.%u", tenant_id);

    DetectEngineCtx *de_ctx = DetectEngineGetByTenantId(tenant_id);
    if (de_ctx == NULL) {
        json_object_set_new(answer, "message", json_string("tenant detect engine not found"));
        return TM_ECODE_FAILED;
    }

    /* move to free list */
    DetectEngineMoveToFreeList(de_ctx);
    DetectEngineDeReference(&de_ctx);

    /* update the threads */
    if (DetectEngineMTApply() < 0) {
        json_object_set_new(answer, "message", json_string("couldn't apply settings"));
        // TODO cleanup
        return TM_ECODE_FAILED;
    }

    /* walk free list, freeing the removed de_ctx */
    DetectEnginePruneFreeList();

    json_object_set_new(answer, "message", json_string("removing tenant succeeded"));
    return TM_ECODE_OK;
}

/**
 * \brief Command to add a hostbit
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 */
TmEcode UnixSocketHostbitAdd(json_t *cmd, json_t* answer, void *data_usused)
{
    /* 1 get ip address */
    json_t *jarg = json_object_get(cmd, "ipaddress");
    if (!json_is_string(jarg)) {
        json_object_set_new(answer, "message", json_string("ipaddress is not an string"));
        return TM_ECODE_FAILED;
    }
    const char *ipaddress = json_string_value(jarg);

    Address a;
    struct in_addr in;
    memset(&in, 0, sizeof(in));
    if (inet_pton(AF_INET, ipaddress, &in) != 1) {
        uint32_t in6[4];
        memset(&in6, 0, sizeof(in6));
        if (inet_pton(AF_INET6, ipaddress, &in) != 1) {
            json_object_set_new(answer, "message", json_string("invalid address string"));
            return TM_ECODE_FAILED;
        } else {
            a.family = AF_INET6;
            a.addr_data32[0] = in6[0];
            a.addr_data32[1] = in6[1];
            a.addr_data32[2] = in6[2];
            a.addr_data32[3] = in6[3];
        }
    } else {
        a.family = AF_INET;
        a.addr_data32[0] = in.s_addr;
        a.addr_data32[1] = 0;
        a.addr_data32[2] = 0;
        a.addr_data32[3] = 0;
    }

    /* 2 get variable name */
    jarg = json_object_get(cmd, "hostbit");
    if (!json_is_string(jarg)) {
        json_object_set_new(answer, "message", json_string("hostbit is not a string"));
        return TM_ECODE_FAILED;
    }
    const char *hostbit = json_string_value(jarg);
    uint32_t idx = VarNameStoreLookupByName(hostbit, VAR_TYPE_HOST_BIT);
    if (idx == 0) {
        json_object_set_new(answer, "message", json_string("hostbit not found"));
        return TM_ECODE_FAILED;
    }

    /* 3 get expire */
    jarg = json_object_get(cmd, "expire");
    if (!json_is_integer(jarg)) {
        json_object_set_new(answer, "message", json_string("expire is not an integer"));
        return TM_ECODE_FAILED;
    }
    uint32_t expire = json_integer_value(jarg);

    SCLogInfo("add-hostbit: ip %s hostbit %s expire %us", ipaddress, hostbit, expire);

    SCTime_t current_time = TimeGet();
    Host *host = HostGetHostFromHash(&a);
    if (host) {
        HostBitSet(host, idx, SCTIME_SECS(current_time) + expire);
        HostUnlock(host);

        json_object_set_new(answer, "message", json_string("hostbit added"));
        return TM_ECODE_OK;
    } else {
        json_object_set_new(answer, "message", json_string("couldn't create host"));
        return TM_ECODE_FAILED;
    }
}

/**
 * \brief Command to remove a hostbit
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 */
TmEcode UnixSocketHostbitRemove(json_t *cmd, json_t* answer, void *data_unused)
{
    /* 1 get ip address */
    json_t *jarg = json_object_get(cmd, "ipaddress");
    if (!json_is_string(jarg)) {
        json_object_set_new(answer, "message", json_string("ipaddress is not an string"));
        return TM_ECODE_FAILED;
    }
    const char *ipaddress = json_string_value(jarg);

    Address a;
    struct in_addr in;
    memset(&in, 0, sizeof(in));
    if (inet_pton(AF_INET, ipaddress, &in) != 1) {
        uint32_t in6[4];
        memset(&in6, 0, sizeof(in6));
        if (inet_pton(AF_INET6, ipaddress, &in) != 1) {
            json_object_set_new(answer, "message", json_string("invalid address string"));
            return TM_ECODE_FAILED;
        } else {
            a.family = AF_INET6;
            a.addr_data32[0] = in6[0];
            a.addr_data32[1] = in6[1];
            a.addr_data32[2] = in6[2];
            a.addr_data32[3] = in6[3];
        }
    } else {
        a.family = AF_INET;
        a.addr_data32[0] = in.s_addr;
        a.addr_data32[1] = 0;
        a.addr_data32[2] = 0;
        a.addr_data32[3] = 0;
    }

    /* 2 get variable name */
    jarg = json_object_get(cmd, "hostbit");
    if (!json_is_string(jarg)) {
        json_object_set_new(answer, "message", json_string("hostbit is not a string"));
        return TM_ECODE_FAILED;
    }

    const char *hostbit = json_string_value(jarg);
    uint32_t idx = VarNameStoreLookupByName(hostbit, VAR_TYPE_HOST_BIT);
    if (idx == 0) {
        json_object_set_new(answer, "message", json_string("hostbit not found"));
        return TM_ECODE_FAILED;
    }

    SCLogInfo("remove-hostbit: %s %s", ipaddress, hostbit);

    Host *host = HostLookupHostFromHash(&a);
    if (host) {
        HostBitUnset(host, idx);
        HostUnlock(host);
        json_object_set_new(answer, "message", json_string("hostbit removed"));
        return TM_ECODE_OK;
    } else {
        json_object_set_new(answer, "message", json_string("host not found"));
        return TM_ECODE_FAILED;
    }
}

/**
 * \brief Command to list hostbits for an ip
 *
 * \param cmd the content of command Arguments as a json_t object
 * \param answer the json_t object that has to be used to answer
 *
 * Message looks like:
 * {"message": {"count": 1, "hostbits": [{"expire": 3222, "name": "firefox-users"}]}, "return": "OK"}
 *
 * \retval r TM_ECODE_OK or TM_ECODE_FAILED
 */
TmEcode UnixSocketHostbitList(json_t *cmd, json_t* answer, void *data_unused)
{
    /* 1 get ip address */
    json_t *jarg = json_object_get(cmd, "ipaddress");
    if (!json_is_string(jarg)) {
        json_object_set_new(answer, "message", json_string("ipaddress is not an string"));
        return TM_ECODE_FAILED;
    }
    const char *ipaddress = json_string_value(jarg);

    Address a;
    struct in_addr in;
    memset(&in, 0, sizeof(in));
    if (inet_pton(AF_INET, ipaddress, &in) != 1) {
        uint32_t in6[4];
        memset(&in6, 0, sizeof(in6));
        if (inet_pton(AF_INET6, ipaddress, &in) != 1) {
            json_object_set_new(answer, "message", json_string("invalid address string"));
            return TM_ECODE_FAILED;
        } else {
            a.family = AF_INET6;
            a.addr_data32[0] = in6[0];
            a.addr_data32[1] = in6[1];
            a.addr_data32[2] = in6[2];
            a.addr_data32[3] = in6[3];
        }
    } else {
        a.family = AF_INET;
        a.addr_data32[0] = in.s_addr;
        a.addr_data32[1] = 0;
        a.addr_data32[2] = 0;
        a.addr_data32[3] = 0;
    }

    SCLogInfo("list-hostbit: %s", ipaddress);

    SCTime_t ts = TimeGet();

    struct Bit {
        uint32_t id;
        uint32_t expire;
    } bits[256];
    memset(&bits, 0, sizeof(bits));
    int i = 0, use = 0;

    Host *host = HostLookupHostFromHash(&a);
    if (!host) {
        json_object_set_new(answer, "message", json_string("host not found"));
        return TM_ECODE_FAILED;
    }

    XBit *iter = NULL;
    while (use < 256 && HostBitList(host, &iter) == 1) {
        bits[use].id = iter->idx;
        bits[use].expire = iter->expire;
        use++;
    }
    HostUnlock(host);

    json_t *jdata = json_object();
    json_t *jarray = json_array();
    if (jarray == NULL || jdata == NULL) {
        if (jdata != NULL)
            json_decref(jdata);
        if (jarray != NULL)
            json_decref(jarray);
        json_object_set_new(answer, "message",
                            json_string("internal error at json object creation"));
        return TM_ECODE_FAILED;
    }

    for (i = 0; i < use; i++) {
        json_t *bitobject = json_object();
        if (bitobject == NULL)
            continue;
        uint32_t expire = 0;
        if ((uint32_t)SCTIME_SECS(ts) < bits[i].expire)
            expire = bits[i].expire - (uint32_t)SCTIME_SECS(ts);

        const char *name = VarNameStoreLookupById(bits[i].id, VAR_TYPE_HOST_BIT);
        if (name == NULL)
            continue;
        json_object_set_new(bitobject, "name", json_string(name));
        SCLogDebug("xbit %s expire %u", name, expire);
        json_object_set_new(bitobject, "expire", json_integer(expire));
        json_array_append_new(jarray, bitobject);
    }

    json_object_set_new(jdata, "count", json_integer(i));
    json_object_set_new(jdata, "hostbits", jarray);
    json_object_set_new(answer, "message", jdata);
    return TM_ECODE_OK;
}

static void MemcapBuildValue(uint64_t val, char *str, uint32_t str_len)
{
    if ((val / (1024 * 1024 * 1024)) != 0) {
        snprintf(str, str_len, "%"PRIu64"gb", val / (1024*1024*1024));
    } else if ((val / (1024 * 1024)) != 0) {
        snprintf(str, str_len, "%"PRIu64"mb", val / (1024*1024));
    } else {
        snprintf(str, str_len, "%"PRIu64"kb", val / (1024));
    }
}

TmEcode UnixSocketSetMemcap(json_t *cmd, json_t* answer, void *data)
{
    char *memcap = NULL;
    char *value_str = NULL;
    uint64_t value;
    int i;

    json_t *jarg = json_object_get(cmd, "config");
    if (!json_is_string(jarg)) {
        json_object_set_new(answer, "message", json_string("memcap key is not a string"));
        return TM_ECODE_FAILED;
    }
    memcap = (char *)json_string_value(jarg);

    jarg = json_object_get(cmd, "memcap");
    if (!json_is_string(jarg)) {
        json_object_set_new(answer, "message", json_string("memcap value is not a string"));
        return TM_ECODE_FAILED;
    }
    value_str = (char *)json_string_value(jarg);

    if (ParseSizeStringU64(value_str, &value) < 0) {
        SCLogError("Error parsing "
                   "memcap from unix socket: %s",
                value_str);
        json_object_set_new(answer, "message",
                            json_string("error parsing memcap specified, "
                                        "value not changed"));
        return TM_ECODE_FAILED;
    }

    for (i = 0; i < MEMCAPS_MAX; i++) {
        if (strcmp(memcaps[i].name, memcap) == 0 && memcaps[i].SetFunc) {
            int updated = memcaps[i].SetFunc(value);
            char message[150];

            if (updated) {
                snprintf(message, sizeof(message),
                "memcap value for '%s' updated: %"PRIu64" %s",
                memcaps[i].name, value,
                (value == 0) ? "(unlimited)" : "");
                json_object_set_new(answer, "message", json_string(message));
                return TM_ECODE_OK;
            } else {
                if (value == 0) {
                    snprintf(message, sizeof(message),
                             "Unlimited value is not allowed for '%s'", memcaps[i].name);
                } else {
                    if (memcaps[i].GetMemuseFunc()) {
                        char memuse[50];
                        MemcapBuildValue(memcaps[i].GetMemuseFunc(), memuse, sizeof(memuse));
                        snprintf(message, sizeof(message),
                                 "memcap value specified for '%s' is less than the memory in use: %s",
                                 memcaps[i].name, memuse);
                    } else {
                        snprintf(message, sizeof(message),
                                 "memcap value specified for '%s' is less than the memory in use",
                                 memcaps[i].name);
                    }
                }
                json_object_set_new(answer, "message", json_string(message));
                return TM_ECODE_FAILED;
            }
        }
    }

    json_object_set_new(answer, "message",
                        json_string("Memcap value not found. Use 'memcap-list' to show all"));
    return TM_ECODE_FAILED;
}

TmEcode UnixSocketShowMemcap(json_t *cmd, json_t *answer, void *data)
{
    char *memcap = NULL;
    int i;

    json_t *jarg = json_object_get(cmd, "config");
    if (!json_is_string(jarg)) {
        json_object_set_new(answer, "message", json_string("memcap name is not a string"));
        return TM_ECODE_FAILED;
    }
    memcap = (char *)json_string_value(jarg);

    for (i = 0; i < MEMCAPS_MAX; i++) {
        if (strcmp(memcaps[i].name, memcap) == 0 && memcaps[i].GetFunc) {
            char str[50];
            uint64_t val = memcaps[i].GetFunc();
            json_t *jobj = json_object();
            if (jobj == NULL) {
                json_object_set_new(answer, "message",
                                json_string("internal error at json object creation"));
                return TM_ECODE_FAILED;
            }

            if (val == 0) {
                strlcpy(str, "unlimited", sizeof(str));
            } else {
                MemcapBuildValue(val, str, sizeof(str));
            }

            json_object_set_new(jobj, "value", json_string(str));
            json_object_set_new(answer, "message", jobj);
            return TM_ECODE_OK;
        }
    }

    json_object_set_new(answer, "message",
                        json_string("Memcap value not found. Use 'memcap-list' to show all"));
    return TM_ECODE_FAILED;
}

TmEcode UnixSocketShowAllMemcap(json_t *cmd, json_t *answer, void *data)
{
    json_t *jmemcaps = json_array();
    int i;

    if (jmemcaps == NULL) {
        json_object_set_new(answer, "message",
                            json_string("internal error at json array creation"));
        return TM_ECODE_FAILED;
    }

    for (i = 0; i < MEMCAPS_MAX; i++) {
        json_t *jobj = json_object();
        if (jobj == NULL) {
            json_decref(jmemcaps);
            json_object_set_new(answer, "message",
                                json_string("internal error at json object creation"));
            return TM_ECODE_FAILED;
        }
        char str[50];
        uint64_t val = memcaps[i].GetFunc();

        if (val == 0) {
            strlcpy(str, "unlimited", sizeof(str));
        } else {
            MemcapBuildValue(val, str, sizeof(str));
        }

        json_object_set_new(jobj, "name", json_string(memcaps[i].name));
        json_object_set_new(jobj, "value", json_string(str));
        json_array_append_new(jmemcaps, jobj);
    }

    json_object_set_new(answer, "message", jmemcaps);
    SCReturnInt(TM_ECODE_OK);
}

TmEcode UnixSocketGetFlowStatsById(json_t *cmd, json_t *answer, void *data)
{
    /* Input: we need the IP tuple including VLAN/tenant and the flow ID */
    json_t *jarg = json_object_get(cmd, "flow_id");
    if (!json_is_integer(jarg)) {
        SCLogInfo("error: command is not a string");
        json_object_set_new(answer, "message", json_string("flow_id is not an integer"));
        return TM_ECODE_FAILED;
    }
    int64_t flow_id = json_integer_value(jarg);

    Flow *f = FlowGetExistingFlowFromFlowId(flow_id);
    if (f == NULL) {
        json_object_set_new(answer, "message", json_string("Not found"));
        SCReturnInt(TM_ECODE_FAILED);
    }
    uint32_t tosrcpktcnt = f->tosrcpktcnt;
    uint32_t todstpktcnt = f->todstpktcnt;
    uint64_t tosrcbytecnt = f->tosrcbytecnt;
    uint64_t todstbytecnt = f->todstbytecnt;
    uint64_t age = SCTIME_SECS(f->lastts) - SCTIME_SECS(f->startts);
    FLOWLOCK_UNLOCK(f);

    json_t *flow_info = json_object();
    if (flow_info == NULL) {
        SCReturnInt(TM_ECODE_FAILED);
    }
    json_object_set_new(flow_info, "pkts_toclient", json_integer(tosrcpktcnt));
    json_object_set_new(flow_info, "pkts_toserver", json_integer(todstpktcnt));
    json_object_set_new(flow_info, "bytes_toclient", json_integer(tosrcbytecnt));
    json_object_set_new(flow_info, "bytes_toserver", json_integer(todstbytecnt));
    json_object_set_new(flow_info, "age", json_integer(age));
    json_object_set_new(answer, "message", flow_info);
    SCReturnInt(TM_ECODE_OK);
}
#endif /* BUILD_UNIX_SOCKET */

#ifdef BUILD_UNIX_SOCKET
/**
 * \brief Single thread version of the Pcap file processing.
 */
static int RunModeUnixSocketMaster(void)
{
    if (UnixManagerInit() != 0)
        return 1;

    PcapCommand *pcapcmd = SCMalloc(sizeof(PcapCommand));
    if (unlikely(pcapcmd == NULL)) {
        SCLogError("Can not allocate pcap command");
        return 1;
    }
    TAILQ_INIT(&pcapcmd->files);
    pcapcmd->running = 0;
    pcapcmd->current_file = NULL;

    memset(&unix_manager_pcap_last_processed, 0, sizeof(struct timespec));

    SCCtrlMutexInit(&unix_manager_pcap_last_processed_mutex, NULL);

    UnixManagerRegisterCommand("pcap-file", UnixSocketAddPcapFile, pcapcmd, UNIX_CMD_TAKE_ARGS);
    UnixManagerRegisterCommand("pcap-file-continuous", UnixSocketAddPcapFileContinuous, pcapcmd, UNIX_CMD_TAKE_ARGS);
    UnixManagerRegisterCommand("pcap-file-number", UnixSocketPcapFilesNumber, pcapcmd, 0);
    UnixManagerRegisterCommand("pcap-file-list", UnixSocketPcapFilesList, pcapcmd, 0);
    UnixManagerRegisterCommand("pcap-last-processed", UnixSocketPcapLastProcessed, pcapcmd, 0);
    UnixManagerRegisterCommand("pcap-interrupt", UnixSocketPcapInterrupt, pcapcmd, 0);
    UnixManagerRegisterCommand("pcap-current", UnixSocketPcapCurrent, pcapcmd, 0);

    UnixManagerRegisterBackgroundTask(UnixSocketPcapFilesCheck, pcapcmd);

    UnixManagerThreadSpawn(1);
    unix_socket_mode_is_running = 1;

    return 0;
}
#endif

int RunModeUnixSocketIsActive(void)
{
    return unix_socket_mode_is_running;
}