summaryrefslogtreecommitdiff
path: root/src/reqs.c
blob: 516851dfe59a9a650c8c33ad48234a436b66f6f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
/* $Id: reqs.c,v 1.96 2003-04-16 18:11:58 rjkaes Exp $
 *
 * This is where all the work in tinyproxy is actually done. Incoming
 * connections have a new child created for them. The child then
 * processes the headers from the client, the response from the server,
 * and then relays the bytes between the two.
 *
 * Copyright (C) 1998	    Steven Young
 * Copyright (C) 1999-2002  Robert James Kaes (rjkaes@flarenet.com)
 * Copyright (C) 2000       Chris Lightfoot (chris@ex-parrot.com)
 * Copyright (C) 2002       Petr Lampa (lampa@fit.vutbr.cz)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 */

#include "tinyproxy.h"

#include "acl.h"
#include "anonymous.h"
#include "buffer.h"
#include "conns.h"
#include "filter.h"
#include "hashmap.h"
#include "heap.h"
#include "htmlerror.h"
#include "log.h"
#include "network.h"
#include "regexp.h"
#include "reqs.h"
#include "sock.h"
#include "stats.h"
#include "text.h"
#include "utils.h"
#include "vector.h"

/*
 * Maximum length of a HTTP line
 */
#define HTTP_LINE_LENGTH (MAXBUFFSIZE / 6)

/*
 * Macro to help test if the Upstream proxy supported is compiled in and
 * enabled.
 */
#ifdef UPSTREAM_SUPPORT
#  define UPSTREAM_CONFIGURED() (config.upstream_name && config.upstream_port != -1)
#else
#  define UPSTREAM_CONFIGURED() (0)
#endif

/*
 * Codify the test for the carriage return and new line characters.
 */
#define CHECK_CRLF(header, len) ((len == 1 && header[0] == '\n') || (len == 2 && header[0] == '\r' && header[1] == '\n'))

/*
 * This is a global variable which stores which ports are allowed by
 * the CONNECT method.  It's a security thing.
 */
static vector_t ports_allowed_by_connect = NULL;

/*
 * Now, this routine adds a "port" to the list.  It also creates the list if
 * it hasn't already by done.
 */
void
add_connect_port_allowed(int port)
{
	if (!ports_allowed_by_connect) {
		ports_allowed_by_connect = vector_create();
		if (!ports_allowed_by_connect) {
			log_message(LOG_WARNING, "Could not create a list of allowed CONNECT ports");
			return;
		}
	}

	log_message(LOG_INFO, "Adding Port [%d] to the list allowed by CONNECT", port);
	vector_insert(ports_allowed_by_connect, (void **)&port, sizeof(port));
}

/*
 * This routine checks to see if a port is allowed in the CONNECT method.
 *
 * Returns: 1 if allowed
 *          0 if denied
 *          negative upon error
 */
static int
check_allowed_connect_ports(int port)
{
	ssize_t i;
	int *data;

	/*
	 * If the port list doesn't exist, allow everything.  This might need
	 * to be changed in the future.
	 */
	if (!ports_allowed_by_connect)
		return 1;

	for (i = 0; i < vector_length(ports_allowed_by_connect); ++i) {
		if (vector_getentry(ports_allowed_by_connect, i, (void **)&data) < 0)
			return -1;

		if (*data == port)
			return 1;
	}

	return 0;
}

/*
 * Read in the first line from the client (the request line for HTTP
 * connections. The request line is allocated from the heap, but it must
 * be freed in another function.
 */
static int
read_request_line(struct conn_s *connptr)
{
	ssize_t len;

      retry:
	len = readline(connptr->client_fd, &connptr->request_line);
	if (len <= 0) {
		log_message(LOG_ERR,
			    "read_request_line: Client (file descriptor: %d) closed socket before read.",
			    connptr->client_fd);

		return -1;
	}

	/*
	 * Strip the new line and character return from the string.
	 */
	if (chomp(connptr->request_line, len) == len) {
		/*
		 * If the number of characters removed is the same as the
		 * length then it was a blank line. Free the buffer and
		 * try again (since we're looking for a request line.)
		 */
		safefree(connptr->request_line);
		goto retry;
	}

	log_message(LOG_CONN, "Request (file descriptor %d): %s",
		    connptr->client_fd, connptr->request_line);

	return 0;
}

/*
 * This structure holds the information pulled from a URL request.
 */
struct request_s {
	char *method;
	char *protocol;

	char *host;
	uint16_t port;

	char *path;
};

static void
free_request_struct(struct request_s *request)
{
	if (!request)
		return;

	safefree(request->method);
	safefree(request->protocol);

	if (request->host)
		safefree(request->host);
	if (request->path)
		safefree(request->path);

	safefree(request);
}

/*
 * Take a host string and if there is a username/password part, strip
 * it off.
 */
