-
-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathargs.c
More file actions
1824 lines (1646 loc) · 62.1 KB
/
Copy pathargs.c
File metadata and controls
1824 lines (1646 loc) · 62.1 KB
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
/* Pi-hole: A black hole for Internet advertisements
* (c) 2017 Pi-hole, LLC (https://pi-hole.net)
* Network-wide ad blocking via your own hardware.
*
* FTL Engine
* Argument parsing routines
*
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
// DNSMASQ COPYRIGHT
#define FTLDNS
#include "dnsmasq/dnsmasq.h"
#undef __USE_XOPEN
#include <nettle/bignum.h>
#if !defined(NETTLE_VERSION_MAJOR)
# define NETTLE_VERSION_MAJOR 2
# define NETTLE_VERSION_MINOR 0
#endif
#ifdef HAVE_TLS
/*
* dnsmasq.h (included above) defines common allocator names like `free` and
* `strdup` as macros expanding to FTL's tracked wrappers. If still active while
* the OpenSSL headers are included, they get expanded inside OpenSSL's
* declarations/inline functions and produce invalid code (the exact breakage
* depends on the OpenSSL version). Undefine them around the includes and
* restore afterwards - the same protection src/FTL.h applies to its own system
* headers.
*/
#ifdef __GNUC__
#pragma push_macro("free")
#pragma push_macro("strdup")
#undef free
#undef strdup
#endif
#include <openssl/opensslv.h>
#include <openssl/crypto.h>
#include <openssl/provider.h>
#ifdef __GNUC__
#pragma pop_macro("strdup")
#pragma pop_macro("free")
#endif
#endif
#include "FTL.h"
#include "args.h"
#include "version.h"
#include "main.h"
#include "log.h"
// global variable killed
#include "signals.h"
// regex_speedtest()
#include "regex_r.h"
// init_shmem()
#include "shmem.h"
// LUA dependencies
#include "lua/ftl_lua.h"
// gravity_parseList()
#include "tools/gravity-parseList.h"
// run_dhcp_discover()
#include "tools/dhcp-discover.h"
// mg_version()
#include "webserver/civetweb/civetweb.h"
// webserver_have_http2()/webserver_have_http3() for the --version report
#include "webserver/webserver.h"
// cJSON_Version()
#include "webserver/cJSON/cJSON.h"
#include "config/cli.h"
#include "config/config.h"
// compression functions
#include "zip/gzip.h"
// teleporter functions
#include "zip/teleporter.h"
// printTOTP()
#include "api/api.h"
// generate_certificate()
#include "webserver/x509.h"
// run_dhcp_discover()
#include "tools/dhcp-discover.h"
// run_arp_scan()
#include "tools/arp-scan.h"
// run_performance_test()
#include "config/password.h"
// idn2_to_ascii_lz()
#include <idn2.h>
// sha256sum()
#include "files.h"
// resolveHostname()
#include "resolve.h"
// ntp_client()
#include "ntp/ntp.h"
// check_capability()
#include "capabilities.h"
// get_gateway_name()
#include "tools/netlink.h"
// wait_for_string_in_file()
#include "config/inotify.h"
// get_all_supported_ciphersuites()
#include "webserver/webserver.h"
// mmap(), PROT_NONE, MAP_PRIVATE, MAP_ANONYMOUS — used for intentional crash
// test
#include <sys/mman.h>
// defined in dnsmasq.c
extern void print_dnsmasq_version(const char *yellow, const char *green, const char *bold, const char *normal);
// defined in database/shell.c
extern int sqlite3_shell_main(int argc, char **argv);
// defined in database/sqlite3_rsync.c
extern int sqlite3_rsync_main(int argc, char **argv);
bool debug_mode = false;
bool daemonmode = true, cli_mode = false;
int argc_dnsmasq = 0;
const char** argv_dnsmasq = NULL;
// Prototypes
static void suggest_complete(const int argc, char *argv[]);
static bool __attribute__ ((pure)) is_term(void)
{
// test whether STDOUT refers to a terminal or if env variable
// FORCE_COLOR is set
return getenv("FORCE_COLOR") != NULL || isatty(fileno(stdout)) == 1;
}
// Returns green [✓]
const char __attribute__ ((pure)) *cli_tick(void)
{
return is_term() ? "["COL_GREEN"✓"COL_NC"]" : "[✓]";
}
// Returns red [✗]
const char __attribute__ ((pure)) *cli_cross(void)
{
return is_term() ? "["COL_RED"✗"COL_NC"]" : "[✗]";
}
// Returns [i]
const char __attribute__ ((pure)) *cli_info(void)
{
return is_term() ? COL_BOLD"[i]"COL_NC : "[i]";
}
// Returns [?]
const char __attribute__ ((const)) *cli_qst(void)
{
return "[?]";
}
// Returns green "done!""
const char __attribute__ ((pure)) *cli_done(void)
{
return is_term() ? COL_GREEN"done!"COL_NC : "done!";
}
// Sets font to bold
const char __attribute__ ((pure)) *cli_bold(void)
{
return is_term() ? COL_BOLD : "";
}
const char __attribute__ ((pure)) *cli_underline(void)
{
return is_term() ? COL_ULINE : "";
}
const char __attribute__ ((pure)) *cli_italics(void)
{
return is_term() ? COL_ITALIC : "";
}
// Resets font to normal
const char __attribute__ ((pure)) *cli_normal(void)
{
return is_term() ? COL_NC : "";
}
// Set color if STDOUT is a terminal
const char __attribute__ ((pure)) *cli_color(const char *color)
{
return is_term() ? color : "";
}
// Go back to beginning of line and erase to end of line if STDOUT is a terminal
const char __attribute__ ((pure)) *cli_over(void)
{
// \x1b[K is the ANSI escape sequence for "erase to end of line"
return is_term() ? CLI_OVER : "\r";
}
/**
* @brief Checks if a given string ends with a specified substring.
*
* This function determines whether the string pointed to by @p input ends with the substring pointed to by @p end.
*
* @param input The input string to check.
* @param end The substring to check for at the end of @p input.
* @return true if @p input ends with @p end, false otherwise.
*/
static bool strEndsWith(const char *input, const char *end)
{
const size_t input_len = strlen(input);
const size_t end_len = strlen(end);
// If the input is shorter than the end, it cannot end with it
if(input_len < end_len)
return false;
return strcmp(input + input_len - end_len, end) == 0;
}
/**
* @brief Checks if a given string starts with a specified prefix.
*
* This function compares the beginning of the input string with the start string.
* It returns true if the input string starts with the prefix specified by start.
*
* @param input The string to check.
* @param start The prefix to look for at the beginning of input.
* @return true if input starts with start, false otherwise.
*/
static bool strStartsWith(const char *input, const char *start)
{
return strncmp(input, start, strlen(start)) == 0;
}
/**
* @brief Checks if a string starts with a given prefix, ignoring case.
*
* This function compares the beginning of the input string with the specified
* prefix (start), ignoring the case of the characters. It returns true if the
* input string starts with the prefix, false otherwise.
*
* @param input The input string to check.
* @param start The prefix to look for at the start of the input string.
* @return true if input starts with start (case-insensitive), false otherwise.
*/
static bool strStartsWithIgnoreCase(const char *input, const char *start)
{
return strncasecmp(input, start, strlen(start)) == 0;
}
#ifdef HAVE_TLS
// Return the value part of an OpenSSL_version() string, skipping the leading
// "label: " prefix that most of them carry (e.g. "built on: <date>").
static const char *openssl_value(const char *s)
{
const char *sep = strstr(s, ": ");
return sep != NULL ? sep + 2 : s;
}
#endif
void parse_args(int argc, char *argv[])
{
bool quiet = false;
// Regardless of any arguments, we always pass "-k" (nofork) to dnsmasq
argc_dnsmasq = 3;
argv_dnsmasq = calloc(argc_dnsmasq, sizeof(char*));
argv_dnsmasq[0] = "";
argv_dnsmasq[1] = "-k";
argv_dnsmasq[2] = "";
bool consume_for_dnsmasq = false;
// If the binary name is "dnsmasq" (e.g., symlink /usr/bin/dnsmasq -> /usr/bin/pihole-FTL),
// we operate in drop-in mode and consume all arguments for the embedded dnsmasq core
if(strEndsWith(argv[0], "dnsmasq"))
consume_for_dnsmasq = true;
// If the binary name is "lua" (e.g., symlink /usr/bin/lua -> /usr/bin/pihole-FTL),
// we operate in drop-in mode and consume all arguments for the embedded lua engine
// Also, we do this if the first argument is a file with ".lua" ending
if(strEndsWith(argv[0], "lua") ||
(argc > 1 && strEndsWith(argv[1], ".lua")))
exit(run_lua_interpreter(argc, argv, false));
// If the binary name is "luac" (e.g., symlink /usr/bin/luac -> /usr/bin/pihole-FTL),
// we operate in drop-in mode and consume all arguments for the embedded luac engine
if(strEndsWith(argv[0], "luac"))
exit(run_luac(argc, argv));
// Special (undocumented) mode to test kernel signal handling
if(argc == 2 && strcmp(argv[1], "sigtest") == 0)
exit(sigtest());
// Print the value of SIGRTMIN, for use in the scripts to avoid issues
// caused by its inconsistent value across environments
if(argc == 2 && strcmp(argv[1], "sigrtmin") == 0)
exit(sigrtmin());
// Intentional crash test — used in CI to verify the crash handler and
// backtrace machinery work correctly.
// We use mmap(PROT_NONE) + a write to produce SIGSEGV SEGV_ACCERR.
// This is NOT undefined behaviour, NOT elided by the optimiser, and NOT
// intercepted by ASan or UBSan — unlike a raw null/invalid-pointer cast.
// handle_signals() and init_backtrace() are called here explicitly
// because parse_args() runs before main() sets them up.
if(argc == 2 && strcmp(argv[1], "crash") == 0)
{
cli_mode = true;
log_ctrl(false, true);
config.misc.addr2line.v.b = true; // Enable addr2line — config not loaded in subcommand context
handle_signals();
void *addr = mmap(NULL, 4096u, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if(addr != MAP_FAILED)
{
volatile char *ptr = (volatile char *)addr;
*ptr = 'x'; // Write to PROT_NONE page — SIGSEGV SEGV_ACCERR
}
raise(SIGSEGV); // Fallback: mmap should never fail in practice
exit(EXIT_FAILURE);
}
// Generate a backtrace without crashing — useful for manual inspection
// of the backtrace output on a given build/platform.
if(argc == 2 && strcmp(argv[1], "backtrace") == 0)
{
cli_mode = true;
log_ctrl(false, true);
config.misc.addr2line.v.b = true; // Enable addr2line — config not loaded in subcommand context
generate_backtrace();
exit(EXIT_SUCCESS);
}
// If the binary name is "sqlite3" (e.g., symlink /usr/bin/sqlite3 -> /usr/bin/pihole-FTL),
// we operate in drop-in mode and consume all arguments for the embedded SQLite3 engine
// Also, we do this if the first argument is a file with ".db" ending
if(strEndsWith(argv[0], "sqlite3") ||
(argc > 1 && strEndsWith(argv[1], ".db")))
exit(sqlite3_shell_main(argc, argv));
// If the binary name is "sqlite3_rsync" (e.g., symlink /usr/bin/sqlite3_rsync -> /usr/bin/pihole-FTL),
// we operate in drop-in mode and consume all arguments for the embedded sqlite3_rsync tool
if(strEndsWith(argv[0], "sqlite3_rsync"))
exit(sqlite3_rsync_main(argc, argv));
if(argc > 1 && strcmp(argv[1], "--complete") == 0)
suggest_complete(argc, argv);
// Compression feature
if((argc == 3 || argc == 4) &&
(strcmp(argv[1], "gzip") == 0 || strcmp(argv[1], "--gzip") == 0))
{
// Enable stdout printing
cli_mode = true;
log_ctrl(false, true);
// Get input and output file names
const char *infile = argv[2];
bool is_gz = strEndsWith(infile, ".gz");
char *outfile = NULL;
if(argc == 4)
{
// If an output file is given, we use it
outfile = strdup(argv[3]);
}
else if(is_gz)
{
// If no output file is given, and this is a gzipped
// file, we use the input file name without ".gz"
// appended
outfile = calloc(strlen(infile)-2, sizeof(char));
memcpy(outfile, infile, strlen(infile)-3);
}
else
{
// If no output file is given, and this is not a gzipped
// file, we use the input file name with ".gz" appended
outfile = calloc(strlen(infile)+4, sizeof(char));
strcpy(outfile, infile);
strcat(outfile, ".gz");
}
bool success = false;
if(is_gz)
{
// If the input file is already gzipped, we decompress it
success = inflate_file(infile, outfile, true);
}
else
{
// If the input file is not gzipped, we compress it
success = deflate_file(infile, outfile, true);
}
// Free allocated memory
free(outfile);
// Return exit code
exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
}
// Set config option through CLI
if(argc > 1 && strcmp(argv[1], "--config") == 0)
{
// Enable stdout printing
cli_mode = true;
log_ctrl(false, false);
const bool conf_read = readFTLconf(&config, false);
log_ctrl(false, true);
clear_debug_flags(); // No debug printing wanted
// When querying (not setting) a config value, warn the user if the
// value we are about to print may not reflect the current
// configuration. This happens when the primary config file exists
// but cannot be read - most commonly because the command is run
// without sudo as a user that is not allowed to read pihole.toml
// (which is installed mode 0640 owned by pihole:pihole). In that
// case, FTL silently falls back to a config backup or, if none can
// be read either, to the compiled-in defaults. We warn on stderr so
// the (possibly stale or default) value can still be consumed on
// stdout (see GitHub issue #2849).
const bool querying = argc == 2 || argc == 3 ||
(argc == 4 && strcmp(argv[2], "-q") == 0);
if(querying && file_exists(GLOBALTOMLPATH))
{
if(access(GLOBALTOMLPATH, R_OK) != 0)
{
const int err = errno;
fprintf(stderr, "Warning: %s exists but cannot be read (%s).\n"
" The value shown below may not reflect the current configuration.\n",
GLOBALTOMLPATH, strerror(err));
// Only suggest sudo for permission-related errors; other
// failures (e.g. I/O errors) are not fixed by elevated
// privileges.
if(err == EACCES || err == EPERM)
fprintf(stderr, " Try running this command with sudo.\n");
}
else if(!conf_read)
fprintf(stderr, "Warning: %s could not be parsed.\n"
" The value shown below may not reflect the current configuration.\n",
GLOBALTOMLPATH);
}
if(argc == 2)
exit(get_config_from_CLI(NULL, false));
else if(argc == 3)
exit(get_config_from_CLI(argv[2], false));
else if(argc == 4 && strcmp(argv[2], "-q") == 0)
exit(get_config_from_CLI(argv[3], true));
else if(argc == 4)
exit(set_config_from_CLI(argv[2], argv[3]));
else
{
printf("Usage: %s --config [<config item key>] [<value>]\n", argv[0]);
printf("Example: %s --config dns.CNAMEdeepInspect true\n", argv[0]);
exit(EXIT_FAILURE);
}
}
// Set config option through CLI
if(argc == 2 && strcmp(argv[1], "--totp") == 0)
{
cli_mode = true;
log_ctrl(false, false);
readFTLconf(&config, false);
log_ctrl(false, true);
clear_debug_flags(); // No debug printing wanted
exit(printTOTP());
}
// Create teleporter archive through CLI
if(argc == 2 && strcmp(argv[1], "--teleporter") == 0)
{
// Enable stdout printing
cli_mode = true;
log_ctrl(false, true);
readFTLconf(&config, false);
exit(write_teleporter_zip_to_disk() ? EXIT_SUCCESS : EXIT_FAILURE);
}
// Create test NTP client
if((argc > 1 && argc < 5) && strcmp(argv[1], "ntp") == 0)
{
// Parse arguments
const bool update = (argc > 2 && strcmp(argv[2], "--update") == 0) ||
(argc > 3 && strcmp(argv[3], "--update") == 0);
const char *server = "127.0.0.1";
if(argc > 2 && strcmp(argv[2], "--update") != 0)
server = argv[2];
// Ensure we have the necessary capabilities
if(update && !check_capability(CAP_SYS_TIME))
{
puts("Insufficient capabilities to run NTP client");
const char *bold = cli_bold();
const char *normal = cli_normal();
printf("Try: %ssudo%s ", bold, normal);
for(int i = 0; i < argc; i++)
printf("%s ", argv[i]);
puts("");
exit(EXIT_FAILURE);
}
printf("Using NTP server: %s\n", server);
// Enable stdout printing
cli_mode = true;
log_ctrl(false, true);
readFTLconf(&config, false);
exit(ntp_client(server, update, true) ? EXIT_SUCCESS : EXIT_FAILURE);
}
// Import teleporter archive through CLI
if(argc == 3 && strcmp(argv[1], "--teleporter") == 0)
{
// Enable stdout printing
cli_mode = true;
log_ctrl(false, true);
readFTLconf(&config, false);
exit(read_teleporter_zip_from_disk(argv[2]) ? EXIT_SUCCESS : EXIT_FAILURE);
}
// Generate X.509 certificate
if(argc > 1 && strcmp(argv[1], "--gen-x509") == 0)
{
#ifdef HAVE_TLS
if(argc < 3 || argc > 5)
{
printf("Usage: %s --gen-x509 <output file> [<domain>] [rsa]\n", argv[0]);
printf("Example: %s --gen-x509 /etc/pihole/tls.pem\n", argv[0]);
printf(" with domain: %s --gen-x509 /etc/pihole/tls.pem pi.hole\n", argv[0]);
printf(" RSA with domain: %s --gen-x509 /etc/pihole/tls.pem nanopi.lan rsa\n", argv[0]);
exit(EXIT_FAILURE);
}
// Read config
readFTLconf(&config, false);
// Enable stdout printing
cli_mode = true;
log_ctrl(false, true);
const char *domain = argc > 3 ? argv[3] : "pi.hole";
const bool rsa = argc > 4 && strcasecmp(argv[4], "rsa") == 0;
exit(generate_certificate(argv[2], rsa, domain, config.webserver.tls.validity.v.ui) ? EXIT_SUCCESS : EXIT_FAILURE);
#else
printf("Error: FTL was compiled without TLS support. Certificate generation is not available.\n");
exit(EXIT_FAILURE);
#endif
}
// Parse X.509 certificate
if(argc > 1 &&
(strcmp(argv[1], "--read-x509") == 0 ||
strcmp(argv[1], "--read-x509-key") == 0))
{
#ifdef HAVE_TLS
if(argc > 4)
{
printf("Usage: %s %s [<input file>] [<domain>]\n", argv[0], argv[1]);
printf("Example: %s %s /etc/pihole/tls.pem\n", argv[0], argv[1]);
printf(" with domain: %s %s /etc/pihole/tls.pem pi.hole\n", argv[0], argv[1]);
exit(EXIT_FAILURE);
}
// Option parsing
// Should we report on the private key?
const bool private_key = strcmp(argv[1], "--read-x509-key") == 0;
// If no certificate file is given, we use the one from the config
const char *certfile = NULL;
if(argc == 2)
{
readFTLconf(&config, false);
certfile = config.webserver.tls.cert.v.s;
}
else
certfile = argv[2];
// If no domain is given, we only check the certificate
const char *domain = argc > 3 ? argv[3] : NULL;
// Enable stdout printing
cli_mode = true;
log_ctrl(false, true);
enum cert_check result = read_certificate(certfile, domain, private_key);
if(argc < 4)
exit(result == CERT_OKAY ? EXIT_SUCCESS : EXIT_FAILURE);
else if(result == CERT_DOMAIN_MATCH)
{
printf("Certificate matches domain %s\n", argv[3]);
exit(EXIT_SUCCESS);
}
else
{
printf("Certificate does not match domain %s\n", argv[3]);
exit(EXIT_FAILURE);
}
#else
printf("Error: FTL was compiled without TLS support. Certificate reading is not available.\n");
exit(EXIT_FAILURE);
#endif
}
// If the first argument is "gravity" (e.g., /usr/bin/pihole-FTL gravity),
// we offer some specialized gravity tools
if(argc > 1 && (strcmp(argv[1], "gravity") == 0 || strcmp(argv[1], "antigravity") == 0))
{
const bool antigravity = strcmp(argv[1], "antigravity") == 0;
// pihole-FTL gravity parseList <infile> <outfile> <adlistID>
if(argc == 6 && strcasecmp(argv[2], "parseList") == 0)
{
// Parse the given list and write the result to the given file
exit(gravity_parseList(argv[3], argv[4], argv[5], false, antigravity));
}
// pihole-FTL gravity checkList <infile>
if(argc == 4 && strcasecmp(argv[2], "checkList") == 0)
{
// Parse the given list and write the result to the given file
exit(gravity_parseList(argv[3], "", "-1", true, antigravity));
}
printf("Incorrect usage of pihole-FTL gravity subcommand\n");
exit(EXIT_FAILURE);
}
// DHCP discovery mode
if(argc > 1 && strcmp(argv[1], "dhcp-discover") == 0)
{
// Enable stdout printing
cli_mode = true;
exit(run_dhcp_discover());
}
// Password hashing performance test
if(argc > 1 && (strcmp(argv[1], "--perf") == 0 || strcmp(argv[1], "performance") == 0))
{
// Enable stdout printing
cli_mode = true;
exit(run_performance_test());
}
// ARP scanning mode
if(argc > 1 && strcmp(argv[1], "arp-scan") == 0)
{
// Enable stdout printing
cli_mode = true;
const bool scan_all = argc > 2 && strcmp(argv[2], "-a") == 0;
const bool extreme_mode = argc > 2 && strcmp(argv[2], "-x") == 0;
exit(run_arp_scan(scan_all, extreme_mode));
}
// IDN2 conversion mode
if(argc > 1 && strcmp(argv[1], "idn2") == 0)
{
// Enable stdout printing
cli_mode = true;
if(argc == 3)
{
// Convert unicode domain to punycode
char *punycode = NULL;
const int rc = idn2_to_ascii_lz(argv[2], &punycode, IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL);
if (rc != IDN2_OK)
{
// Invalid domain name
printf("Invalid domain name: %s\n", argv[2]);
exit(EXIT_FAILURE);
}
// Convert punycode domain to lowercase
for(unsigned int i = 0u; i < strlen(punycode); i++)
punycode[i] = tolower(punycode[i]);
printf("%s\n", punycode);
exit(EXIT_SUCCESS);
}
else if(argc == 4 && (strcmp(argv[2], "-d") == 0 || strcmp(argv[2], "--decode") == 0))
{
// Convert punycode domain to unicode
char *unicode = NULL;
const int rc = idn2_to_unicode_lzlz(argv[3], &unicode, IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL);
if (rc != IDN2_OK)
{
// Invalid domain name
printf("Invalid domain name: %s\n", argv[3]);
exit(EXIT_FAILURE);
}
printf("%s\n", unicode);
exit(EXIT_SUCCESS);
}
else
{
printf("Usage: %s idn2 [--decode] <domain>\n", argv[0]);
exit(EXIT_FAILURE);
}
}
// sha256sum mode
if(argc == 3 && strcmp(argv[1], "sha256sum") == 0)
{
// Enable stdout printing
cli_mode = true;
uint8_t checksum[SHA256_DIGEST_SIZE];
if(!sha256sum(argv[2], checksum, false))
exit(EXIT_FAILURE);
// Convert checksum to hex string
char hex[SHA256_DIGEST_SIZE*2+1];
sha256_raw_to_hex(checksum, hex);
// Print result
printf("%s %s\n", hex, argv[2]);
exit(EXIT_SUCCESS);
}
// Checksum verification mode
if(argc == 2 && strcmp(argv[1], "verify") == 0)
{
// Enable stdout printing
cli_mode = true;
const enum verify_result match = verify_FTL(true);
printf("%s Binary integrity check: %s\n",
match == VERIFY_OK ? cli_tick() :
match == VERIFY_NO_CHECKSUM ? cli_qst() : cli_cross(),
match == VERIFY_OK ? "OK" :
match == VERIFY_NO_CHECKSUM ? "No checksum found" :
match == VERIFY_ERROR ? "Error" : "Failed");
exit(match);
}
// Local reverse name resolver
if((argc == 3 || argc == 4) && strcasecmp(argv[1], "ptr") == 0)
{
// Enable stdout printing
cli_mode = true;
// Need to get dns.port and the resolver settings
readFTLconf(&config, false);
// TCP or UDP (default)?
const bool tcp = argc == 4 && strcasecmp(argv[3], "tcp") == 0;
// Create a socket
struct sockaddr_in dest;
const int sock = create_socket(tcp, &dest);
char hostn[MAXDOMAINLEN] = { 0 };
if(!resolveHostname(sock, tcp, &dest, hostn, argv[2], true, NULL))
{
// Close the socket
close(sock);
exit(EXIT_FAILURE);
}
// Close the socket
close(sock);
// Print result
printf("%s\n", hostn);
exit(EXIT_SUCCESS);
}
// Set config option through CLI
if(argc == 3 && strcmp(argv[1], "migrate") == 0 && strcmp(argv[2], "v6") == 0)
{
cli_mode = true;
log_ctrl(false, true);
exit(migrate_config_v6() ? EXIT_SUCCESS : EXIT_FAILURE);
}
// Get name of the default gateway
if(argc == 2 && strcmp(argv[1], "--default-gateway") == 0)
{
cli_mode = true;
char gateway[MAXIFACESTRLEN];
get_gateway_name(gateway);
printf("%s\n", gateway);
exit(EXIT_SUCCESS);
}
// Undocumented option to create an all-default dummy config file
if(argc == 3 && strcmp(argv[1], "create-default-config") == 0)
{
// Enable stdout printing
cli_mode = true;
log_ctrl(false, true);
// Validate the output filename
if(strstr(argv[2], "..") || strchr(argv[2], '/') || strchr(argv[2], '\\'))
{
fprintf(stderr, "Error: Invalid filename. Path traversal or special characters are not allowed.\n");
exit(EXIT_FAILURE);
}
// Create the default config file
if(create_default_config(argv[2]))
exit(EXIT_SUCCESS);
else
exit(EXIT_FAILURE);
}
// Check file for given string
// pihole-FTL wait-for <string> <file> <timeout> [<initial_filesize>]
// Example: pihole-FTL wait-for "DNS service is running" /var/log/pihole/FTL.log 30
// This will check /var/log/pihole/FTL.log for the string "DNS service is running"
if((argc == 5 || argc == 6) && strcmp(argv[1], "wait-for") == 0)
{
// Enable stdout printing
cli_mode = true;
log_ctrl(false, true);
const int timeout = atoi(argv[4]);
if(timeout < 0)
{
fprintf(stderr, "Error: Timeout must be a non-negative integer.\n");
exit(EXIT_FAILURE);
}
const long initial_filesize = (argc == 6) ? (long)atol(argv[5]) : -1;
if(argc == 6 && initial_filesize < 0)
{
fprintf(stderr, "Error: Optional initial file size must be a non-negative integer if specified.\n");
exit(EXIT_FAILURE);
}
exit(wait_for_string_in_file(argv[3], argv[2], (unsigned int)timeout, initial_filesize) ? EXIT_SUCCESS : EXIT_FAILURE);
}
if(argc == 2 && strcmp(argv[1], "--tls-ciphers") == 0)
{
cli_mode = true;
log_ctrl(false, true);
get_all_supported_ciphersuites();
exit(EXIT_SUCCESS);
}
// start from 1, as argv[0] is the executable name
for(int i = 1; i < argc; i++)
{
bool ok = false;
// Expose internal lua interpreter
if(strcmp(argv[i], "lua") == 0 ||
strcmp(argv[i], "--lua") == 0)
{
exit(run_lua_interpreter(argc - i, &argv[i], debug_mode));
}
// Expose internal lua compiler
if(strcmp(argv[i], "luac") == 0 ||
strcmp(argv[i], "--luac") == 0)
{
exit(luac_main(argc - i, &argv[i]));
}
// Expose embedded SQLite3 engine
if(strcmp(argv[i], "sql") == 0 ||
strcmp(argv[i], "sqlite3") == 0 ||
strcmp(argv[i], "--sqlite3") == 0)
{
// Human-readable table output mode
if(i+1 < argc && strcmp(argv[i+1], "-h") == 0)
{
int argc2 = argc - i + 5 - 2;
char **argv2 = calloc(argc2, sizeof(char*));
argv2[0] = argv[0]; // Application name
argv2[1] = (char*)"-column";
argv2[2] = (char*)"-header";
argv2[3] = (char*)"-nullvalue";
argv2[4] = (char*)"(null)";
// i = "sqlite3"
// i+1 = "-h"
for(int j = 0; j < argc - i - 2; j++)
argv2[5 + j] = argv[i + 2 + j];
exit(sqlite3_shell_main(argc2, argv2));
}
// Special non-interative mode
else if(i+1 < argc && strcmp(argv[i+1], "-ni") == 0)
{
int argc2 = argc - i + 4 - 2;
char **argv2 = calloc(argc2, sizeof(char*));
argv2[0] = argv[0]; // Application name
argv2[1] = (char*)"-batch";
argv2[2] = (char*)"-init";
argv2[3] = (char*)"/dev/null";
// i = "sqlite3"
// i+1 = "-ni"
for(int j = 0; j < argc - i - 2; j++)
argv2[4 + j] = argv[i + 2 + j];
exit(sqlite3_shell_main(argc2, argv2));
}
else
exit(sqlite3_shell_main(argc - i, &argv[i]));
}
if(strcmp(argv[i], "sqlite3_rsync") == 0 ||
strcmp(argv[i], "--sqlite3_rsync") == 0)
{
exit(sqlite3_rsync_main(argc - i, &argv[i]));
}
// Implement dnsmasq's test function, no need to prepare the entire FTL
// environment (initialize shared memory, load queries from long-term
// database, ...) when the task is a simple (dnsmasq) syntax check
if(strcmp(argv[i], "dnsmasq-test") == 0 ||
strcmp(argv[i], "--test") == 0)
{
const char *arg[2];
arg[0] = "";
arg[1] = "--test";
log_ctrl(false, true);
// Signal dnsmasq's die() to exit() instead of trying to
// jump back into FTL's main() via longjmp(exit_jmp, ...).
// exit_jmp is only initialized (setjmp) once we reach
// main(), which never happens on this early-exit path, so
// a config read error (e.g., permission denied) would
// otherwise longjmp through an uninitialized jmp_buf and
// crash (see https://github.com/pi-hole/FTL/issues/2924).
only_testing = true;
exit(main_dnsmasq(2, (char**)arg));
}
// Implement dnsmasq's test function, no need to prepare the entire FTL
// environment (initialize shared memory, lead queries from long-term
// database, ...) when the task is a simple (dnsmasq) syntax check
if(argc == 3 && strcmp(argv[1], "dnsmasq-test-file") == 0)
{
const char *arg[3];
char *filename = calloc(strlen(argv[2])+strlen("--conf-file=")+1, sizeof(char));
arg[0] = "";
sprintf(filename, "--conf-file=%s", argv[2]);
arg[1] = filename;
arg[2] = "--test";
log_ctrl(false, true);
// See note above: ensure die() exit()s cleanly instead of
// longjmp()ing through an uninitialized exit_jmp.
only_testing = true;
exit(main_dnsmasq(3, (char**)arg));
}
// If we find "--" we collect everything behind that for dnsmasq
if(strcmp(argv[i], "--") == 0)
{
// Remember that the rest is for dnsmasq ...
consume_for_dnsmasq = true;
// ... and skip the current argument ("--")
continue;
}
// List available DHCPv4 config options
if(strcmp(argv[i], "--list-dhcp") == 0 || strcmp(argv[i], "--list-dhcp4") == 0)
{
display_opts();
exit(EXIT_SUCCESS);
}
// List available DHCPv6 config options
if(strcmp(argv[i], "--list-dhcp6") == 0)
{
display_opts6();
exit(EXIT_SUCCESS);
}
// If consume_for_dnsmasq is true, we collect all remaining options for
// dnsmasq
if(consume_for_dnsmasq)
{
if(argv_dnsmasq != NULL)
free(argv_dnsmasq);
argc_dnsmasq = argc - i + 3;
argv_dnsmasq = calloc(argc_dnsmasq, sizeof(const char*));
argv_dnsmasq[0] = "";
if(debug_mode)
{
argv_dnsmasq[1] = "-d";
argv_dnsmasq[2] = "--log-debug";
}
else
{
argv_dnsmasq[1] = "-k";
argv_dnsmasq[2] = "";
}
if(debug_mode)
{
printf("dnsmasq options: [0]: %s\n", argv_dnsmasq[0]);
printf("dnsmasq options: [1]: %s\n", argv_dnsmasq[1]);
printf("dnsmasq options: [2]: %s\n", argv_dnsmasq[2]);
}
int j = 3;
while(i < argc)
{
argv_dnsmasq[j++] = strdup(argv[i++]);
if(debug_mode)
printf("dnsmasq options: [%i]: %s\n", j-1, argv_dnsmasq[j-1]);
}
// Return early: We have consumes all available command line arguments
return;
}
// What follows beyond this point are FTL internal command line arguments
if(strcmp(argv[i], "d") == 0 ||
strcmp(argv[i], "debug") == 0)