File: tproxy.c

package info (click to toggle)
transproxy 1.4-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 148 kB
  • ctags: 101
  • sloc: ansic: 1,563; sh: 136; makefile: 63
file content (2115 lines) | stat: -rw-r--r-- 52,236 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
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
/* vim:ai ts=4 sw=4
 * tproxy.c:
 *
 * This is a transparent proxy server. It can be started from inetd to
 * service HTTP requests, or run as a stand-alone daemon. HTTP requests
 * are transparently accepted and passed to the WWW proxy cache for
 * handling. The HTTP request line is modified into a form usable by
 * the WWW proxy cache. The destination WWW site name is extracted from
 * the HTTP headers to avoid DNS lookups.
 */

#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
# include <syslog.h>
#endif
#ifdef HAVE_PATHS_H
# include <paths.h>
#endif
#include <signal.h>
#include <fcntl.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>

#ifdef HAVE_GETOPT_H
# include <getopt.h>
#endif

#ifdef IPFILTER
# include <sys/ioctl.h>
# include <netinet/in_systm.h>
# include <netinet/ip.h>
# include <netinet/tcp.h>
# include <net/if.h>
# include <netinet/ip_compat.h>
# include <netinet/ip_fil.h>
# include <netinet/ip_nat.h>
#endif

#ifdef IPTABLES
# include <linux/netfilter_ipv4.h>
#endif

#ifdef TCP_WRAPPERS
# include <tcpd.h>
#endif

/* For Solaris */
#ifndef INADDR_NONE
# define INADDR_NONE		(in_addr_t)-1
#endif

/* For Linux */
#if defined(SIGCLD) && !defined(SIGCHLD)
# define SIGCHLD			SIGCLD
#endif

#ifndef _PATH_DEVNULL
# define _PATH_DEVNULL		"/dev/null"
#endif
#ifndef _PATH_VARRUN
# define _PATH_VARRUN		"/var/run/"
#endif

#include "acl.h"

#define ACTIVITY_TIMEOUT	120			/* 120 seconds, 2 minutes */
#define BUFFER_SIZE			(32769)		/* Requests must fit in this size */
#define REFERRER_SIZE		(1024)
#define HOSTNAME_SIZE		(256)

#define PS_METHOD			0
#define PS_METHOD_END		5
#define PS_URI				10
#define PS_URI_END			15
#define PS_VERSION			20
#define PS_HEADER			30
#define PS_HEADER_END		35
#define PS_POST_DATA		40
#define PS_END_OF_REQUEST	45
#define PS_HOST_HEADER		50	/* Needs 10 slots */
#define PS_REFERER_HEADER	60	/* Needs 10 slots */
#define PS_LENGTH_HEADER	70	/* Needs 20 slots */
#define PS_TRANSPARENT		100

#define RC_TRANSPARENT		1
#define RC_FORCED			2
#define RC_DNSLOOKUP		3
#define RC_NODNS			4

/*
 * Typedefs.
 */
typedef unsigned long	ip_address_t;
typedef unsigned char	byte_t;

typedef struct buffer_
{
	byte_t				buffer[BUFFER_SIZE];
	int					head;
	int					free_space;
}	buffer_t;

typedef struct connection_
{
	int					client_fd;
	int					proxy_fd;
	struct sockaddr_in	client_addr;
	struct sockaddr_in	dest_addr;
	buffer_t			read_buffer;
	buffer_t			request;
	int					parse_state;
	int					method_end_offset;
	int					url_offset;
	int					url_end_offset;
	int					version_offset;
	char				host_header[HOSTNAME_SIZE];
	int					host_header_length;
	char				referer_header[REFERRER_SIZE];
	int					referer_header_length;
	int					content_length;
	int					request_number;
}	connection_t;

/*
 * Macros.
 */
#define FD_MAX(a,b)		((a) > (b) ? (a) : (b))

/*
 * Function prototypes.
 */
static void usage(char *prog, char *opt);
static short getportnum(char *portnum);
static ip_address_t getipaddress(char *ipaddr);
static uid_t getuserid(char *user);
static uid_t getgroupid(uid_t uid);
static int bind_to_port(ip_address_t bind_ip, short bind_port);
static int connect_to_proxy(ip_address_t ip, short port);
static void lookup_hostname(struct sockaddr_in *addr, char *hostname, int hostlen, int needed);
static void server_main_loop(int sock, char *server_hostname, short server_port);
static void trans_proxy(int sock, struct sockaddr_in *addr,
						char *server_hostname, short server_port);
static int process_proxy_response(connection_t *conn, size_t last_read);
static int process_client_request(connection_t *conn, size_t last_read);
static int send_data(int fd, char *data, size_t length);
#if defined(DEBUG_INPUT_REQUESTS) || defined(DEBUG_OUTPUT_REQUESTS)
static void print_request(char *prefix, char *data, size_t length);
#endif
static void write_pid(char *prog);
static void term_signal(int sig);
static void alarm_signal(int sig);
#ifdef LOG_TO_FILE
static void hup_signal(int sig);
static void log_it(char *fmt, ...);
#endif

/*
 * Command line switches.
 */
static char				*prog;
static int				daemonize = 1;
static int				fully_transparent = 0;
static int				proxy_only = 0;
static char				*force_url = NULL;
static int				force_url_length;
#ifdef LOG_TO_FILE
static char				*log_file_name = NULL;
static FILE				*log_file = NULL;
#endif

#ifdef IPFILTER
/*
 * The /dev/ipnat device node.
 */
static int				natdev = -1;
#endif

#ifdef TCP_WRAPPERS
/*
 * The syslog levels for tcp_wrapper checking.
 */
int						deny_severity;
int						allow_severity;
#endif

/*
 * Main loop.
 */