static void
strip_username_password(char* host)
{
	char *ptr1, *ptr2;

	if ((ptr1 = strchr(host, '@')) != NULL) {
		ptr1++; /* move to one past the @ symbol */
		ptr2 = host;

		/* copy the bytes up to the NUL */
		while (*ptr1) 
			*ptr2++ = *ptr1++;
		*ptr2 = '\0';
	}
}

/*
 * Pull the information out of the URL line.  This will handle both HTTP
 * and FTP (proxied) URLs.
 */
static int
extract_http_url(const char *url, struct request_s *request)
{
	request->host = safemalloc(strlen(url) + 1);
	request->path = safemalloc(strlen(url) + 1);

	if (!request->host || !request->path)
		goto ERROR_EXIT;

	if (sscanf
	    (url, "%[^:/]:%hu%s", request->host, &request->port,
	     request->path) == 3) ;
	else if (sscanf(url, "%[^/]%s", request->host, request->path) == 2)
		request->port = 80;
	else if (sscanf(url, "%[^:/]:%hu", request->host, &request->port)
		 == 2)
		strcpy(request->path, "/");
	else if (sscanf(url, "%[^/]", request->host) == 1) {
		request->port = 80;
		strcpy(request->path, "/");
	} else {
		log_message(LOG_ERR, "extract_http_url: Can't parse URL.");
		goto ERROR_EXIT;
	}

	/* Remove the username/password if they're present */
	strip_username_password(request->host);

	return 0;

  ERROR_EXIT:
	if (request->host)
		safefree(request->host);
	if (request->path)
		safefree(request->path);

	return -1;
}

/*
 * Extract the URL from a SSL connection.
 */
static int
extract_ssl_url(const char *url, struct request_s *request)
{
	request->host = safemalloc(strlen(url) + 1);
	if (!request->host)
		return -1;

	if (sscanf(url, "%[^:]:%hu", request->host, &request->port) == 2) ;
	else if (sscanf(url, "%s", request->host) == 1)
		request->port = 443;
	else {
		log_message(LOG_ERR, "extract_ssl_url: Can't parse URL.");

		safefree(request->host);
		return -1;
	}

	/* Remove the username/password if they're present */
	strip_username_password(request->host);

	return 0;
}

/*
 * Build a URL from parts.
 */
static int
build_url(char **url, const char *host, int port, const char *path)
{
	int len;

	assert(url != NULL);
	assert(host != NULL);
	assert(port > 0 && port < 32768);
	assert(path != NULL);

	len = strlen(host) + strlen(path) + 14;
	*url = safemalloc(len);
	if (*url == NULL)
		return -1;

	return snprintf(*url, len, "http://%s:%d%s", host, port, path);
}

/*
 * Create a connection for HTTP connections.
 */
static int
establish_http_connection(struct conn_s *connptr, struct request_s *request)
{
	return write_message(connptr->server_fd,
			     "%s %s HTTP/1.0\r\n" \
			     "Host: %s:%u\r\n" \
			     "Connection: close\r\n",
			     request->method, request->path,
			     request->host, request->port);
}

/*
 * These two defines are for the SSL tunneling.
 */
#define SSL_CONNECTION_RESPONSE "HTTP/1.0 200 Connection established"
#define PROXY_AGENT "Proxy-agent: " PACKAGE "/" VERSION

/*
 * Send the appropriate response to the client to establish a SSL
 * connection.
 */
static inline int
send_ssl_response(struct conn_s *connptr)
{
	return write_message(connptr->client_fd,
			     "%s\r\n" \
			     "%s\r\n" \
			     "\r\n",
			     SSL_CONNECTION_RESPONSE, PROXY_AGENT);
}

/*
 * Break the request line apart and figure out where to connect and
 * build a new request line. Finally connect to the remote server.
 */
