File: acfg.cc

package info (click to toggle)
apt-cacher-ng 0.7.27-1~bpo70+1
  • links: PTS
  • area: main
  • in suites: wheezy-backports
  • size: 1,740 kB
  • sloc: cpp: 13,987; sh: 519; perl: 442; ansic: 414; makefile: 77
file content (1391 lines) | stat: -rw-r--r-- 32,795 bytes parent folder | download
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

#include "debug.h"

#include "acfg.h"
#include "meta.h"
#include "filereader.h"
#include "fileio.h"
#include "lockable.h"
#include "cleaner.h"

#include <regex.h>

#include <iostream>
#include <fstream>
#include <string>
#include <deque>
#include <map>
#include <list>
#include <algorithm>

using namespace MYSTD;


#define _iterPos(it, start) (it-start.begin())/sizeof(it)
#define sProblemLoc szPath<< ':'<< _iterPos(it, lines)

// hint to use the main configuration excluding the complex directives
bool g_testMode=false;

#define BARF(x) {if(!g_testMode){ cerr << x << endl; exit(EXIT_FAILURE); }}
#define BADSTUFF_PATTERN "\\.\\.($|%|/)"
mstring PTHOSTS_PATTERN;

namespace rechecks
{
bool CompileExpressions();
bool CompileUncExpressions(const string & req, const string & tgt);
}