int main(int argc, char **argv)
{
	int					arg;
	int					run_as_server = 0;
	ip_address_t		bind_ip = INADDR_ANY;
	short				bind_port = -1;
	char 				*server_hostname = NULL;
	short				server_port = -1;
	uid_t				run_uid = 0;
	gid_t				run_gid = 0;
#if !defined(DEBUG) && !defined(DEBUG_INPUT_REQUESTS) && !defined(DEBUG_OUTPUT_REQUESTS)
	int					fd;
#endif
	int					sock;
	struct sockaddr_in	addr;
	int					len;

	/*
	 * Get the name if the program.
	 */
	if ((prog = strrchr(argv[0], '/')) != NULL)
		++prog;
	else
		prog = argv[0];

	/*
	 * Reset the access control list.
	 */
	reset_acl();

	/*
	 * Parse the command line arguments.
	 */
	while ((arg = getopt(argc, argv, "dtps:r:b:f:l:a:")) != EOF)
	{
		switch (arg)
		{
		case 't':
			fully_transparent = 1;
			proxy_only = 0;
			break;

		case 'p':
			proxy_only = 1;
			fully_transparent = 0;
			break;

		case 's':
			run_as_server = 1;
			bind_port = getportnum(optarg);
			break;

		case 'd':
			if (run_as_server)
			{
				daemonize = 0;
			}
			else
			{
				usage(prog, "This option is valid when running as a server");
			}
			break;

		case 'b':
			if (run_as_server)
			{
				bind_ip = getipaddress(optarg);
			}
			else
			{
				usage(prog, "This option is valid when running as a server");
			}
			break;

		case 'r':
			if (run_as_server)
			{
				run_uid = getuserid(optarg);
				run_gid = getgroupid(run_uid);
			}
			else
			{
				usage(prog, "This option is valid when running as a server");
			}
			break;

		case 'a':
			if (run_as_server)
			{
				if (!add_acl(optarg))
					usage(prog, "ACL not in expected format");
			}
			else
			{
				usage(prog, "This option is valid when running as a server");
			}
			break;

		case 'f':
			force_url = optarg;
			force_url_length = strlen(force_url);
			break;

#ifdef LOG_TO_FILE
		case 'l':
			log_file_name = optarg;
			break;
#endif

		default:
		case '?':
			usage(prog, NULL);
			break;
		}
	}

	/*
	 * Process the remaining command line arguments.
	 */
	for (; optind < argc; ++optind)
	{
		if (server_hostname == NULL)
		{
			server_hostname = argv[optind];
		}
		else if (server_port == -1)
		{
			server_port = getportnum(argv[optind]);
		}
		else
		{
			usage(prog, "Extra arguments were specified.");
		}
	}

	/*
	 * Test to make sure required args were provided and are valid.
	 */
	if (!fully_transparent && server_hostname == NULL)
	{
		usage(prog, "No proxyhost was specified (or it was invalid).");
	}
	if (!fully_transparent && server_port == -1)
	{
		usage(prog, "No proxyport was specified (or it was invalid).");
	}
	if (run_as_server && (bind_ip == INADDR_NONE))
	{
		usage(prog, "The server ipaddr is invalid.");
	}
	if (run_as_server && (bind_port == -1))
	{
		usage(prog, "No server port was specified (or it was invalid).");
	}

	/*
	 * Set the current directory to the root filesystem.
	 */
	chdir("/");

#ifdef IPFILTER
	/*
	 * Now is a good time to open /dev/ipnat, before giving up our uid/gid.
	 */
	if ((natdev = open(IPL_NAT, O_RDONLY)) < 0)
	{
		perror("open(" IPL_NAT ")");
		exit(1);
	}
#endif

#ifdef LOG_TO_FILE
	/*
	 * Open the log file for the first time.
	 */
	if (log_file_name)
	{
		log_file = fopen(log_file_name, "a");
# ifdef LOG_TO_FILE_LINEBUFF
		if (log_file)
			setvbuf(log_file, NULL, _IOLBF, BUFSIZ);
# endif
	}
#endif

	/*
	 * See if we should run as a server.
	 */
	if (run_as_server)
	{
		/*
		 * Start by binding to the port, the child inherits this socket.
		 */
		sock = bind_to_port(bind_ip, bind_port);

		/*
		 * Start a server process.
		 */
		if (daemonize)
		{
			switch (fork())
			{
			case -1:
				/*
				 * We could not fork a daemon process.
				 */
				perror("fork()");
				exit(1);
			case 0:
				/*
				 * The child continues as the daemon process.
				 */
				break;
			default:
				/*
				 * Parent exits at this stage.
				 */
				_exit(0);
			}

			/*
			 * Start a new session and group.
			 */
			setsid();
		}

#if !defined(DEBUG) && !defined(DEBUG_INPUT_REQUESTS) && !defined(DEBUG_OUTPUT_REQUESTS)
		/*
		 * Point file descriptors to /dev/null, unless DEBUG is defined.
		 */
		if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) >= 0)
		{
			dup2(fd, STDIN_FILENO);
			dup2(fd, STDOUT_FILENO);
			dup2(fd, STDERR_FILENO);
			if (fd > STDERR_FILENO)
				close(fd);
		}
#endif

#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
		/*
		 * Open syslog for logging errors.
		 */
		openlog(prog, LOG_PID, LOG_DAEMON);
#endif

		/*
		 * Ignore some signals.
		 */
		if (daemonize)
			signal(SIGINT, SIG_IGN);
		signal(SIGQUIT, SIG_IGN);
		signal(SIGTSTP, SIG_IGN);
		signal(SIGCONT, SIG_IGN);
		signal(SIGPIPE, SIG_IGN);
		signal(SIGALRM, alarm_signal);
#ifdef LOG_TO_FILE
		signal(SIGHUP, hup_signal);
#else
		signal(SIGHUP, SIG_IGN);
#endif
		signal(SIGTERM, term_signal);

		/*
		 * Create a .pid file in /var/run.
		 */
		write_pid(prog);

		/*
		 * Drop back to an untrusted user.
		 */
		if (run_gid != 0)
			setgid(run_gid);
		if (run_uid != 0)
			setuid(run_uid);

		/*
		 * Handle the server main loop.
		 */
		server_main_loop(sock, server_hostname, server_port);

		/*
		 * Should never exit.
		 */
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
		closelog();
#endif
		exit(1);
	}

#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
	/*
	 * Open syslog for logging errors.
	 */
	openlog(prog, LOG_PID, LOG_DAEMON);
#endif

	/*
	 * We are running from inetd so find the peer address.
	 */
	len = sizeof(addr);
	if (getpeername(STDIN_FILENO, (struct sockaddr *)&addr, &len) < 0)
	{
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
		syslog(LOG_ERR, "getpeername(): %m");
		closelog();
#endif
		exit(1);
	}

	/*
	 * Set the keepalive socket option to on.
	 */
	{
		int		on = 1;
		setsockopt(STDIN_FILENO, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof(on));
	}

	/*
	 * We are running from inetd so process stdin.
	 */
	trans_proxy(STDIN_FILENO, &addr, server_hostname, server_port);
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
	closelog();
#endif

	return (0);
}

/*
 * Print some basic help information.
 */