static struct request_s *
process_request(struct conn_s *connptr, hashmap_t hashofheaders)
{
	char *url;
	struct request_s *request;

	int ret;

	size_t request_len;

	/* NULL out all the fields so frees don't cause segfaults. */
	request = safecalloc(1, sizeof(struct request_s));
	if (!request)
		return NULL;

	request_len = strlen(connptr->request_line) + 1;

	request->method = safemalloc(request_len);
	url = safemalloc(request_len);
	request->protocol = safemalloc(request_len);

	if (!request->method || !url || !request->protocol) {
		safefree(url);
		free_request_struct(request);

		return NULL;
	}

	ret =
	    sscanf(connptr->request_line, "%[^ ] %[^ ] %[^ ]",
		   request->method, url, request->protocol);
	if (ret < 2) {
		log_message(LOG_ERR,
			    "process_request: Bad Request on file descriptor %d",
			    connptr->client_fd);
		indicate_http_error(connptr, 400, "Bad Request",
				    "detail", "Request has an invalid format",
				    "url", url,
				    NULL);

		safefree(url);
		free_request_struct(request);

		return NULL;
	}

	/* 
	 * FIXME: We need to add code for the simple HTTP/0.9 style GET
	 * request.
	 */

	if (!url) {
		log_message(LOG_ERR,
			    "process_request: Null URL on file descriptor %d",
			    connptr->client_fd);
		indicate_http_error(connptr, 400, "Bad Request",
				    "detail", "Request has an empty URL",
				    "url", url,
				    NULL);

		safefree(url);
		free_request_struct(request);

		return NULL;
	}

	if (strncasecmp(url, "http://", 7) == 0
	    || (UPSTREAM_CONFIGURED() && strncasecmp(url, "ftp://", 6) == 0)) {
		char *skipped_type = strstr(url, "//") + 2;

		if (extract_http_url(skipped_type, request) < 0) {
			indicate_http_error(connptr, 400, "Bad Request",
					    "detail", "Could not parse URL",
					    "url", url,
					    NULL);

			safefree(url);
			free_request_struct(request);

			return NULL;
		}
	} else if (strcmp(request->method, "CONNECT") == 0) {
		if (extract_ssl_url(url, request) < 0) {
			indicate_http_error(connptr, 400, "Bad Request",
					    "detail", "Could not parse URL",
					    "url", url,
					    NULL);

			safefree(url);
			free_request_struct(request);

			return NULL;
		}

		/* Verify that the port in the CONNECT method is allowed */
		if (check_allowed_connect_ports(request->port) <= 0) {
			indicate_http_error(connptr, 403, "Access violation",
					    "detail", "The CONNECT method not allowed " \
					              "with the port you tried to use.",
					    "url", url,
					    NULL);
			log_message(LOG_INFO, "Refused CONNECT method on port %d",
				    request->port);

			safefree(url);
			free_request_struct(request);

			return NULL;
		}
		
		connptr->connect_method = TRUE;
	} else {
#ifdef TRANSPARENT_PROXY
		/*
		 * This section of code is used for the transparent proxy
		 * option.  You will need to configure your firewall to
		 * redirect all connections for HTTP traffic to tinyproxy
		 * for this to work properly.
		 *
		 * This code was written by Petr Lampa <lampa@fit.vutbr.cz>
		 */
		int length;
		char *data;
		length = hashmap_entry_by_key(hashofheaders, "host", (void **)&data);
		if (length <= 0) {
			struct sockaddr_in dest_addr;

			if (getsockname(connptr->client_fd, (struct sockaddr *)&dest_addr, &length) < 0) {
				log_message(LOG_ERR,
					    "process_request: cannot get destination IP for %d",
					    connptr->client_fd);
				indicate_http_error(connptr, 400, "Bad Request",
						    "detail", "Unknown destination",
						    "url", url,
						    NULL);
				safefree(url);
				free_request_struct(request);
				return NULL;
			} 
			request->host = safemalloc(17);
			strcpy(request->host, inet_ntoa(dest_addr.sin_addr));
			request->port = ntohs(dest_addr.sin_port);
			request->path = safemalloc(strlen(url) + 1);
			strcpy(request->path, url);
			safefree(url);
			build_url(&url, request->host, request->port, request->path);
			log_message(LOG_INFO,
				    "process_request: trans IP %s %s for %d",
				    request->method, url, connptr->client_fd);
		} else {
			request->host = safemalloc(length+1);
			if (sscanf(data, "%[^:]:%hu", request->host, &request->port) != 2) {
				strcpy(request->host, data);
				request->port = 80;
			}
			request->path = safemalloc(strlen(url) + 1);
			strcpy(request->path, url);
			safefree(url);
			build_url(&url, request->host, request->port, request->path);
			log_message(LOG_INFO,
				    "process_request: trans Host %s %s for %d",
				    request->method, url, connptr->client_fd);
		}
		if (config.ipAddr &&
		    strcmp(request->host, config.ipAddr) == 0) {
			log_message(LOG_ERR,
				    "process_request: destination IP is localhost %d",
				    connptr->client_fd);
			indicate_http_error(connptr, 400, "Bad Request",
					    "detail", "You tried to connect to the machine the proxy is running on",
					    "url", url,
					    NULL);
			safefree(url);
			free_request_struct(request);
			return NULL;
		}
#else
		log_message(LOG_ERR,
			    "process_request: Unknown URL type on file descriptor %d",
			    connptr->client_fd);
		indicate_http_error(connptr, 400, "Bad Request",
				    "detail", "Unknown URL type",
				    "url", url,
				    NULL);

		safefree(url);
		free_request_struct(request);

		return NULL;
#endif
	}

#ifdef FILTER_ENABLE
	/*
	 * Filter restricted domains/urls
	 */
	if (config.filter) {
		if (config.filter_url)
			ret = filter_url(url);
		else
			ret = filter_domain(request->host);

		if (ret) {
			update_stats(STAT_DENIED);

			if (config.filter_url)
				log_message(LOG_NOTICE,
					    "Proxying refused on filtered url \"%s\"",
					    url);
			else
				log_message(LOG_NOTICE,
					    "Proxying refused on filtered domain \"%s\"",
					    request->host);

			indicate_http_error(connptr, 403, "Filtered",
					    "detail", "The request you made has been filted",
					    "url", url,
					    NULL);

			safefree(url);
			free_request_struct(request);

			return NULL;
		}
	}
#endif

	safefree(url);

	/*
	 * Check to see if they're requesting the stat host
	 */
	if (config.stathost && strcmp(config.stathost, request->host) == 0) {
		log_message(LOG_NOTICE, "Request for the stathost.");
		connptr->show_stats = TRUE;

		free_request_struct(request);
		return NULL;
	}

	/*
	 * Break apart the protocol and update the connection structure.
	 */
	if (strncasecmp(request->protocol, "http", 4) == 0) {
		memcpy(request->protocol, "HTTP", 4);
		sscanf(request->protocol, "HTTP/%u.%u",
		       &connptr->protocol.major, &connptr->protocol.minor);
	}

	return request;
}