namespace acfg {


// internal stuff:
string sPopularPath("/debian/");

string tmpDontcache, tmpDontcacherq, tmpDontcacheResolved;

tStrMap localdirs;
lockable mimemap_lock;
NoCaseStringMap mimemap;

MYSTD::bitset<65536> *pUserPorts = NULL;

typedef struct
{
	const char *name; mstring *ptr;
	const char *warn;
}
MapNameToString;

typedef struct
{
	const char *name; int *ptr;
	const char *warn; int base;
}
MapNameToInt;

#ifndef MINIBUILD

MapNameToString n2sTbl[] = {
		{  "Port", 			&port , 0}
		,{ "CacheDir", 	&cachedir, 0 }
		,{ "LogDir", 	&logdir , 0}
		,{ "SupportDir", 	&suppdir, 0}
		,{ "SocketPath", 	&fifopath, 0}
		,{ "PidFile", 	&pidfile, 0}
		,{ "ReportPage",&reportpage, 0}
		,{ "VfilePattern", &vfilepat, 0}
		,{ "PfilePattern", &pfilepat, 0}
		,{ "WfilePattern", &wfilepat, 0}
		,{ "AdminAuth",  &adminauth, 0}
		,{ "BindAddress", &bindaddr, 0}
		,{ "UserAgent", &agentname, 0}
		,{ "DontCache",	&tmpDontcache, 0}
		,{ "DontCacheRequested",	&tmpDontcacherq, 0}
		,{ "DontCacheResolved",	&tmpDontcacheResolved, 0}
		,{ "PrecacheFor", &mirrorsrcs, 0}
		,{ "RequestAppendix", &requestapx, 0}
		,{ "PassThroughPattern", &PTHOSTS_PATTERN, 0}
		,{ "CApath", &capath, 0}
		,{ "CAfile", &cafile, 0}
};

MapNameToInt n2iTbl[] = {
		{ "Debug", 		&debug, 0 , 10}
		,{ "OfflineMode", 	&offlinemode , NULL, 10}
		,{ "ForeGround", 	&foreground , NULL, 10}
		,{ "Verbose", 		NULL, "Option is deprecated, ignoring the value." , 10}
		,{ "ForceManaged", 	&forcemanaged , NULL, 10}
		,{ "StupidFs", 		&stupidfs , NULL, 10}
		,{ "VerboseLog",	&verboselog , NULL, 10}
		,{ "ExTreshold",	&extreshhold, NULL, 10}
		,{ "MaxSpareThreadSets",	&tpstandbymax, "Deprecated option name, mapped to MaxStandbyConThreads", 10}
		,{ "MaxStandbyConThreads",	&tpstandbymax, NULL, 10}
		,{ "MaxConThreads",	&tpthreadmax, NULL, 10}
		,{ "DnsCacheSeconds", &dnscachetime, NULL, 10}
		,{ "UnbufferLogs", &debug , NULL, 10}
		,{ "ExAbortOnProblems", &exfailabort, NULL, 10}
		,{ "ExposeOrigin", &exporigin, NULL, 10}
		,{ "LogSubmittedOrigin", &logxff, NULL, 10}
		,{ "OldIndexUpdater", &oldupdate, "Option is deprecated, ignoring the value." , 10}
		,{ "RecompBz2", &recompbz2, NULL, 10}
		,{ "NetworkTimeout", &nettimeout, NULL, 10}
		,{ "MinUpdateInterval", &updinterval, NULL, 10}
		,{ "ForwardBtsSoap", &forwardsoap, NULL, 10}
		,{ "KeepExtraVersions", &keepnver, NULL, 10}
		,{ "UseWrap", &usewrap, NULL, 10}
		,{ "FreshIndexMaxAge", &maxtempdelay, NULL, 10}
		,{ "RedirMax", &redirmax, NULL, 10}
		,{ "VfileUseRangeOps", &vrangeops, NULL, 10}
		,{ "ResponseFreezeDetectTime", &stucksecs, NULL, 10}
		,{ "ReuseConnections", &persistoutgoing, NULL, 10}
		,{ "PipelineDepth", &pipelinelen, NULL, 10}
		,{ "ExSuppressAdminNotification", &exsupcount, NULL, 10}
		,{ "OptProxyTimeout", &optproxytimeout, NULL, 10}

		,{ "DirPerms", &dirperms, NULL, 8}
		,{ "FilePerms", &fileperms, NULL, 8}
};

void ReadRewriteFile(const string & sFile, const string & sRepName);
void ReadBackendsFile(const string & sFile, const string &sRepName);

struct fct_lt_host
{
	bool operator()(const tHttpUrl &a, const tHttpUrl &b) const
	{
		cmstring& ap = a.GetPort();
		cmstring& bp = b.GetPort();
		if (ap != bp)
			return ap < bp;
		return strcasecmp(a.sHost.c_str(), b.sHost.c_str()) < 0;
	}
};
typedef multimap<tHttpUrl,const string*, fct_lt_host> tMapUrl2StringPtr; 
typedef tMapUrl2StringPtr::iterator tUrl2RepIter;
tMapUrl2StringPtr mapUrl2pVname;

typedef map<const string, tRepoData> tRepMap;
tRepMap repoparms;

string * GetStringPtr(const string &key) {
	for(unsigned int i=0; i<_countof(n2sTbl); i++)
	{
		if(0==strcasecmp(key.c_str(), n2sTbl[i].name))
		{
			if(n2sTbl[i].warn)
				cerr << "Warning, " << key << ": " << n2sTbl[i].warn << endl;

			return n2sTbl[i].ptr;
		}
	}
	return NULL;
}

int * GetIntPtr(const string &key, int &base) {
	for(unsigned int i=0; i<_countof(n2iTbl); i++)
	{
		if(0==strcasecmp(key.c_str(), n2iTbl[i].name))
		{
			if(n2iTbl[i].warn)
				cerr << "Warning, " << key << ": " << n2iTbl[i].warn << endl;
			base = n2iTbl[i].base;
			return n2iTbl[i].ptr;
		}
	}
	return NULL;
}

void printVar(cmstring &key)
{
	string *ps=GetStringPtr(key);
	if(ps)
		cout << *ps << endl;
	int base, *pn=GetIntPtr(key, base);
	if(pn)
		cout << *pn <<endl;
}

// shortcut for frequently needed code, opens the config file, reads step-by-step
// and skips comment and empty lines
struct tCfgIter
{
	filereader reader;
	string sLine;
	tCfgIter(cmstring &fn)
	{
		reader.OpenFile(fn);
		reader.AddEofLines();
	}
	inline operator bool() const { return reader.CheckGoodState(false); }
	inline bool Next()
	{
		while(reader.GetOneLine(sLine))
		{
			trimFront(sLine);
			if(sLine.empty() || sLine[0] == '#')
				continue;
			return true;
		}
		return false;
	}
};

inline bool qgrep(cmstring &needle, cmstring &file)
{
	for(acfg::tCfgIter itor(file); itor.Next();)
		if(itor.sLine.find(needle) != stmiss)
			return true;
	return false;
}

inline void _FixPostPreSlashes(string &val)
{
	// fix broken entries

	if (val.empty() || val.at(val.length()-1) != '/')
		val.append("/");
	if (val.at(0) != '/')
		val.insert(0, "/", 1);
}

bool ReadOneConfFile(const string & szFilename)
{
	tCfgIter itor(szFilename);
	itor.reader.CheckGoodState(true);

	NoCaseStringMap dupeCheck;

	while(itor.Next())
	{
#ifdef DEBUG
		cerr << itor.sLine <<endl;
#endif
		// XXX: To something about escaped/quoted version
		tStrPos pos=itor.sLine.find('#');
		if(stmiss != pos)
			itor.sLine.erase(pos);

		if(! SetOption(itor.sLine, g_testMode, &dupeCheck))
			BARF("Error reading main options, terminating.");
	}
	return true;
}

inline const string * GetRepoEntryNamePtr(const string & sRepName)
{
	// save some memory by storing only pointer to its entry in the map since the life time is guaranteed

	tRepMap::iterator it = repoparms.find(sRepName);
	if(repoparms.end() == it)
	{
		repoparms[sRepName] = tRepoData();
		it = repoparms.find(sRepName);
	}
	return & it->first;
}

inline bool ParseOptionLine(const string &sLine, string &key, string &val, bool bQuiet)
{
	string::size_type posCol = sLine.find(":");
	string::size_type posEq = sLine.find("=");
	if (posEq==stmiss && posCol==stmiss)
	{
		if(!bQuiet)
			cerr << "Not a valid configuration directive: " << sLine <<endl;
		return false;
	}
	string::size_type pos;
	if (posEq!=stmiss && posCol!=stmiss)
		pos=min(posEq,posCol);
	else if (posEq!=stmiss)
		pos=posEq;
	else
		pos=posCol;

	key=sLine.substr(0, pos);
	val=sLine.substr(pos+1);
	trimString(key);
	trimString(val);
	if(key.empty())
		return false; // weird

	return true;
}


inline void AddRemapFlag(const string & token, const string &repname)
{
	mstring key, value;
	if(!ParseOptionLine(token, key, value, true))
		return;

	tRepoData &where = repoparms[repname];

	if(key=="keyfile")
	{

		if(value.empty())
			return;

		//if(!startsWithSz(value, "/"))
		//	value.insert(0, "/");
		if (acfg::debug&LOG_FLUSH)
			cerr << "Fatal keyfile for " <<repname<<": "<<value <<endl;

		where.m_keyfiles.push_back(value);
	}
	else if(key=="deltasrc")
	{

		if(value.empty())
			return;

		if(!endsWithSzAr(value, "/"))
			value+="/";

		if(!where.m_deltasrc.SetHttpUrl(value))
			cerr << "Couldn't parse Debdelta source URL, ignored " <<value <<endl;
	}
	else if(key=="proxy")
	{
		static MYSTD::list<tHttpUrl> alt_proxies;
		tHttpUrl cand;
		if(value.empty() || cand.SetHttpUrl(value))
		{
			alt_proxies.push_back(cand);
			where.m_pProxy = & alt_proxies.back();
		}
		else
		{
			cerr << "Warning, failed to parse proxy setting " << value << " , "
					<< endl << "ignoring it" <<endl;
		}
	}
}

tStrDeq ExpandFileTokens(cmstring &token)
{

	tStrDeq srcs;

	string sPath = token.substr(5);
	if (sPath.empty())
		BARF("Bad file spec for repname, file:?");
	bool bAbs = IsAbsolute(sPath);
	if (suppdir.empty() || bAbs)
	{
		if (!bAbs)
			sPath = confdir + sPathSep + sPath;
		srcs = ExpandFilePattern(sPath, true);
	}
	else
	{
		tStrMap bname2path;

		mstring* paths[] =
		{ &suppdir, &confdir };
		for (mstring **ps = paths; ps < paths + _countof(paths); ++ps)
		{
			// chop slashes. That should not be required but better be sure.
			while(endsWithSzAr(**ps, sPathSep) && (**ps).size()>1)
				(**ps).resize((**ps).size()-1);

			// temporary only
			srcs = ExpandFilePattern(**ps + sPathSep + sPath, true);
			if (srcs.size() == 1 && GetFileSize(srcs[0], -23) == off_t(-23))
				continue; // file not existing, wildcard returned

			// hits in confdir will overwrite those from suppdir
			for (; !srcs.empty(); srcs.pop_back())
				bname2path[::GetBaseName(srcs.back())] = srcs.back();
		}
		if (bname2path.empty())
		{
			cerr << "WARNING: No URL list file matching " << token
					<< " found in config or support directories." << endl;
		}
		srcs.clear();
		for (tStrMap::const_iterator it = bname2path.begin(); it != bname2path.end(); ++it)
			srcs.push_back(it->second);
	}
	return srcs;
}

inline void AddRemapInfo(bool bAsBackend, const string & token,
		const string &repname)
{
	if (0!=token.compare(0, 5, "file:"))
	{
		tHttpUrl url;
		if(! url.SetHttpUrl(token))
			BARF(token + " <-- bad URL detected");
		_FixPostPreSlashes(url.sPath);

		if (bAsBackend)
			repoparms[repname].m_backends.push_back(url);
		else
			mapUrl2pVname.insert(pair<tHttpUrl,const string*>(
					url, GetRepoEntryNamePtr(repname)));
	}
	else
	{
		tStrDeq srcs = ExpandFileTokens(token);
		
		for(tStrDeq::const_iterator it=srcs.begin(); it!=srcs.end(); it++)
		{
			if (bAsBackend)
				ReadBackendsFile(*it, repname);
			else
				ReadRewriteFile(*it, repname);
		}
	}
}

struct tHookHandler: public tRepoData::IHookHandler, public lockable
{
	string cmdRel, cmdCon;
	time_t downDuration, downTimeNext;