static void usage(char *prog, char *opt)
{
	if (opt)
	{
		fprintf(stderr, "%s: %s\n", prog, opt);
	}
#ifdef LOG_TO_FILE
	fprintf(stderr, "usage: %s [-t | -p] [-f url] [-s port [-d] [-b ipaddr] [-r user] [-a acl]] [-l file] proxyhost proxyport\n", prog);
#else
	fprintf(stderr, "usage: %s [-t | -p] [-f url] [-s port [-d] [-b ipaddr] [-r user] [-a acl]] proxyhost proxyport\n", prog);
#endif
	fprintf(stderr, "    -t          Operate transparently, don't talk to a proxy.\n");
	fprintf(stderr, "    -p          Only talk to a proxy, disable direct fall-back.\n");
	fprintf(stderr, "    -f url      Force access to always go to specified URL.\n");
	fprintf(stderr, "    -s port     Run as a server bound to the specified port.\n");
	fprintf(stderr, "    -d          Do not background the daemon in server mode.\n");
	fprintf(stderr, "    -b ipaddr   Bind to the specified ipaddr in server mode.\n");
	fprintf(stderr, "    -r user     Run as the specified user in server mode.\n");
	fprintf(stderr, "    -a acl      Add an ACL to restrict connections in server mode.\n");
#ifdef LOG_TO_FILE
	fprintf(stderr, "    -l file     Log accesses to the specified file (relative to /).\n");
#endif
	exit(1);
}

/*
 * Return the port number, in network order, of the specified service.
 */
static short getportnum(char *portnum)
{
	char			*digits = portnum;
	struct servent	*serv;
	short			port;

	for (port = 0; isdigit((int)*digits); ++digits)
	{
		port = (port * 10) + (*digits - '0');
	}

	if ((*digits != '\0') || (port <= 0))
	{
		if ((serv = getservbyname(portnum, "tcp")) != NULL)
		{
			port = serv->s_port;
		}
		else
		{
			port = -1;
		}
		endservent();
	}
	else
		port = htons(port);

#ifdef DEBUG
	printf("Port lookup %s -> %hd\n", portnum, ntohs(port));
#endif

	return (port);
}

/*
 * Return the IP address of the specified host.
 */
static ip_address_t getipaddress(char *ipaddr)
{
	struct hostent	*host;
	ip_address_t	ip;

	if (((ip = inet_addr(ipaddr)) == INADDR_NONE)
	    &&
		(strcmp(ipaddr, "255.255.255.255") != 0))
	{
		if ((host = gethostbyname(ipaddr)) != NULL)
		{
			memcpy(&ip, host->h_addr, sizeof(ip));
		}
		endhostent();
	}

#ifdef DEBUG
	printf("IP lookup %s -> 0x%08lx\n", ipaddr, ntohl(ip));
#endif

	return (ip);
}

/*
 * Find the userid of the specified user.
 */
static uid_t getuserid(char *user)
{
	struct passwd	*pw;
	uid_t			uid;

	if ((pw = getpwnam(user)) != NULL)
	{
		uid = pw->pw_uid;
	}
	else if (*user == '#')
	{
		uid = (uid_t)atoi(&user[1]);
	}
	else
	{
		uid = -1;
	}

#ifdef DEBUG
	printf("User lookup %s -> %lu\n", user, (unsigned long)uid);
#endif

	endpwent();

	return (uid);
}

/*
 * Find the groupid of the specified user.
 */
static uid_t getgroupid(uid_t uid)
{
	struct passwd	*pw;
	gid_t			gid;

	if ((pw = getpwuid(uid)) != NULL)
	{
		gid = pw->pw_gid;
	}
	else
	{
		gid = -1;
	}

#ifdef DEBUG
	printf("Group lookup %lu -> %lu\n", (unsigned long)uid, (unsigned long)gid);
#endif

	endpwent();

	return (gid);
}

/*
 * Bind to the specified ip and port.
 */
static int bind_to_port(ip_address_t bind_ip, short bind_port)
{
	struct sockaddr_in	addr;
	int					sock;

	/*
	 * Allocate a socket.
	 */
	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("socket()");
		exit(1);
	}

	/*
	 * Set the SO_REUSEADDR option so we can start tproxy quickly if it dies.
	 */
	{
	 	int	on = 1;

		setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on));
	}

	/*
	 * Set the address to listen to.
	 */
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = bind_port;
	addr.sin_addr.s_addr = bind_ip;

	/*
	 * Bind our socket to the above address.
	 */
	if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
	{
		perror("bind()");
		close(sock);
		exit(1);
	}

	/*
	 * Establish a large listen backlog.
	 */
	if (listen(sock, SOMAXCONN) < 0)
	{
		perror("listen()");
		close(sock);
		exit(1);
	}

	return (sock);
}

/*
 * Connect to the proxy server.
 */
static int connect_to_proxy(ip_address_t ip, short port)
{
	struct sockaddr_in	addr;
	int					sock;

	/*
	 * Allocate a socket.
	 */
	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
		syslog(LOG_ERR, "socket(): %m");
#endif
		return (-1);
	}

	/*
	 * Set the address to connect to.
	 */
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = port;
	addr.sin_addr.s_addr = ip;

	/*
	 * Connect our socket to the above address.
	 */
	if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
	{
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
		syslog(LOG_WARNING, "connect(): %m");
#endif
		close(sock);
		return (-1);
	}

	/*
	 * Set the keepalive socket option to on.
	 */
	{
		int		on = 1;
		setsockopt(STDIN_FILENO, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof(on));
	}

	return (sock);
}

/*
 * Translate a sockaddr_in structure into a usable ASCII hostname.
 */
static void lookup_hostname(struct sockaddr_in *addr, char *hostname, int hostlen, int needed)
{
#ifdef DNS_LOOKUPS
	struct hostent	*host;

	if (needed)
	{
		if ((host = gethostbyaddr((char *)&addr->sin_addr,
								  sizeof(addr->sin_addr), AF_INET)) != NULL)
		{
			strncpy(hostname, host->h_name, hostlen);
			hostname[hostlen - 1] = '\0';
		}
		else
		{
			strncpy(hostname, inet_ntoa(addr->sin_addr), hostlen);
			hostname[hostlen - 1] = '\0';
# ifdef LOG_TO_SYSLOG
			syslog(LOG_WARNING, "DNS lookup for %s failed: %m", hostname);
# endif
		}
	}
	else
	{
# ifdef USELESS_DNS_LOOKUPS
		if ((host = gethostbyaddr((char *)&addr->sin_addr,
								  sizeof(addr->sin_addr), AF_INET)) != NULL)
		{
			strncpy(hostname, host->h_name, hostlen);
			hostname[hostlen - 1] = '\0';
		}
		else
		{
			strncpy(hostname, inet_ntoa(addr->sin_addr), hostlen);
			hostname[hostlen - 1] = '\0';
#  ifdef LOG_TO_SYSLOG
			syslog(LOG_WARNING, "DNS lookup for %s failed: %m", hostname);
#  endif
		}
# else
		strncpy(hostname, inet_ntoa(addr->sin_addr), hostlen);
		hostname[hostlen - 1] = '\0';
# endif
	}
#else
	strncpy(hostname, inet_ntoa(addr->sin_addr), hostlen);
	hostname[hostlen - 1] = '\0';
#endif
}

