-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.c
More file actions
1000 lines (799 loc) · 28.7 KB
/
Copy pathconfig.c
File metadata and controls
1000 lines (799 loc) · 28.7 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
/*
This source file is part of the AutoBlock project.
Copyright (C) 2026 Dennis Hawkins
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you use this code in any way, I would love to hear from you. My email
address is: dennis@galliform.com
*/
// This module handles the config file.
#include "AutoBlock.h"
/*
* config.c
* Parses the AutoBlock configuration file and sets global variables.
*
*/
// This module handles processing of the conf file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* --------------------------------------------------------------------------
* Global variables
* -------------------------------------------------------------------------- */
bool G_DryRun = false;
int P_DryRun = -1;
char G_LogFilePath[PATH_SIZE] = DEFAULTLOGFILE;
char G_AsteriskNoticeFile[PATH_SIZE] = {0};
char G_FirewallBlockListPath[PATH_SIZE]= {0};
char G_TransferCmd[PATH_SIZE] = {0};
char G_ReloadCmd[PATH_SIZE] = {0};
DWORD G_Verbosity = STATUS;
int P_Verbosity = -1;
DWORD G_RequestTypes = 0;
int G_AllowNamedServer = 0; // 0=FALSE, -1=TRUE, count
RANGE *G_AllowedNumericalIds = NULL;
int G_NumAllowedNumericalIds = 0;
IPTYPE *G_IgnoreBlocks = NULL;
int G_NumIgnoreBlocks = 0;
int G_MinCidr = 0;
int G_MaxCidr = 32;
bool G_UseWhois = true;
IPTYPE *G_Imports = NULL;
int G_NumImports = 0;
int G_Compress = 60;
int G_Expire = 99999999;
static char *Continued = NULL; // buffer for joined continuation lines
static int ContBufLen = 0; // Length of continuation buffer
static DWORD SeenFlags = 0;
/* ==========================================================================
* FreeConfig
*
* Releases any heap memory allocated by ParseConfig().
* ========================================================================== */
void FreeConfig(void)
{
if (G_AllowedNumericalIds)
{
free(G_AllowedNumericalIds);
G_AllowedNumericalIds = NULL;
G_NumAllowedNumericalIds = 0;
}
if (G_IgnoreBlocks)
{
free(G_IgnoreBlocks);
G_IgnoreBlocks = NULL;
G_NumIgnoreBlocks = 0;
}
if (Continued)
{
free(Continued);
Continued = NULL;
ContBufLen = 0; // Length of continuation buffer
}
if (G_Imports)
{
free(G_Imports);
G_Imports = NULL;
G_NumImports = 0;
}
}
/* --------------------------------------------------------------------------
* Internal helper: trim leading and trailing whitespace in-place.
* Returns pointer to the first non-whitespace character in s.
* -------------------------------------------------------------------------- */
char *trim(char *s)
{
char *end;
int len;
// first trim trailing spaces newlines and line feeds
if (!s) return(NULL);
for (end = s + strlen(s) - 1; end >= s; end--)
{
if (isspace((unsigned char) *end)) *end = '\0';
else break;
}
// remove leading white space
end = s + strspn(s, " \t\v\f");
len = strlen(end) + 1;
// Note that there is a bug in the gcc library for strcpy(). In K&R,
// opverlapping strings copied right to left are supporsed to work
// properly. They do not with gcc. You have to use memmove().
if (end != s) memmove(s, end, len);
// if (end != s) strcpy(s, end); // won't work with gcc.
return(s);
}
// Strip line of comments, CR, and LF.
// Convert tabs, form feeds, and vertical feeds to regular spaces
char *StripComments(char *s)
{
char *p, ch;
for (p = s; (ch = *p) != '\0'; p++)
{
if (ch == '#' || ch == '\r' || ch == '\n') // end of line chars
{
*p = '\0';
break;
}
else if (ch == '\v' || ch == '\f' || ch == '\t') *p = ' '; // change to spaces
}
return(s);
}
/* --------------------------------------------------------------------------
* Internal helper: convert string to uppercase in-place.
* -------------------------------------------------------------------------- */
#if !defined(__BORLANDC__)
static void strupr(char *s)
{
for (; *s; s++)
{
*s = toupper((unsigned char) *s);
}
return;
}
#endif
// Return 0 if "FALSE", 1 if "TRUE", or -1 if neither
static int GetBoolParam(const char *s)
{
strupr((char *) s);
if (strcmp(s, "TRUE") == 0) return(1);
if (strcmp(s, "FALSE") == 0) return(0);
return(-1); // neither
}
// Return pointer to a path. Remove optional quotes.
// If quotes are used, then only the part inside those quotes are returned.
// If quotes are used and the terminating quote is not present, then return
// empty string.
// NOTE: That paths may not contain backslashes. Backslashes are the
// continuation character.
// NOTE2: Because Linux is case sensitive, the path cannot be changed to
// upper case.
static void GetConfigPath(char *s, char *buf, int bufsize)
{
char *q, *t, qc;
q = strpbrk(s, "\"'`"); // find a quote or null
if (q) // has quotes
{
qc = *q; // save quote char so we can find its match
for (t = s; t <= q; t++) *t = ' '; // any chars before and including the quote are padded
q = strchr(q + 1, qc); // find match
if (q) // found match
{
*q = '\0'; // terminate string there
trim(s); // get rid of leading spaces
// Quotes are gone and only that which was inside them remain
}
else // no matching quote
{
s[0] = '\0'; // This will cause the following code to return an empty string.
PrintErr(WARN, "No matching quote in path:%s\n", s);
}
}
strncpy(buf, s, bufsize - 1);
buf[bufsize - 1] = '\0';
}
// Read a line from the file, pre-process it and return a continuous line
// that has no leading or trailing spaces and has comments and newlines
// stripped out. Line continuations are handle here.
// A pointer to a complete usable line is returned or NULL if there is an
// error or EOF.
#define LINEBLOCKSIZE 1024
char *GetPreProcessedLine(FILE *fp)
{
char *s, *p, *NewCont;
int len;
if (!fp) return(NULL);
// make sure the buffer has a minimal size
if (!Continued) // line buffer not allocated yet
{
ContBufLen = LINEBLOCKSIZE;
Continued = malloc(LINEBLOCKSIZE); // start with 1024 bytes
if (!Continued)
{
PrintErr(FATAL, "Insufficient memory!\n");
return(NULL); // not enough memory
}
}
Continued[0] = '\0'; // clear old buffer
s = Continued; // s is the working line buffer pointer
while (fgets(s, LINEBLOCKSIZE, fp) != NULL)
{
// strip comments and leading and trailing spaces
StripComments(s);
trim(s);
// Check for continuation backslash, if there, remove and retrim.
// check for continuation character - only one allowed per line
p = strchr(s, '\\');
if (p) // get rid of backslash and re-trim line.
{
// This line is continued on the next physical line
*p = ' '; // convert backslash to a space
// Remove spaces between the '\' and the last char before it
trim(s); // trim again
// add free space that goes in between lines if not an empty line
if (s[0]) strcat(s, " ");
}
else
{
// This line is not continued, but could be the last line of
// other continued lines
if (Continued[0] == '\0') // Whole line is a Blank line
{
s = Continued; // start over with fresh line
continue; // Don't return blank lines
}
return(Continued); // return entire line
}
// If we are here, then we have another line that needs to be
// read, so prepare for it.
len = strlen(Continued); // get bytes currently used plus terminator
// make sure that continuation buffer is big enough
if (ContBufLen < len + LINEBLOCKSIZE + 1)
{
// make sure there is enough room
ContBufLen += LINEBLOCKSIZE;
NewCont = realloc(Continued, ContBufLen);
if (!NewCont) // not enough memory - return what we have
{
PrintErr(FATAL, "Insufficent Memory!");
ContBufLen -= LINEBLOCKSIZE;
return(Continued); // No memory left - Return what we have
}
Continued = NewCont;
}
s = Continued + len; // s points to the '\0' of existing line
// go back up and read the continued line
}
// If we are here, it means that there are no more physical lines in the
// file, so we output what we have
// No more lines in file, but might still have one in buffer
return(Continued[0] ? Continued : NULL);
}
// Parse the line into an array of string pointers pointing to tokens in
// the line (now null terminated). Caller must free() the returned array
// before GetPreProcessedLine() gets called again.
// The returned value will be NULL if there was a problem.
// The first token will be the variable name before the ':'.
// The additional tokens will be the parameters.
char **ParseConfigLine(char *line)
{
int i, count = 0;
char **tokens;
char *p;
if (!line || !line[0]) return NULL;
// Count tokens (Variable Name + Parameters)
// Syntax: Variable:Param1,Param2,Param3
// The following for loop might over count, but that's OK
for (i = 0; line[i] != '\0'; i++)
{
if (line[i] == ':' || line[i] == ',') count++;
}
if (count == 0) return NULL;
// The for loop will miss the last token in the line because it doesn't
// have a deliminator at the end. We add one for that to the count,
// plus an extra one for the NULL at the end of the list.
// Yes, I know this is prone to over counting, but that's OK.
count += 2;
// Allocate array of pointers
tokens = (char **)malloc((count) * sizeof(char *));
if (!tokens) return NULL;
memset(tokens, 0, count * sizeof(char *)); // make sure it starts fresh
// Tokenize with strtok().
// Yes I know that strtok() is not thread safe, but this program has
// only one thread so its OK.
p = strtok(line, ":"); // get first token (the variable)
tokens[0] = p;
count = 1;
while (p != NULL)
{
p = strtok(NULL, ",");
tokens[count++] = p;
}
// When there are no more tokens, strtok() returns NULL which is
// automatically set to the last entry in tokens[].
// After tokenizing...
for (i = 0; tokens[i] != NULL; i++)
{
// trim leading and trailing spaces from token
trim(tokens[i]);
}
return tokens;
}
// Search approved variables for Token and return index to that token.
// Return -1 if not found.
// Note that the order of this enum and the table below must be in sync.
enum
{
DRYRUN=0, VERBOSITY, LOGFILEPATH, ASTERISKNOTICEFILE,
FIREWALLBLOCKLISTPATH, REQUESTTYPES, ALLOWNAMEDSERVER,
ALLOWEDNUMERICALIDS, IGNOREBLOCKS, MINCIDR, MAXCIDR, USEWHOIS,
TRANSFERCMD, RELOADCMD, IMPORT, COMPRESS, EXPIRE, VARIABLE_COUNT
};
int GetVariable(char *Token)
{
int i;
// This table must match the above enum exactly.
static const char *vars[] =
{
"DRYRUN",
"VERBOSITY",
"LOGFILEPATH",
"ASTERISKNOTICEFILE",
"FIREWALLBLOCKLISTPATH",
"REQUESTTYPES",
"ALLOWNAMEDSERVER",
"ALLOWEDNUMERICALIDS",
"IGNOREBLOCKS",
"MINCIDR",
"MAXCIDR",
"USEWHOIS",
"TRANSFERCMD",
"RELOADCMD",
"IMPORT",
"COMPRESS",
"EXPIRE",
NULL
};
strupr(Token); // convert to uppercase for comaparison
for (i = 0; vars[i]; i++)
{
if (strcmp(vars[i], Token) == 0)
return(i);
}
return(-1); // didn't find it
}
// Process REQUESTTYPES and return a flag
// Since this parses multiple parameters, the entire token table needs
// to be passed in. The flag returned is a bitfield indicating which
// Request Types are specified.
DWORD ProcessRequestTypes(char **Tokens)
{
static char *pTab[5] =
{
"REGISTER",
"INVITE",
"OPTIONS",
"*",
NULL
};
DWORD fTab[5] = // This must match pTab[] exactly
{
BIT_REGISTER,
BIT_INVITE,
BIT_OPTIONS,
( BIT_REGISTER | BIT_INVITE | BIT_OPTIONS),
0
};
int i, pn; // parameter number
DWORD flags = 0;
if (!Tokens) return(0);
// check each parameter
for (pn = 1; Tokens[pn]; pn++)
{
strupr(Tokens[pn]); // make sure its uppercase
for (i = 0; pTab[i]; i++)
{
if (strcmp(Tokens[pn], pTab[i]) == 0)
{
flags |= fTab[i];
break;
}
}
// if the parameter isn't matched, then don't change flags
}
return(flags);
}
DWORD GetVerbosity(char *Token)
{
static const char *pTab[5] =
{
"QUIET",
"FATAL",
"WARN",
"STATUS",
NULL
};
int i;
if (!Token) return(0);
strupr(Token); // make sure its uppercase
for (i = 0; pTab[i]; i++)
{
if (strcmp(Token, pTab[i]) == 0)
return(i);
}
PrintErr(QUIET, "Verbosity cannot be set to: %s\n", Token);
return(STATUS); // return this if the token isn't found.
}
// Creates a table at G_AllowedNumericalIds and then processes ranges
// into RANGE elements of that table. Sets G_NumAllowedNumericalIds
// to the number of ranges in the table.
void ProcessAllowedIds(char **Tokens)
{
int numRanges, np;
char *tk, *pd;
// check if this isn't the first time here
if (G_AllowedNumericalIds)
{
free(G_AllowedNumericalIds); // free old ones, new ones overwrite
G_AllowedNumericalIds = NULL;
G_NumAllowedNumericalIds = 0;
}
// count the number of ranges we have
for (numRanges = 0; Tokens[numRanges + 1]; numRanges++);
if (!numRanges) return; // no ranges to process
// Allocate new table
G_AllowedNumericalIds = malloc(numRanges * sizeof(RANGE));
memset(G_AllowedNumericalIds, 0, numRanges * sizeof(RANGE));
G_NumAllowedNumericalIds = numRanges;
// Note if the syntax is correct, the following will work
for (np = 0; (tk = Tokens[np + 1]) != NULL; np++)
{
// Get token range
G_AllowedNumericalIds[np].last = // get first part and
G_AllowedNumericalIds[np].first = atoi(tk); //store in both
pd = strchr(tk, '-'); // look for a dash
if (pd) // found dash - we have a second part
{
G_AllowedNumericalIds[np].last = atoi(pd + 1); // Get the last part after the dash
}
// check to make sure they aren't reversed
if (G_AllowedNumericalIds[np].first > G_AllowedNumericalIds[np].last)
PrintErr(WARN, "ID Range has bad order.\n");
}
}
// Create a table of G_NumIgnoreBlocks IPTYPE blocks at G_IgnoreBlocks.
// Process IP's, IP cidr, and domain names. Note that the domain name
// lookup is done at the start of each run so this works great for
// whitelisting people with DDNS domain names that change frequently.
void ProcessIgnoredBlocks(char **Tokens)
{
int numBlocks, cnt, np;
char *tk, *p;
IPTYPE ip;
bool isDom;
// check if this isn't the first time here
if (G_IgnoreBlocks)
{
free(G_IgnoreBlocks); // free old ones, new ones overwrite
G_IgnoreBlocks = NULL;
G_NumIgnoreBlocks = 0;
}
// count the number of blocks we have
for (numBlocks = 0; Tokens[numBlocks + 1]; numBlocks++);
if (!numBlocks) return; // no blocks to process
// Allocate new table
G_IgnoreBlocks = malloc(numBlocks * sizeof(IPTYPE));
memset(G_IgnoreBlocks, 0, numBlocks * sizeof(IPTYPE));
// Note if the syntax is correct, the following will work
isDom = false;
cnt = 0;
for (np = 0; (tk = Tokens[np + 1]) != NULL; np++)
{
// Find cidr block if there
p = strchr(tk, '/');
if (p)
{
*p = '\0';
p++;
}
// Get Block
if (Str2Ip(tk, &ip) == 0) // The parameter is a domain name
{
ip.IP = Domain2Ip(tk);
ip.bits = 32;
isDom = true;
}
// If we have a valid IP, then store it
if (ip.IP) // non-zero is good
{
ip.bits = (p && p[0]) ? atoi(p) : 32;
G_IgnoreBlocks[cnt++] = ip;
PrintErr(STATUS, "WhiteListing: %s", IP2Str(ip));
if (isDom) // domain name
PrintErr(STATUS, " (%s)", tk);
PrintErr(STATUS, "\n");
}
else
{
PrintErr(WARN, "Failed to extract IP from: %s\n", tk);
}
}
G_NumIgnoreBlocks = cnt; // return actual count of valid IP blocks
}
bool IpMaskMatch(IPTYPE block_ip, DWORD match_ip)
{
DWORD mask;
// Handle edge case: a 0-bit mask encompasses the entire
// internet (0.0.0.0/0)
if (block_ip.bits == 0)
{
mask = 0;
}
// Handle standard CIDR masks (1 to 32 bits)
else if (block_ip.bits >= 32)
{
mask = 0xFFFFFFFF;
}
else
{
// Create a mask with the highest 'bits' set to 1.
mask = (0xFFFFFFFF << (32 - block_ip.bits));
}
// Compare the network prefixes of both the parameter IP and
// the block IP
if ((match_ip & mask) == (block_ip.IP & mask))
{
return true; // Match found, IP is whitelisted
}
return false;
}
// typedef struct
// {
// DWORD IP; // IPv4 in DWORD format
// DWORD bits; // cidr bits
// } IPTYPE;
// Search the G_IgnoreBlocks[] table to see if the parameter ip (in DWORD
// format) is contained within any of the IP blocks in the table. Return
// true, if any of the blocks in the table encompass the ip, else false.
bool is_ip_whitelisted(DWORD ip)
{
int i;
// Loop through all elements in the global array
for (i = 0; i < G_NumIgnoreBlocks; i++)
{
if (IpMaskMatch(G_IgnoreBlocks[i], ip)) return true;
}
return false; // No blocks encompassed the IP
}
// Search the G_AllowedNumericalIds table for the extension
// Return TRUE if NOT found.
int SearchID(int ext)
{
int i;
for (i = 0; i < G_NumAllowedNumericalIds; i++)
{
if (ext >= G_AllowedNumericalIds[i].first &&
ext <= G_AllowedNumericalIds[i].last)
return(false); // found it
}
return(true);
}
// Starting with G_TransferCmd[PATH_SIZE],
// Replace "%src%" with the local ipset path (SRCPATH).
// Replace "%dst%" with the path to the ipset on the router
// (G_FirewallBlockListPath[PATH_SIZE]).
// "%%" is replaced with "%".
void ProcessTransferCmd(void)
{
char TempStr[sizeof(G_TransferCmd)] = {0};
char *src = G_TransferCmd;
char *dst = TempStr;
size_t max_len = sizeof(TempStr) - 1;
size_t current_len = 0;
int lenSrc = strlen(SRCPATH);
int lenDst = strlen(G_FirewallBlockListPath);
while (*src != '\0')
{
// Safety guard to guarantee we never overflow TempStr
if (current_len >= max_len) break;
if (*src == '%')
{
if (strncmp(src, "%src%", 5) == 0)
{
if (current_len + lenSrc < max_len)
{
strcpy(dst, SRCPATH);
dst += lenSrc;
current_len += lenSrc;
}
src += 5; // Advance past the whole token "%src%" cleanly
}
else if (strncmp(src, "%dst%", 5) == 0)
{
if (current_len + lenDst < max_len)
{
strcpy(dst, G_FirewallBlockListPath);
dst += lenDst;
current_len += lenDst;
}
src += 5; // Advance past the whole token "%dst%" cleanly
}
else if (*(src + 1) == '%')
{
*dst++ = '%';
current_len++;
src += 2; // Skip both percent symbols "%%"
}
else
{
// Unrecognized token (e.g. "%unknown%").
// Skips the isolated '%' to match your original discarding logic.
src++;
}
}
else
{
*dst++ = *src++;
current_len++;
}
}
*dst = '\0'; // Ensure string termination
// copy back to G_TransferCmd
strncpy(G_TransferCmd, TempStr, sizeof(G_TransferCmd) - 1);
G_TransferCmd[sizeof(G_TransferCmd) - 1] = '\0';
// PrintErr(STATUS, "Cmd: %s\n", G_TransferCmd);
}
void ProcessImports(char **Tokens)
{
int i;
char tmpstr[1024];
if (!Tokens || !Tokens[0]) return;
for (i = 1; Tokens[i]; i++)
{
// Get rid of quotes if there
GetConfigPath(Tokens[i], tmpstr, sizeof(tmpstr));
ReadImports(tmpstr);
}
return;
}
/* ==========================================================================
* ParseConfig
*
* Opens and processes the configuration file at 'filepath'.
* Returns 0 on success, non-zero on error.
* ========================================================================== */
int ParseConfig(const char *filepath)
{
/* Variables must be declared at the top of the block (ANSI C89) */
FILE *fp;
char **tokens;
int TokenNum, b;
DWORD mask;
char *p;
fp = fopen(filepath, "rt");
if (!fp)
{
PrintErr(FATAL, "ParseConfig: cannot open '%s'\n", filepath);
return 1;
}
while ((p = GetPreProcessedLine(fp)) != NULL)
{
tokens = ParseConfigLine(p);
if (!tokens) continue; // no tokens found
TokenNum = GetVariable(tokens[0]);
if (TokenNum == -1)
{
PrintErr(WARN, "Unknown Variable: %s\n", tokens[0]);
free(tokens);
continue; // not a valid token
}
// Mark that each variable is set
SeenFlags |= (DWORD)(1 << TokenNum);
switch (TokenNum)
{
// Booleans
case DRYRUN:
b = GetBoolParam(tokens[1]);
if (b == -1) PrintErr(WARN, "Invalid boolean: %s\n", tokens[1]);
G_DryRun = (bool) b;
break;
case USEWHOIS:
b = GetBoolParam(tokens[1]);
if (b == -1) PrintErr(WARN, "Invalid boolean: %s\n", tokens[1]);
G_UseWhois = (bool) b;
break;
case VERBOSITY:
G_Verbosity = GetVerbosity(tokens[1]);
break;
// Paths
case LOGFILEPATH:
GetConfigPath(tokens[1], G_LogFilePath, sizeof(G_LogFilePath));
break;
case ASTERISKNOTICEFILE:
GetConfigPath(tokens[1], G_AsteriskNoticeFile, sizeof(G_AsteriskNoticeFile));
break;
case FIREWALLBLOCKLISTPATH:
GetConfigPath(tokens[1], G_FirewallBlockListPath, sizeof(G_FirewallBlockListPath));
break;
// Cidr sizes
case MINCIDR:
G_MinCidr = atoi(tokens[1]);
if (G_MinCidr < 1) G_MinCidr = 1;
if (G_MinCidr > 31) G_MinCidr = 31;
break;
case MAXCIDR:
G_MaxCidr = atoi(tokens[1]);
if (G_MaxCidr < 2) G_MaxCidr = 2;
if (G_MaxCidr > 32) G_MaxCidr = 32;
break;
// This is a non-standard BOOL, FALSE = 0, TRUE= -1, or
// a count which can be up to 100,000.
case ALLOWNAMEDSERVER:
b = GetBoolParam(tokens[1]);
if (b == 1) b = -1; // TRUE
else if (b == -1) // not TRUE or FALSE, probably a count
{
b = atoi(tokens[1]); // its a count
if (b < 1) b = 1;
if (b > 100000) b = 100000;
}
G_AllowNamedServer = b;
break;
// The following variables are more complicated because
// they allow multiple parameters
// The sip request type can be "REGISTER", "INVITE", or
// "OPTIONS". Set flag accordingly.
case REQUESTTYPES:
G_RequestTypes = ProcessRequestTypes(tokens);
break;
// ALLOWEDNUMERICALIDS is a list of Integer ranges stored
// as RANGE types. If a NOTICE arrives with a numerical ID
// that is in the range specified, then it is not blocked
// right away.
case ALLOWEDNUMERICALIDS:
ProcessAllowedIds(tokens);
break;
// IGNOREBLOCKS is essentiallly a whitelist. Here IP's, Cidr
// Blocks, and domain names can be listed that cause the
// program to ignore errors from the listed IP's. For
// efficiency, make cidr blocks as large as reasonable.
case IGNOREBLOCKS:
ProcessIgnoredBlocks(tokens);
break;
case TRANSFERCMD:
GetConfigPath(tokens[1], G_TransferCmd, sizeof(G_TransferCmd));
ProcessTransferCmd();
break;
case RELOADCMD:
GetConfigPath(tokens[1], G_ReloadCmd, sizeof(G_ReloadCmd));
break;
case IMPORT:
ProcessImports(tokens);
break;
case COMPRESS:
G_Compress = atoi(tokens[1]);
if (G_Compress < 0) G_Compress = 0;
if (G_Compress > 100) G_Compress = 100;
break;
case EXPIRE: // use -1 no expire
G_Expire = atoi(tokens[1]);
if (G_Expire < 0) G_Expire = 999999999;
break;
default:
PrintErr(WARN, "Unknown Variable: %s\n", tokens[0]);
break;
} // end switch
// Free token array
free(tokens);
// Unknown tokens are silently ignored
} // end while
fclose(fp);
// Check if we have seen all variables
mask = (VARIABLE_COUNT >= 32) ? 0xFFFFFFFF : (1UL << VARIABLE_COUNT) - 1;
if ((SeenFlags & mask) != mask)
{
PrintErr(WARN, "Error: Not all variables set.\n");
}
// Cross-validate MINCIDR < MAXCIDR
if (G_MinCidr >= G_MaxCidr)
{
PrintErr(WARN, "Config error: MINCIDR (%d) must be less than MAXCIDR (%d)\n",
G_MinCidr, G_MaxCidr);
// Set to safe defaults
G_MinCidr = 16;
G_MaxCidr = 24;
}
// Command line parameter overrides
if (P_DryRun != -1) G_DryRun = (bool) P_DryRun;
if (P_Verbosity != -1) G_Verbosity = P_Verbosity;
return 0;
}