/*
 * pull_client_data is used to pull across any client data (like in a
 * POST) which needs to be handled before an error can be reported, or
 * server headers can be processed.
 *	- rjkaes
 */
static int
pull_client_data(struct conn_s *connptr, long int length)
{
	char *buffer;
	ssize_t len;

	buffer = safemalloc(min(MAXBUFFSIZE, length));
	if (!buffer)
		return -1;

	do {
		len = safe_read(connptr->client_fd, buffer,
				min(MAXBUFFSIZE, length));
		if (len <= 0)
			goto ERROR_EXIT;

		if (!connptr->error_variables) {
			if (safe_write(connptr->server_fd, buffer, len) < 0)
				goto ERROR_EXIT;
		}

		length -= len;
	} while (length > 0);

	/*
	 * BUG FIX: Internet Explorer will leave two bytes (carriage
	 * return and line feed) at the end of a POST message.  These
	 * need to be eaten for tinyproxy to work correctly.
	 */
	socket_nonblocking(connptr->client_fd);
	len = recv(connptr->client_fd, buffer, 2, MSG_PEEK);
	socket_blocking(connptr->client_fd);

	if (len < 0 && errno != EAGAIN)
		goto ERROR_EXIT;

	if (len == 2 && CHECK_CRLF(buffer, len))
		read(connptr->client_fd, buffer, 2);

	safefree(buffer);
	return 0;

  ERROR_EXIT:
	safefree(buffer);
	return -1;
}

#ifdef XTINYPROXY_ENABLE
/*
 * Add the X-Tinyproxy header to the collection of headers being sent to
 * the server.
 *	-rjkaes
 */
static int
add_xtinyproxy_header(struct conn_s *connptr)
{
	/*
	 * Don't try to send if we have an invalid server handle.
	 */
	if (connptr->server_fd < 0)
		return 0;

	return write_message(connptr->server_fd,
			     "X-Tinyproxy: %s\r\n",
			     connptr->client_ip_addr);
}
#endif				/* XTINYPROXY */

/*
 * Take a complete header line and break it apart (into a key and the data.)
 * Now insert this information into the hashmap for the connection so it
 * can be retrieved and manipulated later.
 */
static inline int
add_header_to_connection(hashmap_t hashofheaders, char *header, size_t len)
{
	char *sep;

	/* Get rid of the new line and return at the end */
	len -= chomp(header, len);

	sep = strchr(header, ':');
	if (!sep)
		return -1;

	/* Blank out colons, spaces, and tabs. */
	while (*sep == ':' || *sep == ' ' || *sep == '\t')
		*sep++ = '\0';

	/* Calculate the new length of just the data */
	len -= sep - header - 1;

	return hashmap_insert(hashofheaders, header, sep, len);
}

/*
 * Read all the headers from the stream
 */
static int
get_all_headers(int fd, hashmap_t hashofheaders)
{
	char *header;
	ssize_t len;
	unsigned int double_cgi = FALSE; /* boolean */

	assert(fd >= 0);
	assert(hashofheaders != NULL);

	for (;;) {
		if ((len = readline(fd, &header)) <= 0) {
			safefree(header);
			return -1;
		}

		/*
		 * If we received just a CR LF on a line, the headers are
		 * finished.
		 */
		if (CHECK_CRLF(header, len)) {
			safefree(header);
			return 0;
		}

		/*
		 * BUG FIX: The following code detects a "Double CGI"
		 * situation so that we can handle the nonconforming system.
		 * This problem was found when accessing cgi.ebay.com, and it
		 * turns out to be a wider spread problem as well.
		 *
		 * If "Double CGI" is in effect, duplicate headers are
		 * ignored.
		 *
		 * FIXME: Might need to change this to a more robust check.
		 */
		if (strncasecmp(header, "HTTP/", 5) == 0) {
			double_cgi = TRUE;

			safefree(header);
			continue;
		}

		if (!double_cgi
		    && add_header_to_connection(hashofheaders, header, len) < 0) {
			safefree(header);
			return -1;
		}

		safefree(header);
	}
}

/*
 * Extract the headers to remove.  These headers were listed in the Connection
 * and Proxy-Connection headers.
 */