	int m_nRefCnt;

	tHookHandler(cmstring&) :
		downDuration(30), downTimeNext(0), m_nRefCnt(0)
	{
//		cmdRel = "logger JobRelease/" + name;
//		cmdCon = "logger JobConnect/" + name;
	}
	virtual void JobRelease()
	{
		setLockGuard;
		if (0 >= --m_nRefCnt)
		{
			//system(cmdRel.c_str());
			downTimeNext = ::time(0) + downDuration;
			g_victor.ScheduleFor(downTimeNext, cleaner::TYPE_ACFGHOOKS);
		}
	}
	virtual void JobConnect()
	{
		setLockGuard;
		if (0 == m_nRefCnt++)
		{
			if(downTimeNext) // huh, already ticking? reset
				downTimeNext=0;
			else if(system(cmdCon.c_str()))
				aclog::err(tSS() << "Warning: " << cmdCon << " returned with error code.");
		}
	}
};

void _AddHooksFile(cmstring& vname)
{
	tCfgIter itor(acfg::confdir+"/"+vname+".hooks");
	if(!itor)
		return;

	struct tHookHandler &hs = *(new tHookHandler(vname));
	mstring key,val;
	while (itor.Next())
	{
		if(!ParseOptionLine(itor.sLine, key, val, false))
			continue;

		const char *p = key.c_str();
		if (strcasecmp("PreUp", p) == 0)
		{
			hs.cmdCon = val;
		}
		else if (strcasecmp("Down", p) == 0)
		{
			hs.cmdRel = val;
		}
		else if (strcasecmp("DownTimeout", p) == 0)
		{
			errno = 0;
			uint n = strtoul(val.c_str(), NULL, 10);
			if (!errno)
				hs.downDuration = n;
		}
	}
	repoparms[vname].m_pHooks = &hs;
}

inline void _ParseLocalDirs(cmstring &value)
{
	for(tSplitWalk splitter(&value, ";"); splitter.Next(); )
	{
		mstring token=splitter.str();
		trimString(token);
		tStrPos pos = token.find_first_of(SPACECHARS);
		if(stmiss == pos)
		{
			cerr << "Cannot map " << token << ", needed format: virtualdir realdir, ignoring it";
			continue;
		}
		string from(token, 0, pos);
		trimString(from, "/");
		string what(token, pos);
		trimString(what, SPACECHARS "'\"");
		if(what.empty())
		{
			cerr << "Unsupported target of " << from << ": " << what << ", ignoring it" << endl;
			continue;
		}
		localdirs[from]=what;
	}
}


cmstring & GetMimeType(cmstring &path)
{
	{
		lockguard g(mimemap_lock);
		static bool inited = false;
		if (!inited)
		{
			inited = true;
			for (tCfgIter itor("/etc/mime.types"); itor.Next();)
			{
				// # regular types:
				// text/plain             asc txt text pot brf  # plain ascii files

				tSplitWalk split(&itor.sLine);
				if (!split.Next())
					continue;

				mstring mimetype = split;
				if (startsWithSz(mimetype, "#"))
					continue;

				while (split.Next())
				{
					mstring suf = split;
					if (startsWithSz(suf, "#"))
						break;
					mimemap[suf] = mimetype;
				}
			}
		}
	}

	tStrPos dpos = path.find_last_of('.');
	if (dpos != stmiss)
	{
		NoCaseStringMap::const_iterator it = acfg::mimemap.find(path.substr(
				dpos + 1));
		if (it != acfg::mimemap.end())
			return it->second;
	}
	// try some educated guess... assume binary if we are sure, text if we are almost sure
	static cmstring os("application/octet-stream"), tp("text/plain"), nix("");
	filereader f;
	if(f.OpenFile(path, true))
	{
		size_t maxLen = MYSTD::min(size_t(255), f.GetSize());
		for(UINT i=0; i< maxLen; ++i)
		{
			if(!isascii((UINT) *(f.GetBuffer()+i)))
				return os;
		}
		return tp;
	}
	return nix;
}

bool SetOption(const string &sLine, bool bQuiet, NoCaseStringMap *pDupeCheck)
{

	string key, value;

	if(!ParseOptionLine(sLine, key, value, bQuiet))
		return false;

	string * psTarget;
	int * pnTarget;
	int nNumBase(10);

	if ( NULL != (psTarget = GetStringPtr(key)))
	{

		if(pDupeCheck && !bQuiet)
		{
			mstring &w = (*pDupeCheck)[key];
			if(w.empty())
				w = value;
			else
				cerr << "WARNING: " << key << " was previously set to " << w << endl;
		}

		*psTarget=value;
	}
	else if ( NULL != (pnTarget = GetIntPtr(key, nNumBase)))
	{

		if(pDupeCheck && !bQuiet)
		{
			mstring &w = (*pDupeCheck)[key];
			if(w.empty())
				w = value;
			else
				cerr << "WARNING: " << key << " was already set to " << w << endl;
		}

		const char *pStart=value.c_str();
		if(! *pStart)
		{
			cerr << "Missing value for " << key << " option!" <<endl;
			return false;
		}
		
		errno=0;
		char *pEnd(0);
		long nVal = strtol(pStart, &pEnd, nNumBase);

		if(RESERVED_DEFVAL == nVal)
		{
			cerr << "Bad value for " << key << " (protected value, use another one)" <<endl;
			return false;
		}

		*pnTarget=nVal;

		if (errno)
		{
			cerr << "Invalid number for " << key << " ";
			perror("option");
			return false;
		}
		if(*pEnd)
		{
			cerr << "Bad value for " << key << " option or found trailing garbage: " << pEnd <<endl;
			return false;
		}
	}

	else if(0==strcasecmp(key.c_str(), "Proxy"))
	{
		if(value.empty())
			proxy_info=tHttpUrl();
		else
		{
			if (!proxy_info.SetHttpUrl(value) || proxy_info.sHost.empty())
				BARF("Invalid proxy specification, aborting...");
		}
	}
	else if(0==strcasecmp(key.c_str(), "LocalDirs") && !g_testMode)
	{
		_ParseLocalDirs(value);
		return !localdirs.empty();
	}
	else if(0==strncasecmp(key.c_str(), "Remap-", 6) && !g_testMode)
	{
		string vname=key.substr(6, key.npos);
		tStrVec tokens;
		Tokenize(value, SPACECHARS, tokens);
		if(tokens.empty() || vname.empty())
		{
			if(!bQuiet)
				cerr << "Found invalid entry, ignoring " << key << ": " << value <<endl;
			return false;
		}
		int type(0); // prefixes ; backends ; flags
		for(tStrVecIterConst it=tokens.begin(); it!=tokens.end(); ++it)
		{
			if(it->empty())
				continue;
			if(it->at(0)=='#')
				break;

			if(it->at(0)==';')
				++type;
			else if(0 == type)
				AddRemapInfo(false, *it, vname);
			else if(1 == type)
				AddRemapInfo(true, *it, vname);
			else if(2 == type)
				AddRemapFlag(*it, vname);
		}
		_AddHooksFile(vname);
	}
	else if(0==strcasecmp(key.c_str(), "AllowUserPorts"))
	{
		if(!pUserPorts)
			pUserPorts=new bitset<TCP_PORT_MAX>;
		for(tSplitWalk split(&value); split.Next();)
		{
			cmstring s(split);
			const char *start(s.c_str());
			char *p(0);
			unsigned long n=strtoul(start, &p, 10);
			if(n>=TCP_PORT_MAX || !p || '\0' != *p || p == start)
				BARF("Bad port in AllowUserPorts: " << start);
			if(n == 0)
			{
				pUserPorts->set();
				break;
			}
			pUserPorts->set(n, true);
		}
	}
	else if(0==strcasecmp(key.c_str(), "ConnectProto"))
	{
		int *p = conprotos;
		for (tSplitWalk split(&value); split.Next(); ++p)
		{
			cmstring val(split);
			if (val.empty())
				break;

			if (p >= conprotos + _countof(conprotos))
				BARF("Too many protocols specified: " << val);

			if (val == "v6")
				*p = PF_INET6;
			else if (val == "v4")
				*p = PF_INET;
			else
				BARF("IP protocol not supported: " << val);
		}
	}
	else
	{
		if(!bQuiet)
			cerr << "Warning, unknown configuration directive: " << key <<endl;
		return false;
	}
	return true;
}


//const string * GetVnameForUrl(string path, string::size_type * nMatchLen)
cmstring * GetRepNameAndPathResidual(const tHttpUrl & in, string & sRetPathResidual)
{
	sRetPathResidual.clear();
	
	// get all the URLs matching THE HOSTNAME
	pair<tUrl2RepIter,tUrl2RepIter> range=mapUrl2pVname.equal_range(in);
	if(range.first==range.second)
		return NULL;
	
	tStrPos bestMatchLen(0);
	string const * psBestHit(NULL);
		
	// now find the longest directory part which is the suffix of requested URL's path
	for (tUrl2RepIter & it=range.first; it!=range.second; it++)
	{
		// rewrite rule path must be a real prefix
		// it's also surrounded by /, ensured during construction
		const string & prefix=it->first.sPath;
		tStrPos len=prefix.length();
		if (in.sPath.size() > len && 0==in.sPath.compare(0, len, prefix))
		{
			if (len>bestMatchLen)
			{
				bestMatchLen=len;
				psBestHit=it->second;
			}
		}
	}
		
	if(psBestHit) sRetPathResidual=in.sPath.substr(bestMatchLen);
	return psBestHit;
	
}

const tRepoData * GetBackendVec(cmstring &vname)
{
	tRepMap::iterator it=repoparms.find(vname);
	if(it==repoparms.end() || it->second.m_backends.empty())
		return NULL;
	return & it->second;
}


void ReadBackendsFile(const string & sFile, const string &sRepName)
{

	int nAddCount=0;
	string key, val;
	tHttpUrl entry;

	tCfgIter itor(sFile);
	if(debug&6)
		cerr << "Reading backend file: " << sFile <<endl;

	if(!itor)
	{
		if(debug&6)
			cerr << "No backend data found, file ignored."<<endl;
		goto try_read_default;
	}
	
	while(itor.Next())
	{
		if(debug & LOG_DEBUG)
			cerr << "backends, got line: " << itor.sLine <<endl;

		trimBack(itor.sLine);

		if( entry.SetHttpUrl(itor.sLine)
				||	( itor.sLine.empty() && ! entry.sHost.empty() && ! entry.sPath.empty()) )
		{
			_FixPostPreSlashes(entry.sPath);
#ifdef DEBUG
			cerr << "Backend: " << sRepName << " <-- " << entry.ToURI(false) <<endl;
#endif		
			repoparms[sRepName].m_backends.push_back(entry);
			nAddCount++;
			entry.clear();
		}
		else if(ParseKeyValLine(itor.sLine, key, val))
		{
			if(keyEq("Site", key))
				entry.sHost=val;
			/* TODO: not supported yet, maybe add later - push to a vector of hosts and add multiple later
			if(keyEq("Aliases", key))
			{
				val+=" ";
				for(string::size_type posA(0), posB(0);
					posA<val.length();
					posA=posB+1)
				{
					posB=val.find_first_of(" \t\r\n\f\v", posA);
					if(posB!=posA)
						hosts.push_back(val.substr(posA, posB-posA));
				}
			}
			*/
			else if(keyEq("Archive-http", key) || keyEq("X-Archive-http", key))
			{
				entry.sPath=val;
			}
		}
		else
		{
			BARF("Bad backend description, around line " << sFile << ":"
					<< itor.reader.GetCurrentLine());
		}
	}

try_read_default:
	if(nAddCount || endsWithSzAr(sFile, ".default"))
		return;
	if(debug>4)
		cerr << "Trying to read replacement from " << sFile << ".default" <<endl;
	ReadBackendsFile(sFile+".default", sRepName);

}

void ShutDown()
{
	mapUrl2pVname.clear();
	repoparms.clear();
}

void ReadRewriteFile(const string & sFile, const string & sRepName)
{

	filereader reader;
	if(debug>4)
		cerr << "Reading rewrite file: " << sFile <<endl;
	reader.OpenFile(sFile);
	reader.CheckGoodState(true);
	reader.AddEofLines();

	tStrVec hosts, paths;
	string sLine, key, val;
	tHttpUrl url;
	
	while(reader.GetOneLine(sLine))
	{
		trimFront(sLine);

		if (0==sLine.compare(0, 1, "#"))
			continue;

		if (url.SetHttpUrl(sLine))
		{
			_FixPostPreSlashes(url.sPath);
			pair<tHttpUrl, const string*> info(url, GetRepoEntryNamePtr(sRepName));
			mapUrl2pVname.insert(info);
#ifdef DEBUG
						cerr << "Mapping: "<< url.ToURI(false)
						<< " -> "<< sRepName <<endl;
#endif
			continue;
		}

		if (sLine.empty()) // end of block, eof, ... -> commit it
		{
			if (hosts.empty() && paths.empty())
				continue; // dummy run or whitespace in a URL style list
			if ( !hosts.empty() && paths.empty())
			{
				cerr << "Warning, missing path spec for the site " << hosts[0] <<", ignoring mirror."<< endl;
				continue;
			}
			if ( !paths.empty() && hosts.empty())
			{
				BARF("Parse error, missing Site: field around line "
						<< sFile << ":"<< reader.GetCurrentLine());
			}
			for (tStrVecIterConst itHost=hosts.begin();
			itHost!=hosts.end(); 
			itHost++)
			{
				for (tStrVecIterConst itPath=paths.begin();
				itPath!=paths.end(); 
				itPath++)
				{
					//mapUrl2pVname[*itHost+*itPath]= &itHostiVec->first;
					tHttpUrl url;
					url.sHost=*itHost;
					url.sPath=*itPath;
					pair<tHttpUrl,const string*> info(url, GetRepoEntryNamePtr(sRepName));
					mapUrl2pVname.insert(info);

#ifdef DEBUG
						cerr << "Mapping: "<< *itHost << *itPath
						<< " -> "<< sRepName <<endl;
#endif
				}
			}
			hosts.clear();
			paths.clear();
			continue;
		}

		if(!ParseKeyValLine(sLine, key, val))
		{
			BARF("Error parsing rewrite definitions, around line "
					<< sFile << ":"<< reader.GetCurrentLine() << " : " << sLine);
		}
		
		// got something, interpret it...
		if( keyEq("Site", key) || keyEq("Alias", key) || keyEq("Aliases", key))
			Tokenize(val, SPACECHARS, hosts, true);
		
		if(keyEq("Archive-http", key) || keyEq("X-Archive-http", key))
		{
			// help STL saving some memory
			if(sPopularPath==val)
				paths.push_back(sPopularPath);
			else
			{
				_FixPostPreSlashes(val);
				paths.push_back(val);
			}
			continue;
		}
	}
}


tRepoData::~tRepoData()
{
	if(m_pHooks)
	{
		delete m_pHooks;
		m_pHooks=NULL;
	}
}

void ReadConfigDirectory(const char *szPath, bool bTestMode)
{
	char buf[PATH_MAX];
	g_testMode=bTestMode;
	if(!realpath(szPath, buf))
		BARF("Failed to open config directory");

	confdir=buf; // pickup the last config directory

#if defined(HAVE_WORDEXP) || defined(HAVE_GLOB)
	tStrDeq srcs=ExpandFilePattern(confdir+SZPATHSEP"*.conf", true);
	for(tStrDeq::const_iterator it=srcs.begin(); it!=srcs.end(); it++)
		ReadOneConfFile(*it);
#else
	ReadOneConfFile(confdir+SZPATHSEP"acng.conf");
#endif
}

void PostProcConfig(bool bDumpConfig)
{
	
	if(port.empty()) // heh?
		port=ACNG_DEF_PORT;

	// let's also apply the umask to the directory permissions
	{
		mode_t mask = umask(0);
		umask(mask); // restore it...
		dirperms &= ~mask;
		fileperms &= ~mask;
	}

    // postprocessing

#ifdef FORCE_CUSTOM_UMASK
	if(!sUmask.empty())
	{
		mode_t nUmask=0;
		if(sUmask.size()>4)
			BARF("Invalid umask length\n");
		for(unsigned int i=0; i<sUmask.size(); i++)
		{
			unsigned int val = sUmask[sUmask.size()-i-1]-'0';
			if(val>7)
				BARF("Invalid umask value\n");
			nUmask |= (val<<(3*i));
		
		}
		//cerr << "Got umask: " << nUmask <<endl;
		umask(nUmask);
	}
#endif
	
   if(cachedir.empty() || cachedir[0] != CPATHSEP)
	   BARF("Cache directory unknown or not absolute, terminating...");
   
   if(!rechecks::CompileExpressions())
	   BARF("An error occured while compiling file type regular expression!");
   
   if(acfg::tpthreadmax < 0)
	   acfg::tpthreadmax = MAX_VAL(int);
	   
   // get rid of duplicated and trailing slash(es)
	for(tStrPos pos; stmiss != (pos = cachedir.find(SZPATHSEP SZPATHSEP )); )
		cachedir.erase(pos, 1);

	cacheDirSlash=cachedir+CPATHSEP;

   if(!pidfile.empty() && pidfile.at(0) != CPATHSEP)
	   BARF("Pid file path must be absolute, terminating...");
   
   if(!acfg::agentname.empty())
	   acfg::agentheader=string("User-Agent: ")+acfg::agentname + "\r\n";
   
   trimString(acfg::requestapx);
   if(!acfg::requestapx.empty())
	   acfg::requestapx = unEscape(acfg::requestapx);

   if(!adminauth.empty())
	   adminauth=string("Basic ")+EncodeBase64Auth(adminauth);
   
   // create working paths before something else fails somewhere
   if(!fifopath.empty())
	   mkbasedir(acfg::fifopath);
   if(!cachedir.empty())
	   mkbasedir(acfg::cachedir);
   if(! pidfile.empty())
	   mkbasedir(acfg::pidfile);

   if(nettimeout < 5) {
	   cerr << "Warning, NetworkTimeout too small, assuming 5." << endl;
	   nettimeout = 5;
   }

   if(RESERVED_DEFVAL == forwardsoap)
	   forwardsoap = !forcemanaged;

   if(RESERVED_DEFVAL == exsupcount)
	   exsupcount = (extreshhold >= 5);

#ifdef _SC_NPROCESSORS_ONLN
	numcores = (int) sysconf(_SC_NPROCESSORS_ONLN);
#elif defined(_SC_NPROC_ONLN)
	numcores = (int) sysconf(_SC_NPROC_ONLN);
#endif

   if(!rechecks::CompileUncExpressions(
		   tmpDontcacherq.empty() ? tmpDontcache : tmpDontcacherq,
		   tmpDontcacheResolved.empty() ? tmpDontcache : tmpDontcacheResolved))
   {
	   BARF("An error occurred while compiling regular expression for non-cached paths!");
   }
   tmpDontcache.clear();
   tmpDontcacheResolved.clear();
   tmpDontcacherq.clear();

   if(usewrap == RESERVED_DEFVAL)
   {
	   usewrap=(qgrep("apt-cacher-ng", "/etc/hosts.deny")
			   || qgrep("apt-cacher-ng", "/etc/hosts.allow"));
#ifndef HAVE_LIBWRAP
	   cerr << "Warning: configured to use libwrap filters but feature is not built-in." <<endl;
#endif
   }

   if(maxtempdelay<0)
   {
	   cerr << "Invalid maxtempdelay value, using default" <<endl;
	   maxtempdelay=27;
   }

   if(redirmax == RESERVED_DEFVAL)
	   redirmax = forcemanaged ? 0 : ACFG_REDIRMAX_DEFAULT;

   if(!persistoutgoing)
	   pipelinelen = 1;

   if(!pipelinelen) {
	   cerr << "Warning, remote pipeline depth of 0 makes no sense, assuming 1." << endl;
	   pipelinelen = 1;
   }

   if (acfg::debug >= LOG_MORE || bDumpConfig)
	{
	   MYSTD::ostream &cmine(bDumpConfig ? cout : cerr);
		for (UINT i = 0; i < _countof(n2sTbl); i++)
			if (n2sTbl[i].ptr)
				cmine << n2sTbl[i].name << " = " << *(n2sTbl[i].ptr) << endl;

		if (acfg::debug >= LOG_DEBUG)
		{
			cerr << "escaped version:" << endl;
			for (UINT i = 0; i < _countof(n2sTbl); i++)
				if (n2sTbl[i].ptr)
				{
					cerr << n2sTbl[i].name << " = ";
					for (const char *p = n2sTbl[i].ptr->c_str(); *p; p++)
						if ('\\' == *p)
							cmine << "\\\\";
						else
							cmine << *p;
					cmine << endl;
				}
		}

		for (UINT i = 0; i < _countof(n2iTbl); i++)
			if (n2iTbl[i].ptr)
				cmine << n2iTbl[i].name << " = \"" << *(n2iTbl[i].ptr) << "\"\n";
	}

#ifndef DEBUG
   if(acfg::debug >= LOG_DEBUG)
	   cerr << "\n\nAdditional debugging information not compiled in.\n\n";
#endif
   
#if 0 //def DEBUG
#warning adding hook control pins
   for(tMapString2Hostivec::iterator it = repoparms.begin();
		   it!=repoparms.end() ; ++it)
   {
	   tHookHandler *p = new tHookHandler(it->first);
	   p->downDuration=10;
	   p->cmdCon = "logger wanna/connect";
	   p->cmdRel = "logger wanna/disconnect";
	   it->second.m_pHooks = p;
   }


   if(debug == -42)
   {
	   /*
	   for(tMapString2Hostivec::const_iterator it=mapRepName2Backends.begin();
			   it!=mapRepName2Backends.end(); it++)
	   {
		   for(tRepoData::const_iterator jit=it->second.begin();
				   jit != it->second.end(); jit++)
		   {
			   cout << jit->ToURI() <<endl;
		   }
	   }

	   for(tUrl2RepIter it=mapUrl2pVname.begin(); it!=mapUrl2pVname.end(); it++)
	   {
		   cout << it->first.ToURI(false) << " ___" << *(it->second) << endl;
	   }

	   exit(1);
	   */
   }
#endif
} // PostProcConfig

//! @brief Fires hook callbacks in the background thread
time_t BackgroundCleanup()
{
	time_t ret(END_OF_TIME), now(time(0));
	for (tRepMap::iterator it = repoparms.begin(); it != repoparms.end(); ++it)
	{
		if (!it->second.m_pHooks)
			continue;
		tHookHandler & hooks = *(static_cast<tHookHandler*> (it->second.m_pHooks));
		lockguard g(hooks);
		if (hooks.downTimeNext)
		{
			if (hooks.downTimeNext <= now) // time to execute
			{
				if(acfg::debug&LOG_MORE)
					aclog::misc(hooks.cmdRel, 'X');
				if(acfg::debug & LOG_FLUSH)
					aclog::flush();

				if(system(hooks.cmdRel.c_str()))
					aclog::err(tSS() << "Warning: " << hooks.cmdRel << " returned with error code.");
				hooks.downTimeNext = 0;
			}
			else // in future, use the soonest time
				ret = min(ret, hooks.downTimeNext);
		}
	}
	return ret;
}

#endif // MINIBUILD

} // namespace acfg