/*
 * This is the main loop when running as a server.
 */
static void server_main_loop(int sock, char *server_hostname, short server_port)
{
	int					new_sock;
	struct sockaddr_in	addr;
	int					len;
	pid_t				pid;
#ifdef DO_DOUBLE_FORK
	int					status;
#endif
#ifdef TCP_WRAPPERS
	struct request_info	req;
#endif

	/*
	 * Ignore dead children so no zombies should be left hanging. However some
	 * systems don't allow this, see the DO_DOUBLE_FORK option.
	 */
#ifdef SA_NOCLDWAIT
	/* Go BSD */
	{
		struct sigaction	sa;

		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = SIG_IGN;
		sa.sa_flags = SA_NOCLDWAIT;
		sigaction(SIGCHLD, &sa, NULL);
	}
#else
	/* Go Linux & SVR4 */
 	signal(SIGCHLD, SIG_IGN);
#endif

	for (;;)
	{
		/*
		 * Accept an incoming connection.
		 */
		len = sizeof(addr);
		while ((new_sock = accept(sock, (struct sockaddr *)&addr, &len)) < 0)
		{
			/*
			 * Connection resets are common enough to log them as debug only.
			 */
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
			if (errno != ECONNRESET)
				syslog(LOG_ERR, "accept(): %m");
# ifdef LOG_TO_SYSLOG
			else
				syslog(LOG_INFO, "accept(): %m");
# endif
#endif
		}

		/*
		 * Check if the access is allowed by ACL rule.
		 */
		if (!check_acl(&addr))
		{
#ifdef LOG_TO_SYSLOG
			syslog(LOG_AUTH | LOG_NOTICE, "ACL refused from %.100s",
					inet_ntoa(addr.sin_addr));
#endif
#ifdef LOG_TO_FILE
			log_it("ACL refused from %.100s", inet_ntoa(addr.sin_addr));
#endif
		}
		else
		{
#ifdef TCP_WRAPPERS
			/*
			 * Initialise the tcp_wrappers request structure. Get the information
			 * about the remote machine that is connecting to us.
			 */
			request_init(&req, RQ_DAEMON, "tproxy", RQ_FILE, new_sock, 0);
			fromhost(&req);

			/*
			 * Initialise the default logging facility and level. Note that
			 * we only allow for logging refused connections. There is enough
			 * logging for valid connections elsewhere.
			 */
			deny_severity = LOG_AUTH | LOG_NOTICE;

			/*
			 * Determine if access is allowed.
			 */
			if (!hosts_access(&req))
			{
# ifdef LOG_TO_SYSLOG
				syslog(deny_severity, "refused connection from %.100s", eval_client(&req));
# endif
# ifdef LOG_TO_FILE
				log_it("Refused connection from %.100s", eval_client(&req));
# endif
			}
			else
#endif
			{
				/*
				 * Create a new process to handle the connection.
				 */
				switch (pid = fork())
				{
				case -1:	/* Error */
					/*
					 * Under load conditions just ignore new connections.
					 */
					break;

				case 0:		/* Child */
#ifdef DO_DOUBLE_FORK
					/*
					 * Some systems like to fork again as the child. This makes the client
					 * run as a child of init so we don't have to handle reaping them.
					 * However all this forking slows us downm so it's optional.
					 */
					if (fork() > 0)	/* Parent */
						exit(0);
#endif

					/*
					 * Start the proxy work in the new socket.
					 */
					trans_proxy(new_sock, &addr, server_hostname, server_port);
					close(new_sock);
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
					closelog();
#endif
					exit(0);

#ifdef DO_DOUBLE_FORK
				default:	/* Parent */
					/*
					 * Wait for the child process to terminate. Since it forked another
					 * child to handle the request, it should terminate quickly.
					 */
					waitpid(pid, &status, 0);
					break;
#endif
				}
			}
		}

		/*
		 * Close the socket as the child handles the call.
		 */
		close(new_sock);
	}
}

/*
 * Perform the transparent proxy activity.
 */