static int
remove_connection_headers(hashmap_t hashofheaders)
{
	static char* headers[] = {
		"connection",
		"proxy-connection"
	};

	char *data;
	char* ptr;
	ssize_t len;
	int i;

	for (i = 0; i < (sizeof(headers) / sizeof(char *)); ++i) {
		/* Look for the connection header.  If it's not found, return. */
		len = hashmap_entry_by_key(hashofheaders, headers[i], (void **)&data);
		if (len <= 0)
			return 0;

		/*
		 * Go through the data line and replace any special characters
		 * with a NULL.
		 */
		ptr = data;
		while ((ptr = strpbrk(ptr, "()<>@,;:\\\"/[]?={} \t")))
			*ptr++ = '\0';

		/*
		 * All the tokens are separated by NULLs.  Now go through the
		 * token and remove them from the hashofheaders.
		 */
		ptr = data;
		while (ptr < data + len) {
			hashmap_remove(hashofheaders, ptr);

			/* Advance ptr to the next token */
			ptr += strlen(ptr) + 1;
			while (*ptr == '\0')
				ptr++;
		}

		/* Now remove the connection header it self. */
		hashmap_remove(hashofheaders, headers[i]);
	}

	return 0;
}

/*
 * If there is a Content-Length header, then return the value; otherwise, return
 * a negative number.
 */
static long
get_content_length(hashmap_t hashofheaders)
{
	ssize_t len;
	char *data;
	long content_length = -1;

	len = hashmap_entry_by_key(hashofheaders, "content-length", (void **)&data);
	if (len > 0)
		content_length = atol(data);

	return content_length;
}

/*
 * Search for Via head in a hash of headers and either write a new Via header,
 * or append our information to the end of an existing Via header.
 *
 * FIXME: Need to add code to "hide" our internal information for security
 * purposes.
 */
static int
write_via_header(int fd, hashmap_t hashofheaders,
		 unsigned int major, unsigned int minor)
{
	ssize_t len;
	char hostname[128];
	char *data;
	int ret;

	gethostname(hostname, sizeof(hostname));

	/*
	 * See if there is a "Via" header.  If so, again we need to do a bit
	 * of processing.
	 */
	len = hashmap_entry_by_key(hashofheaders, "via", (void **)&data);
	if (len > 0) {
		ret = write_message(fd,
				    "Via: %s, %hu.%hu %s (%s/%s)\r\n",
				    data,
				    major, minor,
				    hostname, PACKAGE, VERSION);

		hashmap_remove(hashofheaders, "via");
	} else {
		ret = write_message(fd,
				    "Via: %hu.%hu %s (%s/%s)\r\n",
				    major, minor,
				    hostname, PACKAGE, VERSION);
	}

	return ret;
}

/*
 * Number of buckets to use internally in the hashmap.
 */
#define HEADER_BUCKETS 32

/*
 * Here we loop through all the headers the client is sending. If we
 * are running in anonymous mode, we will _only_ send the headers listed
 * (plus a few which are required for various methods).
 *	- rjkaes
 */
static int
process_client_headers(struct conn_s *connptr, hashmap_t hashofheaders)
{
	static char *skipheaders[] = {
		"host",
		"keep-alive",
		"proxy-authenticate",
		"proxy-authorization",
		"proxy-connection",
		"te",
		"trailers",
		"transfer-encoding",
		"upgrade"
	};
	int i;
	hashmap_iter iter;
	int ret = 0;

	char *data, *header;

	/*
	 * Don't send headers if there's already an error, if the request was
	 * a stats request, or if this was a CONNECT method (unless upstream
	 * proxy is in use.)
	 */
	if (connptr->server_fd == -1 || connptr->show_stats
	    || (connptr->connect_method && !UPSTREAM_CONFIGURED())) {
		log_message(LOG_INFO, "Not sending client headers to remote machine");
		return 0;
	}

	/*
	 * See if there is a "Content-Length" header.  If so, again we need
	 * to do a bit of processing.
	 */
	connptr->content_length.client = get_content_length(hashofheaders);

	/*
	 * See if there is a "Connection" header.  If so, we need to do a bit
	 * of processing. :)
	 */
	remove_connection_headers(hashofheaders);

	/*
	 * Delete the headers listed in the skipheaders list
	 */
	for (i = 0; i < (sizeof(skipheaders) / sizeof(char *)); i++) {
		hashmap_remove(hashofheaders, skipheaders[i]);
	}

	/* Send, or add the Via header */
	if (config.via_http_header) {
		ret = write_via_header(connptr->server_fd, hashofheaders,
				       connptr->protocol.major,
				       connptr->protocol.minor);
		if (ret < 0) {
			indicate_http_error(connptr, 503,
					    "Could not send data to remote server",
					    "detail", "A network error occurred while trying to write data to the remote web server.",
					    NULL);
			goto PULL_CLIENT_DATA;
		}
	}

	/*
	 * Output all the remaining headers to the remote machine.
	 */
	iter = hashmap_first(hashofheaders);
	if (iter >= 0) {
		for ( ; !hashmap_is_end(hashofheaders, iter); ++iter) {
			hashmap_return_entry(hashofheaders,
					     iter,
					     &data,
					     (void**)&header);

			if (!is_anonymous_enabled() || anonymous_search(data) > 0) {
				ret = write_message(connptr->server_fd,
						    "%s: %s\r\n",
						    data, header);
				if (ret < 0) {
					indicate_http_error(connptr, 503,
							    "Could not send data to remote server",
							    "detail", "A network error occurred while trying to write data to the remote web server.",
							    NULL);
					goto PULL_CLIENT_DATA;
				}
			}
		}
	}

#if defined(XTINYPROXY_ENABLE)
	if (config.my_domain)
		add_xtinyproxy_header(connptr);
#endif
	
	/* Write the final "blank" line to signify the end of the headers */
	if (safe_write(connptr->server_fd, "\r\n", 2) < 0)
		return -1;

	/*
	 * Spin here pulling the data from the client.
	 */
  PULL_CLIENT_DATA:
	if (connptr->content_length.client > 0)
		return pull_client_data(connptr,
					connptr->content_length.client);
	else
		return ret;
}