namespace rechecks
{
	MYSTD::pair<regex_t, bool> rex[ematchtype_max];

bool CompileExpressions()
{
	const char *pszExpStrings[] = {
			acfg::pfilepat.c_str(), acfg::vfilepat.c_str(), acfg::wfilepat.c_str(),
			BADSTUFF_PATTERN, PTHOSTS_PATTERN.c_str()
	};
	for(UINT i=0; i<_countof(pszExpStrings); i++)
	{
		if(! pszExpStrings[i] || ! pszExpStrings[i][0] )
			continue;

		int nErr=regcomp(&rex[i].first, pszExpStrings[i], REG_EXTENDED);
		if(nErr)
		{
			char buf[1024];
			regerror(nErr,  &rex[i].first, buf, sizeof(buf));
			buf[_countof(buf)-1]=0; // better be safe...
			MYSTD::cerr << buf << ": " << pszExpStrings[i] << MYSTD::endl;
			return false;
		}
		rex[i].second=true;
	}
	return true;
}

bool Match(cmstring &in, eMatchType type)
{
//	LOGSTARTs("MatchPattern");
//	LOG("type: " << type << in);
	if(!rex[type].second)
		return false;

	bool bRes = !regexec(&rex[type].first, in.c_str(), 0, NULL, 0);
//	LOG("result: " << (bRes ? "true" : "false"));
	return bRes;
}

eMatchType GetFiletype(const string & in) {
	if (Match(in, FILE_INDEX))
		return FILE_INDEX;
	if (Match(in, FILE_PKG))
		return FILE_PKG;
	return FILE_INVALID;
}

deque<regex_t> vecReqPatters, vecTgtPatterns;

#ifndef MINIBUILD
inline bool CompileUncachedRex(const string & token, bool bIsTgtPattern, bool bRecursiveCall)
{
	deque<regex_t> & patvec = bIsTgtPattern ? vecTgtPatterns : vecReqPatters;

	if (0!=token.compare(0, 5, "file:")) // pure pattern
	{
		UINT pos = patvec.size();
		patvec.resize(pos+1);
		return 0==regcomp(&patvec[pos], token.c_str(), REG_EXTENDED);
	}
	else if(!bRecursiveCall) // don't go further than one level
	{
		tStrDeq srcs = acfg::ExpandFileTokens(token);
		for(tStrDeq::const_iterator it=srcs.begin(); it!=srcs.end(); it++)
		{
			acfg::tCfgIter itor(*it);
			if(!itor)
			{
				cerr << "Error opening pattern file: " << *it <<endl;
				return false;
			}
			while(itor.Next())
			{
				if(!CompileUncachedRex(itor.sLine, bIsTgtPattern, true))
					return false;
			}
		}

		return true;
	}

	cerr << token << " is not supported here" <<endl;
	return false;
}


bool CompileUncExpressions(const string & req, const string & resolved)
{
	for(int i=0; i<2; ++i) // req, tgt, stop
		for(tSplitWalk split(i? &req : &resolved); split.Next(); )
			if (!CompileUncachedRex(split, i, false))
				return false;
	return true;
}

bool MatchUncacheableRequest(const string & in)
{
	LOGSTART2s("MatchUncacheableRequest", in << " against " << vecReqPatters.size() << " patterns");
	for(deque<regex_t>::const_iterator it=vecReqPatters.begin();
			it!=vecReqPatters.end(); it++)
	{
		if(!regexec(& (*it), in.c_str(), 0, NULL, 0))
			return true;
	}
	return false;
}

bool MatchUncacheableTarget(const string &in)
{
	for(deque<regex_t>::const_iterator it=vecTgtPatterns.begin();
			it!=vecTgtPatterns.end(); it++)
	{
		if(!regexec(& (*it), in.c_str(), 0, NULL, 0))
			return true;
	}
	return false;
}

#endif //MINIBUILD


} // namespace rechecks

mstring GetDirPart(const string &in)
{
	if(in.empty())
		return "";

	tStrPos end = in.find_last_of(CPATHSEP);
	if(end == stmiss) // none? don't care then
		return "";

	return in.substr(0, end+1);
}

void mkbasedir(const string & path)
{
	if(0==mkdir(GetDirPart(path).c_str(), acfg::dirperms) || EEXIST == errno)
		return; // should succeed in most cases

	UINT pos=0; // but skip the cache dir components, if possible
	if(startsWith(path, acfg::cacheDirSlash))
	{
		// pos=acfg::cachedir.size();
		pos=path.find("/", acfg::cachedir.size()+1);
	}
    for(; pos<path.size(); pos=path.find(SZPATHSEP, pos+1))
    {
        if(pos>0)
            mkdir(path.substr(0,pos).c_str(), acfg::dirperms);
    }
}



/*
int main(int argc, char **argv)
{
	if(argc<2)
		return -1;
	
	acfg::tHostInfo hi;
	cout << "Parsing " << argv[1] << ", result: " << hi.SetUrl(argv[1])<<endl;
	cout << "Host: " << hi.sHost <<", Port: " << hi.sPort << ", Path: " << hi.sPath<<endl;
	return 0;
}
*/