static void trans_proxy(int sock, struct sockaddr_in *from_addr,
						char *server_hostname, short server_port)
{
	ip_address_t		server_ip;
	connection_t		conn;
	int					length;
	int					max_fd;
	fd_set				read_fd;
#ifdef IPFILTER
	natlookup_t			natlook;
#endif

	/*
	 * Initialise the connection structure.
	 */
	memset(&conn, 0, sizeof(connection_t));
	conn.client_fd = sock;
	conn.client_addr = *from_addr;
	conn.read_buffer.free_space = sizeof(conn.read_buffer.buffer);
	conn.request.free_space = sizeof(conn.request.buffer);
	conn.parse_state = PS_METHOD;
	conn.parse_state = PS_METHOD;

#ifdef IPTABLES
	/*
	 * The first thing we do is get the IP address that the client was
	 * trying to connected to. Here lies part of the magic. Linux-2.4
	 * introduces IPTABLES which uses getsockopt instead of getsockname
	 * for a more obvious interface.
	 */
	length = sizeof(conn.dest_addr);
	if (getsockopt(sock, SOL_IP, SO_ORIGINAL_DST, (char *)&conn.dest_addr, &length) < 0)
	{
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
		syslog(LOG_ERR, "getsockopt(SO_ORIGINAL_DST): %m");
#endif
		return;
	}
	
#else/*!IPTABLES*/

	/*
	 * The first thing we do is get the IP address that the client was
	 * trying to connected to. Here lies part of the magic. Normally
	 * getsockname returns our address, but not with transparent proxying.
	 */
	length = sizeof(conn.dest_addr);
	if (getsockname(sock, (struct sockaddr *)&conn.dest_addr, &length) < 0)
	{
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
		syslog(LOG_ERR, "getsockname(): %m");
#endif
		return;
	}

#ifdef IPFILTER
	/*
	 * However, under IPFILTER, we have to do additional work. The "to_addr"
	 * has been changed by the IP filter to trick the IP stack into
	 * processing the packet locally. We need to lookup the real remote
	 * address ourselves using an ioctl().
	 */

	/*
	 * Build up the NAT natlookup structure.
	 */
	memset(&natlook, 0, sizeof(natlook));
	natlook.nl_inip = conn.dest_addr.sin_addr;
	natlook.nl_outip = conn.client_addr.sin_addr;
	natlook.nl_flags = IPN_TCP;
	natlook.nl_inport = conn.dest_addr.sin_port;
	natlook.nl_outport = conn.client_addr.sin_port;

	/*
	 * Use the NAT device to lookup the mapping pair.
	 */
	if (ioctl(natdev, SIOCGNATL, &natlook) == -1)
	{
# if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
		syslog(LOG_ERR, "ioctl(SIOCGNATL): %m");
# endif
		return;
	}

	conn.dest_addr.sin_addr = natlook.nl_realip;
	conn.dest_addr.sin_port = natlook.nl_realport;
#endif

#endif/*!IPTABLES*/

	/*
	 * Lookup proxy server IP address. Because we do the lookup for every
	 * request we make use of DNS round-robin for load balancing.
	 */
	server_ip = getipaddress(server_hostname);
	if (server_ip == INADDR_NONE)
	{
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
		syslog(LOG_ERR, "Could not resolve IP address for proxy: %s", server_hostname);
#endif
		return;
	}

	/*
	 * Connect to the proxy server (or to the original destination in the case
	 * of fully transparent mode, or a failed connect to the proxy).
	 */
	if (fully_transparent ||
		(conn.proxy_fd = connect_to_proxy(server_ip, server_port)) == -1)
	{
		if (!proxy_only)
		{
			conn.proxy_fd = connect_to_proxy(conn.dest_addr.sin_addr.s_addr, conn.dest_addr.sin_port);
			fully_transparent = 1;
		}
		else
		{
			conn.proxy_fd = -1;
		}
	}
	if (conn.proxy_fd == -1)
	{
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
		if (fully_transparent)
			syslog(LOG_ERR, "Could not connect to destination");
		else if (proxy_only)
			syslog(LOG_ERR, "Could not connect to proxy host \"%s\"", server_hostname);
		else
			syslog(LOG_ERR, "Could not connect to proxy host \"%s\" or destination", server_hostname);
#endif
		return;
	}

	/*
	 * This loop acts a bit like the guy in the middle of a "bucket brigade".
	 * When the client passes some data, it gets handed off to the server,
	 * and vise-versa. However for data received from the client, it is
	 * buffered until a full request is received. Once a full request is
	 * received, the request is re-written before being sent to the server.
	 */
	for (;;)
	{
		/*
		 * Construct a select read mask from both file descriptors.
		 */
		FD_ZERO(&read_fd);
		FD_SET(conn.client_fd, &read_fd);
		FD_SET(conn.proxy_fd, &read_fd);
		max_fd = FD_MAX(conn.client_fd, conn.proxy_fd);

		/*
		 * Disconnect after some period of in-activity.
		 */
		alarm(ACTIVITY_TIMEOUT);

		/*
		 * Wait for some data to be read. If we get an signal then
		 * ignore the -1 return and try again.
		 */
		if (select(max_fd + 1, &read_fd, NULL, NULL, NULL) < 0)
		{
			if (errno != EINTR)
			{
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
				syslog(LOG_ERR, "select(): %m");
#endif
				close(conn.proxy_fd);
				return;
			}
		}

		/*
		 * We have something so disable the alarm.
		 */
		alarm(0);

		/*
		 * See if any data can be read from the client.
		 */
		if (FD_ISSET(conn.client_fd, &read_fd))
		{
			switch (length = read(conn.client_fd,
					&conn.request.buffer[conn.request.head],
					conn.request.free_space - conn.request.head))
			{
			case -1:
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
				if (errno != ECONNRESET)
					syslog(LOG_WARNING, "read(client) failed: %m");
# ifdef LOG_TO_SYSLOG
				else
					syslog(LOG_INFO, "read(client) failed: %m");
# endif
#endif
				close(conn.proxy_fd);
				return;

			case 0:
				close(conn.proxy_fd);
				return;

			default:
				/*
				 * Take into account this new data chunk.
				 */
				conn.request.head += length;

				/*
				 * Process requests read from the client. Returns 0 if a
				 * processed request could not be written to the proxy.
				 */
				if (!process_client_request(&conn, length))
				{
#ifdef LOG_TO_SYSLOG
					syslog(LOG_WARNING, "write(proxy) failed: %m");
#endif
					close(conn.proxy_fd);
					return;
				}
				break;
			}
		}

		/*
		 * See if any data can be read from the proxy.
		 */
		if (FD_ISSET(conn.proxy_fd, &read_fd))
		{
			switch (length = read(conn.proxy_fd,
					&conn.read_buffer.buffer[conn.read_buffer.head],
					conn.read_buffer.free_space - conn.read_buffer.head))
			{
			case -1:
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
				syslog(LOG_WARNING, "read(proxy) failed: %m");
#endif
				close(conn.proxy_fd);
				return;

			case 0:
				close(conn.proxy_fd);
				return;

			default:
				/*
				 * Take into account this new data chunk.
				 */
				conn.read_buffer.head += length;

				/*
				 * Process responses read from the proxy. Returns 0 if a
				 * processed request could not be written to the client.
				 */
				if (!process_proxy_response(&conn, length))
				{
#ifdef LOG_TO_SYSLOG
					syslog(LOG_WARNING, "write(client) failed: %m");
#endif
					close(conn.proxy_fd);
					return;
				}
				break;
			}
		}
	}
}

/*
 * Process responses read from the proxy. Returns 0 if a
 * processed request could not be written to the client.
 */
static int process_proxy_response(connection_t *conn, size_t last_read)
{
	/*
	 * Write the response to the client.
	 */
	if (!send_data(conn->client_fd, conn->read_buffer.buffer, conn->read_buffer.head))
		return (0);

	/*
	 * Now that all data is written, reset the "head" index.
	 */
	conn->read_buffer.head = 0;

	return (1);
}

/*
 * Process requests read from the client. Returns 0 if a
 * processed request could not be written to the proxy.
 *
 * Requests are parsed by way of a state machine. The
 * request is only written to the proxy when it has been
 * fully read and processed.
 */