/*
 * Loop through all the headers (including the response code) from the
 * server.
 */
static int
process_server_headers(struct conn_s *connptr)
{
	static char *skipheaders[] = {
		"keep-alive",
		"proxy-authenticate",
		"proxy-authorization",
		"proxy-connection",
		"transfer-encoding",
	};

	char *response_line;

	hashmap_t hashofheaders;
	hashmap_iter iter;
	char *data, *header;
	ssize_t len;
	int i;
	int ret;

	/* FIXME: Remember to handle a "simple_req" type */

	/* Get the response line from the remote server. */
      retry:
	len = readline(connptr->server_fd, &response_line);
	if (len <= 0)
		return -1;

	/*
	 * Strip the new line and character return from the string.
	 */
	if (chomp(response_line, len) == len) {
		/*
		 * If the number of characters removed is the same as the
		 * length then it was a blank line. Free the buffer and
		 * try again (since we're looking for a request line.)
		 */
		safefree(response_line);
		goto retry;
	}

	hashofheaders = hashmap_create(HEADER_BUCKETS);
	if (!hashofheaders) {
		safefree(response_line);
		return -1;
	}

	/*
	 * Get all the headers from the remote server in a big hash
	 */
	if (get_all_headers(connptr->server_fd, hashofheaders) < 0) {
		log_message(LOG_WARNING, "Could not retrieve all the headers from the remote server.");
		hashmap_delete(hashofheaders);
		safefree(response_line);

		indicate_http_error(connptr, 503, "Could not retrieve all the headers",
				    "detail", PACKAGE " was unable to retrieve and process headers from the remote web server.",
				    NULL);
		return -1;
	}

	/* Send the saved response line first */
	ret = write_message(connptr->client_fd, "%s\r\n", response_line);
	safefree(response_line);
	if (ret < 0)
		goto ERROR_EXIT;

	/*
	 * If there is a "Content-Length" header, retrieve the information
	 * from it for later use.
	 */
	connptr->content_length.server = get_content_length(hashofheaders);

	/*
	 * See if there is a connection header.  If so, we need to to a bit of
	 * processing.
	 */
	remove_connection_headers(hashofheaders);

	/*
	 * Delete the headers listed in the skipheaders list
	 */
	for (i = 0; i < (sizeof(skipheaders) / sizeof(char *)); i++) {
		hashmap_remove(hashofheaders, skipheaders[i]);
	}

	/* Send, or add the Via header */
	if (config.via_http_header) {
		ret = write_via_header(connptr->client_fd, hashofheaders,
				       connptr->protocol.major,
				       connptr->protocol.minor);
		if (ret < 0)
			goto ERROR_EXIT;
	}

	/*
	 * All right, output all the remaining headers to the client.
	 */
	iter = hashmap_first(hashofheaders);
	if (iter >= 0) {
		for ( ; !hashmap_is_end(hashofheaders, iter); ++iter) {
			hashmap_return_entry(hashofheaders,
					     iter,
					     &data,
					     (void **)&header);

			ret = write_message(connptr->client_fd,
						  "%s: %s\r\n",
						  data, header);
			if (ret < 0)
				goto ERROR_EXIT;
		}
	}
	hashmap_delete(hashofheaders);

	/* Write the final blank line to signify the end of the headers */
	if (safe_write(connptr->client_fd, "\r\n", 2) < 0)
		return -1;

	return 0;

  ERROR_EXIT:
	hashmap_delete(hashofheaders);
	return -1;
}

/*
 * Switch the sockets into nonblocking mode and begin relaying the bytes
 * between the two connections. We continue to use the buffering code
 * since we want to be able to buffer a certain amount for slower
 * connections (as this was the reason why I originally modified
 * tinyproxy oh so long ago...)
 *	- rjkaes
 */
static void
relay_connection(struct conn_s *connptr)
{
	fd_set rset, wset;
	struct timeval tv;
	time_t last_access;
	int ret;
	double tdiff;
	int maxfd = max(connptr->client_fd, connptr->server_fd) + 1;
	ssize_t bytes_received;

	socket_nonblocking(connptr->client_fd);
	socket_nonblocking(connptr->server_fd);

	last_access = time(NULL);

	for (;;) {
		FD_ZERO(&rset);
		FD_ZERO(&wset);

		tv.tv_sec =
		    config.idletimeout - difftime(time(NULL), last_access);
		tv.tv_usec = 0;

		if (buffer_size(connptr->sbuffer) > 0)
			FD_SET(connptr->client_fd, &wset);
		if (buffer_size(connptr->cbuffer) > 0)
			FD_SET(connptr->server_fd, &wset);
		if (buffer_size(connptr->sbuffer) < MAXBUFFSIZE)
			FD_SET(connptr->server_fd, &rset);
		if (buffer_size(connptr->cbuffer) < MAXBUFFSIZE)
			FD_SET(connptr->client_fd, &rset);

		ret = select(maxfd, &rset, &wset, NULL, &tv);

		if (ret == 0) {
			tdiff = difftime(time(NULL), last_access);
			if (tdiff > config.idletimeout) {
				log_message(LOG_INFO,
					    "Idle Timeout (after select) as %g > %u.",
					    tdiff, config.idletimeout);
				return;
			} else {
				continue;
			}
		} else if (ret < 0) {
			log_message(LOG_ERR,
				    "relay_connection: select() error \"%s\". Closing connection (client_fd:%d, server_fd:%d)",
				    strerror(errno), connptr->client_fd,
				    connptr->server_fd);
			return;
		} else {
			/*
			 * All right, something was actually selected so mark it.
			 */
			last_access = time(NULL);
		}

		if (FD_ISSET(connptr->server_fd, &rset)) {
			bytes_received = read_buffer(connptr->server_fd, connptr->sbuffer);
			if (bytes_received < 0)
				break;

			connptr->content_length.server -= bytes_received;
			if (connptr->content_length.server == 0)
				break;
		}
		if (FD_ISSET(connptr->client_fd, &rset)
		    && read_buffer(connptr->client_fd, connptr->cbuffer) < 0) {
			break;
		}
		if (FD_ISSET(connptr->server_fd, &wset)
		    && write_buffer(connptr->server_fd, connptr->cbuffer) < 0) {
			break;
		}
		if (FD_ISSET(connptr->client_fd, &wset)
		    && write_buffer(connptr->client_fd, connptr->sbuffer) < 0) {
			break;
		}
	}

	/*
	 * Here the server has closed the connection... write the
	 * remainder to the client and then exit.
	 */
	socket_blocking(connptr->client_fd);
	while (buffer_size(connptr->sbuffer) > 0) {
		if (write_buffer(connptr->client_fd, connptr->sbuffer) < 0)
			break;
	}
	shutdown(connptr->client_fd, SHUT_WR);

	/*
	 * Try to send any remaining data to the server if we can.
	 */
	socket_blocking(connptr->server_fd);
	while (buffer_size(connptr->cbuffer) > 0) {
		if (write_buffer(connptr->server_fd, connptr->cbuffer) < 0)
			break;
	}

	return;
}

/*
 * Establish a connection to the upstream proxy server.
 */
static int
connect_to_upstream(struct conn_s *connptr, struct request_s *request)
{
#ifndef UPSTREAM_SUPPORT
	/*
	 * This function does nothing if upstream support was not compiled
	 * into tinyproxy.
	 */
	return -1;
#else
	char *combined_string;
	int len;

	connptr->server_fd =
	    opensock(config.upstream_name, config.upstream_port);

	if (connptr->server_fd < 0) {
		log_message(LOG_WARNING,
			    "Could not connect to upstream proxy.");
		indicate_http_error(connptr, 404, "Unable to connect to upstream proxy",
				    "detail", "A network error occurred while trying to connect to the upstream web proxy.",
				    NULL);
		return -1;
	}

	log_message(LOG_CONN,
		    "Established connection to upstream proxy \"%s\" using file descriptor %d.",
		    config.upstream_name, connptr->server_fd);

	/*
	 * We need to re-write the "path" part of the request so that we
	 * can reuse the establish_http_connection() function. It expects a
	 * method and path.
	 */
	if (connptr->connect_method) {
		len = strlen(request->host) + 6;

		combined_string = safemalloc(len + 1);
		if (!combined_string) {
			return -1;
		}

		snprintf(combined_string, len, "%s:%d", request->host,
			 request->port);
	} else {
		len = strlen(request->host) + strlen(request->path) + 14;
		combined_string = safemalloc(len + 1);
		if (!combined_string) {
			return -1;
		}

		snprintf(combined_string, len, "http://%s:%d%s", request->host,
			 request->port, request->path);
	}

	safefree(request->path);
	request->path = combined_string;

	return establish_http_connection(connptr, request);
#endif
}