static int process_client_request(connection_t *conn, size_t last_read)
{
	size_t	index;
	size_t	send_size;
	int		c;
	int		request_change;
#if defined(LOG_TO_SYSLOG) || defined(LOG_TO_FILE)
	char	client_host[HOSTNAME_SIZE];
#endif
	char	request_buffer[BUFFER_SIZE];
	char	request_port[16];
#if defined(LOG_TO_SYSLOG) || defined(LOG_TO_FILE)
	char	*url_string;
#endif

	/*
	 * Start the processing over again. Called when switching to
	 * transparent mode after a CONNECT method is received.
	 */
reprocess_buffer:

	/*
	 * Transparent mode simply sends any read data to the proxy.
	 */
	if (conn->parse_state == PS_TRANSPARENT)
	{
		/*
		 * Write the buffer to the proxy.
		 */
		if (!send_data(conn->proxy_fd, conn->request.buffer, conn->request.head))
			return (0);

		conn->request.head = 0;
	}
	else
	{
		/*
		 * Loop over the data that has just been added to the request buffer.
		 */
		index = conn->request.head - last_read;
		while (index < conn->request.head)
		{
			/*
			 * Fetch the next character to process.
			 */
			c = conn->request.buffer[index];

			/*
			 * Parse the data that we currently have. This state machine handles HTTP/0.9
			 * requests that don't include headers, as well as HTTP/1.x requests that
			 * do include headers and are terminated with a blank line.
			 */
			switch (conn->parse_state)
			{
			case PS_METHOD:
				if (c == '\r')					conn->parse_state = PS_METHOD + 1;
				else if (c == '\n')				conn->parse_state = PS_END_OF_REQUEST;
				else if (c == ' ') {			conn->parse_state = PS_METHOD_END;
					conn->method_end_offset = index;
				}
				break;

			case PS_METHOD + 1:
				if (c == '\n')					conn->parse_state = PS_END_OF_REQUEST;
				else							conn->parse_state = PS_METHOD;
				break;

			case PS_METHOD_END:
				if (c == '\r')					conn->parse_state = PS_METHOD_END + 1;
				else if (c == '\n')				conn->parse_state = PS_END_OF_REQUEST;
				else if (c != ' ') {			conn->parse_state = PS_URI;
					conn->url_offset = index;
				}
				break;

			case PS_METHOD_END + 1:
				if (c == '\n')					conn->parse_state = PS_END_OF_REQUEST;
				else							conn->parse_state = PS_METHOD_END;
				break;

			case PS_URI:
				if (c == '\r') {				conn->parse_state = PS_URI + 1;
					conn->url_end_offset = index;
				}
				else if (c == '\n') {			conn->parse_state = PS_END_OF_REQUEST;
					conn->url_end_offset = index;
				}
				else if (c == ' ') {			conn->parse_state = PS_URI_END;
					conn->url_end_offset = index;
				}
				break;

			case PS_URI + 1:
				if (c == '\n')					conn->parse_state = PS_END_OF_REQUEST;
				else							conn->parse_state = PS_URI;
				break;

			case PS_URI_END:
				if (c == '\r')					conn->parse_state = PS_URI_END + 1;
				else if (c == '\n')				conn->parse_state = PS_END_OF_REQUEST;
				else if (c != ' ') {			conn->parse_state = PS_VERSION;
					conn->version_offset = index;
				}
				break;

			case PS_URI_END + 1:
				if (c == '\n')					conn->parse_state = PS_END_OF_REQUEST;
				else							conn->parse_state = PS_URI_END;
				break;

			case PS_VERSION:
				if (c == '\r')					conn->parse_state = PS_VERSION + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				break;

			case PS_VERSION + 1:
				if (c == '\n')					conn->parse_state = PS_HEADER_END;
				else							conn->parse_state = PS_VERSION;
				break;

			case PS_HEADER:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				break;

			case PS_HEADER + 1:
				if (c == '\n')					conn->parse_state = PS_HEADER_END;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_HEADER_END:
				if (c == '\r')					conn->parse_state = PS_HEADER_END + 1;
				else if (c == '\n') {
					if (conn->content_length > 0)
						conn->parse_state = PS_POST_DATA;
					else
						conn->parse_state = PS_END_OF_REQUEST;
				}
				else if (c == 'H' || c == 'h')	conn->parse_state = PS_HOST_HEADER;
				else if (c == 'R' || c == 'r')	conn->parse_state = PS_REFERER_HEADER;
				else if (c == 'C' || c == 'c')	conn->parse_state = PS_LENGTH_HEADER;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_HEADER_END + 1:
				if (c == '\n') {
					if (conn->content_length > 0)
						conn->parse_state = PS_POST_DATA;
					else
						conn->parse_state = PS_END_OF_REQUEST;
				}
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_HOST_HEADER:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'O' || c == 'o')	conn->parse_state = PS_HOST_HEADER + 1;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_HOST_HEADER + 1:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'S' || c == 's')	conn->parse_state = PS_HOST_HEADER + 2;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_HOST_HEADER + 2:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'T' || c == 't')	conn->parse_state = PS_HOST_HEADER + 3;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_HOST_HEADER + 3:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == ':')				conn->parse_state = PS_HOST_HEADER + 4;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_HOST_HEADER + 4:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c != ' ') {			conn->parse_state = PS_HOST_HEADER + 5;
					conn->host_header[conn->host_header_length++] = c;
				}
				break;

			case PS_HOST_HEADER + 5:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (conn->host_header_length < (sizeof(conn->host_header) - 1))
					conn->host_header[conn->host_header_length++] = c;
				break;

			case PS_REFERER_HEADER:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'E' || c == 'e')	conn->parse_state = PS_REFERER_HEADER + 1;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_REFERER_HEADER + 1:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'F' || c == 'f')	conn->parse_state = PS_REFERER_HEADER + 2;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_REFERER_HEADER + 2:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'E' || c == 'e')	conn->parse_state = PS_REFERER_HEADER + 3;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_REFERER_HEADER + 3:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'R' || c == 'r')	conn->parse_state = PS_REFERER_HEADER + 4;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_REFERER_HEADER + 4:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'E' || c == 'e')	conn->parse_state = PS_REFERER_HEADER + 5;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_REFERER_HEADER + 5:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'R' || c == 'r')	conn->parse_state = PS_REFERER_HEADER + 6;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_REFERER_HEADER + 6:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == ':')				conn->parse_state = PS_REFERER_HEADER + 7;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_REFERER_HEADER + 7:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c != ' ') {			conn->parse_state = PS_REFERER_HEADER + 8;
					conn->referer_header[conn->referer_header_length++] = c;
				}
				break;

			case PS_REFERER_HEADER + 8:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (conn->referer_header_length < (sizeof(conn->referer_header) - 1))
					conn->referer_header[conn->referer_header_length++] = c;
				break;

			case PS_LENGTH_HEADER:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'O' || c == 'o')	conn->parse_state = PS_LENGTH_HEADER + 1;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 1:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'N' || c == 'n')	conn->parse_state = PS_LENGTH_HEADER + 2;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 2:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'T' || c == 't')	conn->parse_state = PS_LENGTH_HEADER + 3;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 3:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'E' || c == 'e')	conn->parse_state = PS_LENGTH_HEADER + 4;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 4:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'N' || c == 'n')	conn->parse_state = PS_LENGTH_HEADER + 5;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 5:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'T' || c == 't')	conn->parse_state = PS_LENGTH_HEADER + 6;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 6:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == '-')				conn->parse_state = PS_LENGTH_HEADER + 7;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 7:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'L' || c == 'l')	conn->parse_state = PS_LENGTH_HEADER + 8;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 8:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'E' || c == 'e')	conn->parse_state = PS_LENGTH_HEADER + 9;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 9:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'N' || c == 'n')	conn->parse_state = PS_LENGTH_HEADER + 10;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 10:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'G' || c == 'g')	conn->parse_state = PS_LENGTH_HEADER + 11;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 11:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'T' || c == 't')	conn->parse_state = PS_LENGTH_HEADER + 12;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 12:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == 'H' || c == 'h')	conn->parse_state = PS_LENGTH_HEADER + 13;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 13:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c == ':')				conn->parse_state = PS_LENGTH_HEADER + 14;
				else							conn->parse_state = PS_HEADER;
				break;

			case PS_LENGTH_HEADER + 14:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c != ' ') {			conn->parse_state = PS_LENGTH_HEADER + 15;
					if (c >= '0' && c <= '9')
						conn->content_length = c - '0';
					else
						conn->content_length = 0;
				}
				break;

			case PS_LENGTH_HEADER + 15:
				if (c == '\r')					conn->parse_state = PS_HEADER + 1;
				else if (c == '\n')				conn->parse_state = PS_HEADER_END;
				else if (c >= '0' && c <= '9') {
					conn->content_length *= 10;
					conn->content_length += c - '0';
				}
				break;

			case PS_POST_DATA:
				if (conn->content_length <= 1)	conn->parse_state = PS_END_OF_REQUEST;
				else
					--conn->content_length;
				break;

			case PS_TRANSPARENT:
				break;
			}

			/*
			 * We have now officially "consumed" the character.
			 */
			++index;