/*
 * This is the main drive for each connection. As you can tell, for the
 * first few steps we are using a blocking socket. If you remember the
 * older tinyproxy code, this use to be a very confusing state machine.
 * Well, no more! :) The sockets are only switched into nonblocking mode
 * when we start the relay portion. This makes most of the original
 * tinyproxy code, which was confusing, redundant. Hail progress.
 * 	- rjkaes
 */
void
handle_connection(int fd)
{
	struct conn_s *connptr;
	struct request_s *request = NULL;
	hashmap_t hashofheaders = NULL;

	char peer_ipaddr[PEER_IP_LENGTH];
	char peer_string[PEER_STRING_LENGTH];

	getpeer_information(fd, peer_ipaddr, peer_string);

	log_message(LOG_CONN, "Connect (file descriptor %d): %s [%s]",
		    fd, peer_string, peer_ipaddr);

	connptr = initialize_conn(fd, peer_ipaddr, peer_string);
	if (!connptr) {
		close(fd);
		return;
	}

	if (check_acl(fd, peer_ipaddr, peer_string) <= 0) {
		update_stats(STAT_DENIED);
		indicate_http_error(connptr, 403, "Access denied",
				    "detail", "The administrator of this proxy has not configured it to service requests from your host.",
				    NULL);
		send_http_error_message(connptr);
		destroy_conn(connptr);
		return;
	}

	if (read_request_line(connptr) < 0) {
		update_stats(STAT_BADCONN);
		indicate_http_error(connptr, 408, "Timeout",
				    "detail", "Server timeout waiting for the HTTP request from the client.",
				    NULL);
		send_http_error_message(connptr);
		destroy_conn(connptr);
		return;
	}

	/*
	 * The "hashofheaders" store the client's headers.
	 */
	if (!(hashofheaders = hashmap_create(HEADER_BUCKETS))) {
		update_stats(STAT_BADCONN);
		indicate_http_error(connptr, 503, "Internal error",
				    "detail", "An internal server error occurred while processing your request.  Please contact the administrator.",
				    NULL);
		send_http_error_message(connptr);
		destroy_conn(connptr);
		return;
	}

	/*
	 * Get all the headers from the client in a big hash.
	 */
	if (get_all_headers(connptr->client_fd, hashofheaders) < 0) {
		log_message(LOG_WARNING, "Could not retrieve all the headers from the client");
		hashmap_delete(hashofheaders);
		update_stats(STAT_BADCONN);
		destroy_conn(connptr);
		return;
	}

	request = process_request(connptr, hashofheaders);
	if (!request) {
		if (!connptr->error_variables && !connptr->show_stats) {
			update_stats(STAT_BADCONN);
			destroy_conn(connptr);
			hashmap_delete(hashofheaders);
			return;
		}
		goto send_error;
	}

	if (UPSTREAM_CONFIGURED()) {
		if (connect_to_upstream(connptr, request) < 0) {
			goto send_error;
		}
	} else {
		connptr->server_fd = opensock(request->host, request->port);
		if (connptr->server_fd < 0) {
			indicate_http_error(connptr, 500, "Unable to connect",
					    "detail", PACKAGE " was unable to connect to the remote web server.",
					    "error", strerror(errno),
					    NULL);
			goto send_error;
		}

		log_message(LOG_CONN,
			    "Established connection to host \"%s\" using file descriptor %d.",
			    request->host, connptr->server_fd);

		if (!connptr->connect_method)
			establish_http_connection(connptr, request);
	}

      send_error:
	free_request_struct(request);

	if (process_client_headers(connptr, hashofheaders) < 0) {
		update_stats(STAT_BADCONN);
		if (!connptr->error_variables) {
			hashmap_delete(hashofheaders);
			destroy_conn(connptr);
			return;
		}
	}
	hashmap_delete(hashofheaders);

	if (connptr->error_variables) {
		send_http_error_message(connptr);
		destroy_conn(connptr);
		return;
	} else if (connptr->show_stats) {
		showstats(connptr);
		destroy_conn(connptr);
		return;
	}

	if (!connptr->connect_method || UPSTREAM_CONFIGURED()) {
		if (process_server_headers(connptr) < 0) {
			if (connptr->error_variables)
				send_http_error_message(connptr);

			update_stats(STAT_BADCONN);
			destroy_conn(connptr);
			return;
		}
	} else {
		if (send_ssl_response(connptr) < 0) {
			log_message(LOG_ERR,
				    "handle_connection: Could not send SSL greeting to client.");
			update_stats(STAT_BADCONN);
			destroy_conn(connptr);
			return;
		}
	}

	relay_connection(connptr);

	log_message(LOG_INFO, "Closed connection between local client (fd:%d) and remote client (fd:%d)",
		    connptr->client_fd, connptr->server_fd);

	/*
	 * All done... close everything and go home... :)
	 */
	destroy_conn(connptr);
	return;
}