#ifdef DEBUG
			/*
			 * Print the current character and the parse state.
			 */
			if (c >= ' ' && c <= '~')
				printf("Char:    %c, parse state %d\n", c, conn->parse_state);
			else
				printf("Char: 0x%02x, parse state %d\n", c, conn->parse_state);
#endif

			/*
			 * OK we have parsed a complete request.
			 */
			if (conn->parse_state == PS_END_OF_REQUEST)
			{
				/*
				 * Keep track of how many requests per connection.
				 */
				++conn->request_number;

				/*
				 * If we didn't find a Host: header then do a DNS lookup.
				 */
				if (!fully_transparent && conn->host_header_length == 0)
				{
					lookup_hostname(&conn->dest_addr, conn->host_header,
							sizeof(conn->host_header), 1);
					conn->host_header_length = strlen(conn->host_header);

					request_change = RC_DNSLOOKUP;
				}
				else
				{
					conn->host_header[conn->host_header_length] = '\0';

					request_change = RC_NODNS;
				}

#ifdef DEBUG_INPUT_REQUESTS
				/*
				 * For debugging dump out the original request.
				 */
				print_request("Got  : ", conn->request.buffer, index);
#endif

				/*
				 * Build the resulting request into "request_buffer" and set "send_size"
				 * to the length of the request. This enables the final request to be
				 * written with a single write(2) system call. This should be more
				 * efficient for both transproxy and the proxy.
				 */
				if ((fully_transparent) ||
					(strncasecmp(conn->request.buffer, "CONNECT ", 8) == 0))
				{
					/*
					 * Leave the request as it is. Transparent mode is usefull for
					 * operation in a proxy firewall. Or HTTPS protocol doesn't
					 * like modifications so just pass the request on.
					 */
					memcpy(request_buffer, conn->request.buffer, index);
					send_size = index;

					request_change = RC_TRANSPARENT;
				}
				else if (force_url && conn->url_offset > 0)
				{
					/*
					 * Check if the request was referred to by the forced URL.
					 */
					if ((conn->referer_header_length > 0) &&
						(strcmp(conn->referer_header, force_url) == 0))
					{
						/*
						 * It appears that the request is for a page that is
						 * referred to by the original forced URL. In this case
						 * we must let it pass un-changed.
						 */
						memcpy(request_buffer, conn->request.buffer, index);
						send_size = index;
					}
					else
					{
						/*
						 * Force the request to the configured URL. Any images referred to
						 * by this forced URL will work because of the previous check for
						 * requests that have been referred to by the forced URL.
						 */
						send_size = 0;
						memcpy(&request_buffer[send_size], conn->request.buffer, conn->url_offset);
						send_size += conn->url_offset;
						memcpy(&request_buffer[send_size], force_url, force_url_length);
						send_size += force_url_length;
						memcpy(&request_buffer[send_size], &conn->request.buffer[conn->url_end_offset], index - conn->url_end_offset);
						send_size += index - conn->url_end_offset;
						conn->url_end_offset = conn->url_offset + force_url_length;
					}

					request_change = RC_FORCED;
				}
				else if (conn->url_offset > 0 &&
						 conn->request.buffer[conn->url_offset] == '/')
				{
					/*
					 * The request was provided with a URI so we must re-write the request
					 * to a URL of the form {http://hostname}/URI.
					 */
					send_size = 0;
					memcpy(&request_buffer[send_size], conn->request.buffer, conn->url_offset);
					send_size += conn->url_offset;
					memcpy(&request_buffer[send_size], "http://", 7);
					send_size += 7;
					conn->url_end_offset += 7;
					memcpy(&request_buffer[send_size], conn->host_header, conn->host_header_length);
					send_size += conn->host_header_length;
					conn->url_end_offset += conn->host_header_length;
					if ((ntohs(conn->dest_addr.sin_port) != 80) &&
#ifdef USE_STRSTR_BUG
						(strstr(conn->host_header, ":") == NULL))
#else
						(strchr(conn->host_header, ':') == NULL))
#endif
					{
						sprintf(request_port, ":%u", ntohs(conn->dest_addr.sin_port));
						memcpy(&request_buffer[send_size], request_port, strlen(request_port));
						send_size += strlen(request_port);
						conn->url_end_offset += strlen(request_port);
					}
					memcpy(&request_buffer[send_size], &conn->request.buffer[conn->url_offset], index - conn->url_offset);
					send_size += index - conn->url_offset;
				}
				else
				{
					/*
					 * The request didn't appear to have a URI or URL specified. so
					 * leave the request as it is.
					 */
					memcpy(request_buffer, conn->request.buffer, index);
					send_size = index;

					request_change = RC_TRANSPARENT;
				}

				/*
				 * Write the request to the proxy.
				 */
				if (!send_data(conn->proxy_fd, request_buffer, send_size))
					return (0);

#ifdef DEBUG_OUTPUT_REQUESTS
				/*
				 * For debugging dump out the new request.
				 */
				print_request("Sent : ", request_buffer, send_size);
#endif

#if defined(LOG_TO_SYSLOG) || defined(LOG_TO_FILE)
				/*
				 * Find a pretty name for the client.
				 */
				lookup_hostname(&conn->client_addr, client_host, sizeof(client_host), 0);

				/*
				 * Get the URL for logging.
				 */
				if (conn->url_offset > 0)
				{
					url_string = &request_buffer[conn->url_offset];
					request_buffer[conn->url_end_offset] = '\0';
				}
				else
					url_string = "-";

				/*
				 * Log the request.
				 */
				switch (request_change)
				{
				case RC_TRANSPARENT:
# ifdef LOG_TO_SYSLOG
					syslog(LOG_NOTICE, "Transparent   %d %s -> %s",
							conn->request_number, client_host, url_string);
# endif
# ifdef LOG_TO_FILE
					log_it("Transparent   %d %s -> %s",
							conn->request_number, client_host, url_string);
# endif
					break;

				case RC_FORCED:
# ifdef LOG_TO_SYSLOG
					syslog(LOG_NOTICE, "Forced        %d %s -> %s",
							conn->request_number, client_host, url_string);
# endif
# ifdef LOG_TO_FILE
					log_it("Forced        %d %s -> %s",
							conn->request_number, client_host, url_string);
# endif
					break;

				case RC_DNSLOOKUP:
# ifdef LOG_TO_SYSLOG
					syslog(LOG_NOTICE, "Request       %d %s -> %s",
							conn->request_number, client_host, url_string);
# endif
# ifdef LOG_TO_FILE
					log_it("Request       %d %s -> %s",
							conn->request_number, client_host, url_string);
# endif
					break;

				case RC_NODNS:
# ifdef LOG_TO_SYSLOG
					syslog(LOG_NOTICE, "Request_NoDNS %d %s -> %s",
							conn->request_number, client_host, url_string);
# endif
# ifdef LOG_TO_FILE
					log_it("Request_NoDNS %d %s -> %s",
							conn->request_number, client_host, url_string);
# endif
					break;
				}
#endif

				/*
				 * If there is any more data after the current request,
				 * then shift it down in the buffer. Then continue with
				 * the next request.
				 */
				if (index < conn->request.head)
				{
					memcpy(conn->request.buffer, &conn->request.buffer[index],
							conn->request.head - index);
					conn->request.head -= index;
				}
				else
					conn->request.head = 0;

				/*
				 * It we received a CONNECT method then we break out of
				 * the request parsing mode and simply pass data to the
				 * proxy transparently.
				 */
				if (strncasecmp(request_buffer, "CONNECT ", 8) == 0)
				{
					/*
					 * Switch the parser state to transparent mode.
					 */
					conn->parse_state = PS_TRANSPARENT;

					/*
					 * Check if there is any data in the buffer that
					 * should be sent now in transparent mode.
					 */
					goto reprocess_buffer;
				}
				else
				{
					/*
					 * Re-initialise the parser state.
					 */
					conn->parse_state = PS_METHOD;
					conn->url_offset = 0;
					conn->version_offset = 0;
					conn->host_header[0] = '\0';
					conn->host_header_length = 0;
					conn->referer_header_length = 0;
					conn->content_length = 0;
				}
			}
		}
	}

	return (1);
}

/*
 * Send data to a file descriptor (sock). Re-try if the write returns
 * after not sending all of the data.
 */
static int send_data(int fd, char *data, size_t length)
{
	size_t	index;
	size_t	written;

	/*
	 * Loop while there is data to process.
	 */
	for (index = 0; index < length; index += written)
	{
		written = write(fd, &data[index], length - index);

		if (written < 0)
			return (0);
	}

	return (1);
}

#if defined(DEBUG_INPUT_REQUESTS) || defined(DEBUG_OUTPUT_REQUESTS)
/*
 * Print an HTTP request.
 */
static void print_request(char *prefix, char *data, size_t length)
{
	size_t	index;
	int		c;
	int		print_prefix = 1;

	for (index = 0; index < length; ++index)
	{
		if (print_prefix)
			printf("%s", prefix);

		c = data[index];

		if (c >= ' ' && c <= '~')
			printf("%c", c);
		else if (c == '\r')
			printf("\\r");
		else if (c == '\n')
			printf("\\n\n");
		else
			printf(".");

		print_prefix = (c == '\n');
	}

	if (!print_prefix)
		printf("\n");
}
#endif

/*
 * Write out a pid file.
 */
static void write_pid(char *prog)
{
	char	filename[1024];
	FILE	*fp;

	sprintf(filename, "%s%s.pid", _PATH_VARRUN, prog);
	if ((fp = fopen(filename, "w")) != NULL)
	{
		fprintf(fp, "%lu\n", (unsigned long)getpid());
		fclose(fp);
	}
}

/*
 * Catch alarm signals and exit.
 */
static void alarm_signal(int sig)
{
#if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
	syslog(LOG_NOTICE, "Alarm signal caught - connection timeout");
#endif
	exit(1);
}

/*
 * Catch termination signal and exit.
 */
static void term_signal(int sig)
{
	char	filename[1024];

	sprintf(filename, "%s%s.pid", _PATH_VARRUN, prog);
	unlink(filename);

#ifdef LOG_TO_SYSLOG
	syslog(LOG_NOTICE, "Termination signal caught - exiting");
#endif
	exit(1);
}

#ifdef LOG_TO_FILE
/*
 * Catch HUP signals and re-open the log file.
 */
static void hup_signal(int sig)
{
	signal(sig, hup_signal);

	/*
	 * Close the current log file.
	 */
	if (log_file)
	{
		fclose(log_file);
		log_file = NULL;
	}

	/*
	 * Re-open the log file if it is closed.
	 */
	if (log_file == NULL && log_file_name)
	{
		log_file = fopen(log_file_name, "a");
# ifdef LOG_TO_FILE_LINEBUFF
		if (log_file)
			setvbuf(log_file, NULL, _IOLBF, BUFSIZ);
# endif
	}

# if defined(LOG_TO_SYSLOG) || defined(LOG_FAULTS_TO_SYSLOG)
	if (log_file)
		syslog(LOG_NOTICE, "HUP signal caught - re-open log '%s'", log_file_name);
	else if (log_file_name)
		syslog(LOG_NOTICE, "HUP signal caught - re-open failed '%s'", log_file_name);
# endif
}

/*
 * Append an entry to the log file.
 */
static void log_it(char *fmt, ...)
{
	time_t	now;
	char	date[20];
	va_list	args;

	if (log_file)
	{
		time(&now);
		strftime(date, sizeof(date), "%Y/%m/%d %H:%M:%S", localtime(&now));
		fprintf(log_file, "%s  ", date);
		va_start(args, fmt);
		vfprintf(log_file, fmt, args);
		va_end(args);
		fprintf(log_file, "\n");
	}
}
#endif