Diff

Differences From Artifact [cb8ce29868]:

To Artifact [05973c0b4a]:


























1
2
3
4
5
6
7
..
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
..
91
92
93
94
95
96
97





98
99
100
101
102
103
104
...
116
117
118
119
120
121
122

123
124
125
126
127
128
129
...
136
137
138
139
140
141
142






























143
144
145
146
147
148
149
150
151
152





153
154
155
156
157
158
159
...
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
...
277
278
279
280
281
282
283
284






285

286
287
288
289
290
291
292
...
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
...
393
394
395
396
397
398
399

400
401
402
403
404
405
406
...
475
476
477
478
479
480
481










































































































































































































482
483
484
485
486
487
488
...
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
...
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
...
649
650
651
652
653
654
655

656
657
658
659
660
661
662
...
748
749
750
751
752
753
754


755
756
757
758
759
760
761
...
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
...
943
944
945
946
947
948
949
950
951
952
953
954
955

956
957
958
959
960
961
962
....
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
....
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
....
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
....
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
....
1423
1424
1425
1426
1427
1428
1429








1430
1431
1432
1433
1434
1435
1436
....
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
























#include <sys/sendfile.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/prctl.h>
#include <arpa/inet.h>
#include <sys/mman.h>
#include <sys/stat.h>
................................................................................
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <pwd.h>

/* Compile time constants */
#define FILED_VERSION "1.9"
#define FILED_SENDFILE_MAX 16777215
#define FILED_MAX_FAILURE_COUNT 30
#define FILED_DEFAULT_TYPE "application/octet-stream"
#define FILED_PATH_BUFFER_SIZE 1010

/* Default values */
#define PORT 80
#define THREAD_COUNT 5
#define BIND_ADDR "::"
#define CACHE_SIZE 8209
#define LOG_FILE "-"


































/* Configuration options that work threads need to be aware of */
struct filed_options {
	int vhosts_enabled;

};

/* Arguments for worker threads */
struct filed_worker_thread_args {
	int fd;
	struct filed_options options;
};
................................................................................
			off_t length;   /*** Range length ***/
		} range;

		struct {
			int present;
			char host[FILED_PATH_BUFFER_SIZE];
		} host;





	} headers;
};

/* Log record */
struct filed_log_entry {
	/* Type of log entry */
	enum {
................................................................................
	/* Message buffer for type = MESSAGE */
	/* Path buffer for type = TRANSFER */
	char buffer[FILED_PATH_BUFFER_SIZE];

	/* Items for type = TRANSFER */
	int http_code;
	const char *reason;

	time_t starttime;
	time_t endtime;
	off_t req_offset;
	off_t req_length;
	off_t sent_length;
	off_t file_length;
	char ip[128];
................................................................................
struct filed_fileinfo *filed_fileinfo_fdcache = NULL;
unsigned int filed_fileinfo_fdcache_size = 0;

/** Logging **/
struct filed_log_entry *filed_log_msg_list;
pthread_mutex_t filed_log_msg_list_mutex;
pthread_cond_t filed_log_msg_list_ready;































/* Initialize cache */
static int filed_init_cache(unsigned int cache_size) {
	unsigned int idx;
	int mutex_init_ret;

	/* Cache may not be re-initialized */
	if (filed_fileinfo_fdcache_size != 0 || filed_fileinfo_fdcache != NULL) {
		return(1);
	}






	/* Allocate cache */
	filed_fileinfo_fdcache_size = cache_size;
	filed_fileinfo_fdcache = malloc(sizeof(*filed_fileinfo_fdcache) * filed_fileinfo_fdcache_size);
	if (filed_fileinfo_fdcache == NULL) {
		return(1);
	}
................................................................................

	return(0);
}

/* Initialize process */
static int filed_init(unsigned int cache_size) {
	static int called = 0;



	unsigned int random_value = 0;
	int cache_ret;
	int random_fd;

	if (called) {
		return(0);
	}

	called = 1;

	/* Attempt to lock all memory to physical RAM (but don't care if we can't) */
	mlockall(MCL_CURRENT | MCL_FUTURE);

	/* Ignore SIGPIPE */
	signal(SIGPIPE, SIG_IGN);













	/* Initialize cache structure */
	cache_ret = filed_init_cache(cache_size);
	if (cache_ret != 0) {
		return(cache_ret);
	}

	/* Initialize random number generator */
	random_fd = open("/dev/urandom", O_RDONLY);
	if (random_fd >= 0) {
		read(random_fd, &random_value, sizeof(random_value));

		close(random_fd);
	}

	random_value ^= getpid();
	random_value ^= getuid();
	random_value ^= time(NULL);

	srandom(random_value);

	return(0);



}

/* Listen on a particular address/port */
static int filed_listen(const char *address, unsigned int port) {
	struct sockaddr_in6 addr_v6;
	struct sockaddr_in addr_v4;
	struct sockaddr *addr;
	socklen_t addr_len;
	int pton_ret, bind_ret, listen_ret;
	int family;
	int fd;


	family = AF_INET6;
	pton_ret = inet_pton(family, address, &addr_v6.sin6_addr.s6_addr);
	if (pton_ret != 1) {
		family = AF_INET;
		pton_ret = inet_pton(family, address, &addr_v4.sin_addr.s_addr);
		if (pton_ret != 1) {
................................................................................
#ifdef FILED_DONT_LOG
#  define filed_logging_thread_init(x) 0
#  define filed_log_msg_debug(x, ...) /**/
#  define filed_log_msg(x, ...) /**/
#  define filed_log_entry(x) /**/
#  define filed_log_ip(x, ...) NULL
#  define filed_log_new(x) &local_dummy_log
#  define filed_log_open(x) stdout






#else

#  ifdef FILED_DEBUG
#    define filed_log_msg_debug(x, ...) { fprintf(stderr, x, __VA_ARGS__); fprintf(stderr, "\n"); fflush(stderr); }
#  else
#    define filed_log_msg_debug(x, ...) /**/
#  endif

/* Initialize logging thread */
................................................................................
							break;
					}

					if (curr->endtime == ((time_t) -1)) {
						curr->endtime = now;
					}

					fprintf(fp, "TRANSFER METHOD=%s PATH=%s SRC=%s:%i TIME.START=%llu TIME.END=%llu CODE.VALUE=%u CODE.REASON=%s REQUEST.OFFSET=%llu REQUEST.LENGTH=%llu FILE.LENGTH=%llu TRANSFER.LENGTH=%llu",
						method,
						curr->buffer,
						curr->ip, curr->port,

						(unsigned long long) curr->starttime,
						(unsigned long long) curr->endtime,
						curr->http_code, curr->reason,
						(unsigned long long) curr->req_offset,
						(unsigned long long) curr->req_length,
						(unsigned long long) curr->file_length,
						(unsigned long long) curr->sent_length
					);

					break;
			}
			fprintf(fp, " THREAD=%llu TIME=%llu\n",
				(unsigned long long) curr->thread,
				(unsigned long long) now
			);
			fflush(fp);

			prev = curr;
			curr = curr->_prev;

................................................................................
	struct filed_log_entry *retval;

	retval = malloc(sizeof(*retval));

	if (initialize) {
		retval->buffer[0] = '\0';
		retval->http_code = -1;

		retval->starttime = 0;
		retval->endtime = 0;
		retval->req_offset = 0;
		retval->req_length = 0;
		retval->sent_length = 0;
		retval->file_length = 0;
		retval->ip[0] = '\0';
................................................................................
	filed_log_msg_list = NULL;

	pthread_mutex_init(&filed_log_msg_list_mutex, NULL);

	pthread_create(&thread_id, NULL, filed_logging_thread, args);

	filed_log_msg("START");











































































































































































































	return(0);
}
#endif

/* Format time per RFC2616 */
static char *filed_format_time(char *buffer, size_t buffer_len, const time_t timeinfo) {
................................................................................
		(unsigned long long) time(NULL),
		(unsigned long long) random(),
		(unsigned long long) random(),
		(unsigned long long) random(),
		(unsigned long long) random()
	);
}














































/* Open a file and return file information */
static struct filed_fileinfo *filed_open_file(const char *path, struct filed_fileinfo *buffer) {
	struct filed_fileinfo *cache;
	unsigned int cache_idx;
	off_t len;
	int fd;


	cache_idx = filed_hash((const unsigned char *) path, filed_fileinfo_fdcache_size);

	cache = &filed_fileinfo_fdcache[cache_idx];

	filed_log_msg_debug("Locking mutex for idx: %lu", (unsigned long) cache_idx);

	pthread_mutex_lock(&cache->mutex);

	filed_log_msg_debug("Completed locking mutex for idx: %lu", (unsigned long) cache_idx);







	if (strcmp(path, cache->path) != 0) {
		filed_log_msg_debug("Cache miss for idx: %lu: OLD \"%s\", NEW \"%s\"", (unsigned long) cache_idx, cache->path, path);

		fd = open(path, O_RDONLY | O_LARGEFILE);
		if (fd < 0) {

			pthread_mutex_unlock(&cache->mutex);


			return(NULL);
		}

		if (cache->fd >= 0) {
			close(cache->fd);
		}
................................................................................

		/* XXX:TODO: Determine */
		cache->lastmod = filed_format_time(cache->lastmod_b, sizeof(cache->lastmod_b), time(NULL) - 30);
	} else {
		filed_log_msg_debug("Cache hit for idx: %lu: PATH \"%s\"", (unsigned long) cache_idx, path);
	}


	/*
	 * We have to make a duplicate FD, because once we release the cache
	 * mutex, the file descriptor may be closed
	 */
	fd = dup(cache->fd);
	if (fd < 0) {
		pthread_mutex_unlock(&cache->mutex);

		return(NULL);
	}

	buffer->fd = fd;
	buffer->len = cache->len;
	buffer->type = cache->type;
	memcpy(buffer->lastmod_b, cache->lastmod_b, sizeof(buffer->lastmod_b));
	memcpy(buffer->etag, cache->etag, sizeof(buffer->etag));
	buffer->lastmod = buffer->lastmod_b + (cache->lastmod - cache->lastmod_b);

	pthread_mutex_unlock(&cache->mutex);


	return(buffer);



}

/* Process an HTTP request and return the path requested */
static struct filed_http_request *filed_get_http_request(FILE *fp, struct filed_http_request *buffer_st, struct filed_options *options) {
	char *method, *path;
	char *buffer, *workbuffer, *workbuffer_next;
	char *fgets_ret;
................................................................................

	/* Set to default values */
	range_start = 0;
	range_end   = 0;
	range_request = 0;
	range_length = -1;
	buffer_st->headers.host.present = 0;


	buffer = buffer_st->tmpbuf;
	buffer_len = sizeof(buffer_st->tmpbuf);

	fgets_ret = fgets(buffer, buffer_len, fp);
	if (fgets_ret == NULL) {
		return(NULL);
................................................................................

			workbuffer = buffer + 5;
			while (*workbuffer == ' ') {
				workbuffer++;
			}

			strcpy(buffer_st->headers.host.host, workbuffer);


		}

		if (memcmp(buffer, "\r\n", 2) == 0) {
			break;
		}
	}

................................................................................
	/** reason must point to a globally allocated value **/
	log->reason = reason;
	log->http_code = error_number;

	filed_log_entry(log);

	/* Close connection */


	fclose(fp);

	return;
}

/* Return a redirect to index.html */

static void filed_redirect_index(FILE *fp, const char *date_current, const char *path, struct filed_log_entry *log) {
	int http_code = 301;
	fprintf(fp, "HTTP/1.1 %i OK\r\nDate: %s\r\nServer: filed\r\nLast-Modified: %s\r\nContent-Length: 0\r\nConnection: close\r\nLocation: %s\r\n\r\n",
		http_code,
		date_current,
		date_current,
		"index.html"
	);

................................................................................
	/* Log redirect */
	log->reason = "redirect";
	log->http_code = http_code;

	filed_log_entry(log);

	/* Close connection */


	fclose(fp);

	return;

	/* Currently unused: path */
	path = path;
}














/* Handle a single request from a client */
static void filed_handle_client(int fd, struct filed_http_request *request, struct filed_log_entry *log, struct filed_options *options) {
	struct filed_fileinfo *fileinfo;
	ssize_t sendfile_ret;
	size_t sendfile_size;
	off_t sendfile_offset, sendfile_sent, sendfile_len;
	char *path;
	char *date_current, date_current_b[64];
	int http_code;
	FILE *fp;




	/* Determine current time */
	date_current = filed_format_time(date_current_b, sizeof(date_current_b), time(NULL));

	/* Open socket as ANSI I/O for ease of use */
	fp = fdopen(fd, "w+b");
	if (fp == NULL) {


		close(fd);

		log->buffer[0] = '\0';
		log->http_code = -1;
		log->reason = "fdopen_failed";

		filed_log_entry(log);

		return;
	}

	request = filed_get_http_request(fp, request, options);

	if (request == NULL) {
		log->buffer[0] = '\0';

		filed_error_page(fp, date_current, 500, FILED_REQUEST_METHOD_GET, "format", log);

		return;
	}



	path = request->path;
	strcpy(log->buffer, path);
	log->method = request->method;

	/* If the requested path is a directory, redirect to index page */
	if (request->type == FILED_REQUEST_TYPE_DIRECTORY) {














		filed_redirect_index(fp, date_current, path, log);

		return;


	}

	fileinfo = filed_open_file(path, &request->fileinfo);
	if (fileinfo == NULL) {
		filed_error_page(fp, date_current, 404, request->method, "open_failed", log);

		return;
	}

	if (request->headers.range.present) {
		if (request->headers.range.offset != 0 || request->headers.range.length >= 0) {
			if (request->headers.range.offset >= fileinfo->len) {
				filed_error_page(fp, date_current, 416, request->method, "range_invalid", log);

				close(fileinfo->fd);

				return;
			}

			if (request->headers.range.length == ((off_t) -1)) {
				filed_log_msg_debug("Computing length to fit in bounds: fileinfo->len = %llu, request->headers.range.offset = %llu",
					(unsigned long long) fileinfo->len,
					(unsigned long long) request->headers.range.offset
				);
................................................................................
		http_code = 200;

		/* Compute fake range parameters that includes the entire file */
		request->headers.range.offset = 0;
		request->headers.range.length = fileinfo->len;
	}

	fprintf(fp, "HTTP/1.1 %i OK\r\nDate: %s\r\nServer: filed\r\nLast-Modified: %s\r\nContent-Length: %llu\r\nAccept-Ranges: bytes\r\nContent-Type: %s\r\nConnection: close\r\nETag: \"%s\"\r\n",
		http_code,
		date_current,
		fileinfo->lastmod,
		(unsigned long long) request->headers.range.length,
		fileinfo->type,

		fileinfo->etag
	);

	if (http_code == 206) {
		fprintf(fp, "Content-Range: bytes %llu-%llu/%llu\r\n",
			(unsigned long long) request->headers.range.offset,
			(unsigned long long) (request->headers.range.offset + request->headers.range.length - 1),
................................................................................
	log->endtime = (time_t) -1;
	log->sent_length = sendfile_sent;

	filed_log_entry(log);

	close(fileinfo->fd);




	fclose(fp);

	return;






}

/* Handle incoming connections */
static void *filed_worker_thread(void *arg_v) {
	struct filed_worker_thread_args *arg;
	struct filed_http_request request;
	struct filed_log_entry *log, local_dummy_log;
	struct filed_options *options;
	struct sockaddr_in6 addr;
	socklen_t addrlen;
	int failure_count = 0, max_failure_count = FILED_MAX_FAILURE_COUNT;

	int master_fd, fd;

	/* Read arguments */
	arg = arg_v;

	master_fd = arg->fd;
	options = &arg->options;

................................................................................
			filed_log_msg("ALLOCATE_LOG_MSG_FAILED");

			break;
		}

		log->type = FILED_LOG_TYPE_TRANSFER;



		/* Accept a new client */
		addrlen = sizeof(addr);

		fd = accept(master_fd, (struct sockaddr *) &addr, &addrlen);


		/*
		 * If we fail, make a note of it so we don't go into a loop of
		 * accept() failing
		 */
		if (fd < 0) {
			/* Log the new connection */
			filed_log_msg("ACCEPT_FAILED");

			failure_count++;

			free(log);

			continue;
		}



		/* Fill in log structure */
		if (filed_log_ip((struct sockaddr *) &addr, log->ip, sizeof(log->ip)) == NULL) {
			log->ip[0] = '\0';
			log->port = 0;
		} else {
			log->port = addr.sin6_port;
		}

		/* Reset failure count*/
		failure_count = 0;

		/* Handle socket */
		filed_handle_client(fd, &request, log, options);
	}

	/* Report error */
	filed_log_msg("THREAD_DIED ABNORMAL");

	return(NULL);

................................................................................

	return(0);
}

/* Run process */
int main(int argc, char **argv) {
	struct option options[12];
	struct filed_options thread_options;
	const char *bind_addr = BIND_ADDR, *newroot = NULL, *log_file = LOG_FILE;
	FILE *log_fp;
	uid_t user = 0;
	int port = PORT, thread_count = THREAD_COUNT;
	int cache_size = CACHE_SIZE;
	int init_ret, chroot_ret, setuid_ret, lookup_ret, chdir_ret;
	int setuid_enabled = 0, daemon_enabled = 0;
	int ch;
	int fd;

	/* Set default values */
	thread_options.vhosts_enabled = 0;

	/* Process arguments */
	filed_getopt_long_setopt(&options[0], "port", required_argument, 'p');
	filed_getopt_long_setopt(&options[1], "threads", required_argument, 't');
	filed_getopt_long_setopt(&options[2], "cache", required_argument, 'c');
	filed_getopt_long_setopt(&options[3], "bind", required_argument, 'b');
	filed_getopt_long_setopt(&options[4], "user", required_argument, 'u');
	filed_getopt_long_setopt(&options[5], "root", required_argument, 'r');
................................................................................
				if (lookup_ret != 0) {
					filed_print_help(stderr, 0, "Invalid username specified");

					return(1);
				}
				break;
			case 'r':
				newroot = strdup(optarg);
				break;
			case 'l':
				log_file = strdup(optarg);
				break;
			case 'd':
				daemon_enabled = 1;
				break;
................................................................................
	/* Create listening socket */
	fd = filed_listen(bind_addr, port);
	if (fd < 0) {
		perror("filed_listen");

		return(1);
	}









	/* Become a daemon */
	if (daemon_enabled) {
		init_ret = filed_daemonize();
		if (init_ret != 0) {
			perror("filed_daemonize");

................................................................................
	/* Create logging thread */
	init_ret = filed_logging_thread_init(log_fp);
	if (init_ret != 0) {
		perror("filed_logging_thread_init");

		return(4);
	}









	/* Create worker threads */
	init_ret = filed_worker_threads_init(fd, thread_count, &thread_options);
	if (init_ret != 0) {
		perror("filed_worker_threads_init");

		return(5);
	}

	/* Wait for threads to exit */
	/* XXX:TODO: Monitor thread usage */
	while (1) {
		sleep(60);
	}

	/* Return in failure */
	return(2);
}
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|












>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



>







 







>
>
>
>
>







 







>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










>
>
>
>
>







 







>
>
>













|
|
>
>
>
>
>
>
>
>
>
>
>
>










|











>
>
>











<







 







|
>
>
>
>
>
>

>







 







|



>












|







 







>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|





>
|

|

|

|

|
>
>
>
>
>
>




|

>
|
>







 







>
|
|
|
|
|
|
|

|
|

|
|
|
|
|
|

|
|
>

>
>
>







 







>







 







>
>







 







>
>






>

|







 







>
>







>

>
>
>
>
>
>
>
>
>
>
>
>

|









>
>
>






>
>








|









|

>
>







>
>
>
>
>
>
>
>
>
>
>
>
>
>


<
>
>


|



|









|







 







|





>







 







>
>
>
|

<
>
>
>
>
>
>











>
|







 







>
>
|
|
>
|
>











|



>
>













|







 







|










<
<
<







 







|







 







>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>












|





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
..
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
...
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
...
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
...
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
...
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
...
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
...
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
...
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
...
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
...
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
...
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
....
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
....
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
....
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
....
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
....
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
....
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
....
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
....
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
....
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
....
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
/*
 * Copyright (c) 2014 - 2016, Roy Keene
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 	1. Redistributions of source code must retain the above copyright
 * 	   notice, this list of conditions and the following disclaimer.
 * 	2. Redistributions in binary form must reproduce the above copyright
 * 	   notice, this list of conditions and the following disclaimer in the
 * 	   documentation and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <sys/sendfile.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/prctl.h>
#include <arpa/inet.h>
#include <sys/mman.h>
#include <sys/stat.h>
................................................................................
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <pwd.h>

/* Compile time constants */
#define FILED_VERSION "1.21"
#define FILED_SENDFILE_MAX 16777215
#define FILED_MAX_FAILURE_COUNT 30
#define FILED_DEFAULT_TYPE "application/octet-stream"
#define FILED_PATH_BUFFER_SIZE 1010

/* Default values */
#define PORT 80
#define THREAD_COUNT 5
#define BIND_ADDR "::"
#define CACHE_SIZE 8209
#define LOG_FILE "-"

/* Fuzzing Test Code */
#ifdef FILED_TEST_AFL
#define FILED_DONT_LOG 1
#define pthread_create(a, x, y, z) afl_pthread_create(a, x, y, z)
#define bind(x, y, z) afl_bind(x, y, z)
#define socket(x, y, z) 8193
#define listen(x, y) 0
#define accept(x, y, z) afl_accept(x, y, z)
#define close(x) { if (strcmp(#x, "random_fd") == 0) { close(x); } else { exit(0); } }
#define fclose(x) exit(0)

static int afl_accept(int x, void *addr, void *z) {
	((struct sockaddr_in6 *) addr)->sin6_family = AF_INET + AF_INET6 + 1;
	return(STDIN_FILENO);
	x = x;
	z = z;
}

static int afl_bind(int x, void *y, socklen_t z) {
	return(8194);
	x = x;
	y = y;
	z = z;
}

static int afl_pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg) {
	start_routine(arg);
	exit(3);
	thread = thread;
	attr = attr;
}
#endif

/* Configuration options that work threads need to be aware of */
struct filed_options {
	int vhosts_enabled;
	const char *fake_newroot;
};

/* Arguments for worker threads */
struct filed_worker_thread_args {
	int fd;
	struct filed_options options;
};
................................................................................
			off_t length;   /*** Range length ***/
		} range;

		struct {
			int present;
			char host[FILED_PATH_BUFFER_SIZE];
		} host;

		enum {
			FILED_CONNECTION_CLOSE,
			FILED_CONNECTION_KEEP_ALIVE
		} connection;
	} headers;
};

/* Log record */
struct filed_log_entry {
	/* Type of log entry */
	enum {
................................................................................
	/* Message buffer for type = MESSAGE */
	/* Path buffer for type = TRANSFER */
	char buffer[FILED_PATH_BUFFER_SIZE];

	/* Items for type = TRANSFER */
	int http_code;
	const char *reason;
	time_t connecttime;
	time_t starttime;
	time_t endtime;
	off_t req_offset;
	off_t req_length;
	off_t sent_length;
	off_t file_length;
	char ip[128];
................................................................................
struct filed_fileinfo *filed_fileinfo_fdcache = NULL;
unsigned int filed_fileinfo_fdcache_size = 0;

/** Logging **/
struct filed_log_entry *filed_log_msg_list;
pthread_mutex_t filed_log_msg_list_mutex;
pthread_cond_t filed_log_msg_list_ready;

/* Signal Handler */
static void filed_signal_handler(int signal_number) {
	struct filed_fileinfo *cache;
	unsigned int idx;

	switch (signal_number) {
		case SIGHUP:
			for (idx = 0; idx < filed_fileinfo_fdcache_size; idx++) {
				cache = &filed_fileinfo_fdcache[idx];

				pthread_mutex_lock(&cache->mutex);

				cache->path[0] = '\0';
				if (cache->fd >= 0) {
					close(cache->fd);

					cache->fd = -1;
				}

				cache->lastmod = "";
				cache->type = "";

				pthread_mutex_unlock(&cache->mutex);
			}
			break;
	}

	return;
}

/* Initialize cache */
static int filed_init_cache(unsigned int cache_size) {
	unsigned int idx;
	int mutex_init_ret;

	/* Cache may not be re-initialized */
	if (filed_fileinfo_fdcache_size != 0 || filed_fileinfo_fdcache != NULL) {
		return(1);
	}

	/* Cache does not need to be allocated if cache is not enabled */
	if (cache_size == 0) {
		return(0);
	}

	/* Allocate cache */
	filed_fileinfo_fdcache_size = cache_size;
	filed_fileinfo_fdcache = malloc(sizeof(*filed_fileinfo_fdcache) * filed_fileinfo_fdcache_size);
	if (filed_fileinfo_fdcache == NULL) {
		return(1);
	}
................................................................................

	return(0);
}

/* Initialize process */
static int filed_init(unsigned int cache_size) {
	static int called = 0;
	struct sigaction signal_handler_info;
	sigset_t signal_handler_mask;
	ssize_t read_ret = 0;
	unsigned int random_value = 0;
	int cache_ret;
	int random_fd;

	if (called) {
		return(0);
	}

	called = 1;

	/* Attempt to lock all memory to physical RAM (but don't care if we can't) */
	mlockall(MCL_CURRENT | MCL_FUTURE);

	/* Establish signal handlers */
	/* SIGPIPE should interrupt system calls */
	sigfillset(&signal_handler_mask);
	signal_handler_info.sa_handler = filed_signal_handler;
	signal_handler_info.sa_mask = signal_handler_mask;
	signal_handler_info.sa_flags = SA_RESTART;
	sigaction(SIGPIPE, &signal_handler_info, NULL);

	/* Handle SIGHUP to release all caches */
	sigfillset(&signal_handler_mask);
	signal_handler_info.sa_handler = filed_signal_handler;
	signal_handler_info.sa_mask = signal_handler_mask;
	signal_handler_info.sa_flags = 0;
	sigaction(SIGHUP, &signal_handler_info, NULL);

	/* Initialize cache structure */
	cache_ret = filed_init_cache(cache_size);
	if (cache_ret != 0) {
		return(cache_ret);
	}

	/* Initialize random number generator */
	random_fd = open("/dev/urandom", O_RDONLY);
	if (random_fd >= 0) {
		read_ret = read(random_fd, &random_value, sizeof(random_value));

		close(random_fd);
	}

	random_value ^= getpid();
	random_value ^= getuid();
	random_value ^= time(NULL);

	srandom(random_value);

	return(0);

	/* NOTREACH: Read may fail or succeed, we don't actually care */
	read_ret = read_ret;
}

/* Listen on a particular address/port */
static int filed_listen(const char *address, unsigned int port) {
	struct sockaddr_in6 addr_v6;
	struct sockaddr_in addr_v4;
	struct sockaddr *addr;
	socklen_t addr_len;
	int pton_ret, bind_ret, listen_ret;
	int family;
	int fd;


	family = AF_INET6;
	pton_ret = inet_pton(family, address, &addr_v6.sin6_addr.s6_addr);
	if (pton_ret != 1) {
		family = AF_INET;
		pton_ret = inet_pton(family, address, &addr_v4.sin_addr.s_addr);
		if (pton_ret != 1) {
................................................................................
#ifdef FILED_DONT_LOG
#  define filed_logging_thread_init(x) 0
#  define filed_log_msg_debug(x, ...) /**/
#  define filed_log_msg(x, ...) /**/
#  define filed_log_entry(x) /**/
#  define filed_log_ip(x, ...) NULL
#  define filed_log_new(x) &local_dummy_log
#  define filed_log_free(x) /**/

/* Return logging handle */
static FILE *filed_log_open(const char *file) {
	return(stdout);
	file = file;
}
#else
#  define filed_log_free(x) free(x)
#  ifdef FILED_DEBUG
#    define filed_log_msg_debug(x, ...) { fprintf(stderr, x, __VA_ARGS__); fprintf(stderr, "\n"); fflush(stderr); }
#  else
#    define filed_log_msg_debug(x, ...) /**/
#  endif

/* Initialize logging thread */
................................................................................
							break;
					}

					if (curr->endtime == ((time_t) -1)) {
						curr->endtime = now;
					}

					fprintf(fp, "TRANSFER METHOD=%s PATH=%s SRC=%s:%i CLIENT.TIME.CONNECT=%llu REQUEST.TIME.START=%llu REQUEST.TIME.END=%llu CODE.VALUE=%u CODE.REASON=%s REQUEST.OFFSET=%llu REQUEST.LENGTH=%llu FILE.LENGTH=%llu TRANSFER.LENGTH=%llu",
						method,
						curr->buffer,
						curr->ip, curr->port,
						(unsigned long long) curr->connecttime,
						(unsigned long long) curr->starttime,
						(unsigned long long) curr->endtime,
						curr->http_code, curr->reason,
						(unsigned long long) curr->req_offset,
						(unsigned long long) curr->req_length,
						(unsigned long long) curr->file_length,
						(unsigned long long) curr->sent_length
					);

					break;
			}
			fprintf(fp, " THREAD=%llu TIME=%llu\n",
				(unsigned long long) ((intptr_t) curr->thread),
				(unsigned long long) now
			);
			fflush(fp);

			prev = curr;
			curr = curr->_prev;

................................................................................
	struct filed_log_entry *retval;

	retval = malloc(sizeof(*retval));

	if (initialize) {
		retval->buffer[0] = '\0';
		retval->http_code = -1;
		retval->connecttime = 0;
		retval->starttime = 0;
		retval->endtime = 0;
		retval->req_offset = 0;
		retval->req_length = 0;
		retval->sent_length = 0;
		retval->file_length = 0;
		retval->ip[0] = '\0';
................................................................................
	filed_log_msg_list = NULL;

	pthread_mutex_init(&filed_log_msg_list_mutex, NULL);

	pthread_create(&thread_id, NULL, filed_logging_thread, args);

	filed_log_msg("START");

	return(0);
}
#endif

#ifdef FILED_DONT_TIMEOUT
#define filed_sockettimeout_thread_init() 0
#define filed_sockettimeout_init() 0
#define filed_sockettimeout_accept(x) /**/
#define filed_sockettimeout_processing_start(x) /**/
#define filed_sockettimeout_processing_end(x) /**/
#define filed_sockettimeout_close(x, y) /**/
#else
time_t filed_sockettimeout_time;
struct {
	time_t expiration_time;
	pthread_t thread_id;
	enum {
		filed_sockettimeout_valid,
		filed_sockettimeout_invalid,
	} valid;
} *filed_sockettimeout_sockstatus;
long filed_sockettimeout_sockstatus_length;
int filed_sockettimeout_devnull_fd;
pthread_mutex_t filed_sockettimeout_mutex = PTHREAD_MUTEX_INITIALIZER;

static int filed_sockettimeout_sockfd_in_range(int sockfd) {
	if (sockfd < 3) {
		return(0);
	}

	if (sockfd > filed_sockettimeout_sockstatus_length) {
		return(0);
	}

	return(1);
}

static void filed_sockettimeout_expire(int sockfd, int length, int lockheld) {
	time_t now, expire;

	if (!lockheld) {
		pthread_mutex_lock(&filed_sockettimeout_mutex);
	}

	now = filed_sockettimeout_time;

	expire = now + length;

	filed_sockettimeout_sockstatus[sockfd].expiration_time = expire;

	if (!lockheld) {
		pthread_mutex_unlock(&filed_sockettimeout_mutex);
	}

	return;
}

static void filed_sockettimeout_accept(int sockfd) {
	if (!filed_sockettimeout_sockfd_in_range(sockfd)) {
		return;
	}

	pthread_mutex_lock(&filed_sockettimeout_mutex);

	filed_sockettimeout_expire(sockfd, 60, 1);

	filed_sockettimeout_sockstatus[sockfd].thread_id = pthread_self();

	filed_sockettimeout_sockstatus[sockfd].valid = filed_sockettimeout_valid;

	pthread_mutex_unlock(&filed_sockettimeout_mutex);

	return;
}

static void filed_sockettimeout_processing_start(int sockfd) {
	if (!filed_sockettimeout_sockfd_in_range(sockfd)) {
		return;
	}

	filed_sockettimeout_expire(sockfd, 86400, 0);

	return;
}

static void filed_sockettimeout_processing_end(int sockfd) {
	if (!filed_sockettimeout_sockfd_in_range(sockfd)) {
		return;
	}

	filed_sockettimeout_expire(sockfd, 60, 0);

	return;
}

static void filed_sockettimeout_close(int sockfd, int lockheld) {
	if (!filed_sockettimeout_sockfd_in_range(sockfd)) {
		return;
	}

	if (!lockheld) {
		pthread_mutex_lock(&filed_sockettimeout_mutex);
	}

	filed_sockettimeout_sockstatus[sockfd].valid = filed_sockettimeout_invalid;

	if (!lockheld) {
		pthread_mutex_unlock(&filed_sockettimeout_mutex);
	}

	return;
}

static void *filed_sockettimeout_thread(void *arg) {
	struct timespec sleep_time;
	time_t now, expiration_time;
	pthread_t thread_id;
	long idx;
	int count;
	int valid;
	int time_interval = 30;
	int check_period = 90;

	while (1) {
		for (count = 0; count < (check_period / time_interval); count++) {
			sleep_time.tv_sec = time_interval;
			sleep_time.tv_nsec = 0;
			nanosleep(&sleep_time, NULL);

			pthread_mutex_lock(&filed_sockettimeout_mutex);

			now = time(NULL);

			filed_sockettimeout_time = now;

			pthread_mutex_unlock(&filed_sockettimeout_mutex);
		}

		pthread_mutex_lock(&filed_sockettimeout_mutex);

		for (idx = 0; idx < filed_sockettimeout_sockstatus_length; idx++) {
			valid = filed_sockettimeout_sockstatus[idx].valid;

			if (valid != filed_sockettimeout_valid) {
				continue;
			}

			expiration_time = filed_sockettimeout_sockstatus[idx].expiration_time;

			thread_id = filed_sockettimeout_sockstatus[idx].thread_id;

			if (expiration_time > now) {
				continue;
			}

			filed_sockettimeout_close(idx, 1);

			dup2(filed_sockettimeout_devnull_fd, idx);

			pthread_kill(thread_id, SIGPIPE);
		}

		pthread_mutex_unlock(&filed_sockettimeout_mutex);
	}

	return(NULL);

	/* NOTREACH: We don't actually take any arguments */
	arg = arg;
}

static int filed_sockettimeout_thread_init(void) {
	pthread_t thread_id;

	pthread_create(&thread_id, NULL, filed_sockettimeout_thread, NULL);

	return(0);
}

static int filed_sockettimeout_init(void) {
	long maxfd, idx;

	maxfd = sysconf(_SC_OPEN_MAX);
	if (maxfd <= 0) {
		maxfd = 4096;
	}

	filed_sockettimeout_sockstatus_length = maxfd;
	filed_sockettimeout_sockstatus = malloc(sizeof(*filed_sockettimeout_sockstatus) * filed_sockettimeout_sockstatus_length);
	if (filed_sockettimeout_sockstatus == NULL) {
		return(-1);
	}

	for (idx = 0; idx < maxfd; idx++) {
		filed_sockettimeout_sockstatus[idx].valid = filed_sockettimeout_invalid;
	}

	filed_sockettimeout_devnull_fd = open("/dev/null", O_RDWR);
	if (filed_sockettimeout_devnull_fd < 0) {
		return(-1);
	}

	return(0);
}
#endif

/* Format time per RFC2616 */
static char *filed_format_time(char *buffer, size_t buffer_len, const time_t timeinfo) {
................................................................................
		(unsigned long long) time(NULL),
		(unsigned long long) random(),
		(unsigned long long) random(),
		(unsigned long long) random(),
		(unsigned long long) random()
	);
}

#ifdef FILED_FAKE_CHROOT
/* Translate a path into a fake chroot path */
static const char *filed_path_translate(const char *path, struct filed_options *options) {
	static __thread char pathBuffer[8192];
	int snprintf_ret;

	/* If no alternative root is specified, return the unadorned path */
	if (!options->fake_newroot) {
		return(path);
	}

	/* Verify that this request will not go outside of the specified root */
	if (strstr(path, "/../") != NULL || path[0] != '/') {
		filed_log_msg_debug("Unable to translate path \"%s\", contains invalid characters", path);

		return(options->fake_newroot);
	}

	/* Create the new path into our local (TLS) static buffer */
	snprintf_ret = snprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", options->fake_newroot, path);
	if (snprintf_ret < 0 || ((unsigned int) snprintf_ret) >= sizeof(pathBuffer)) {
		filed_log_msg_debug("Unable to translate path \"%s\", will not fit into new buffer", path);

		return(options->fake_newroot);
	}

	filed_log_msg_debug("Translating path \"%s\" into \"%s\"", path, pathBuffer);

	/* Return the new path */
	return(pathBuffer);
}

static void filed_path_translate_set_root(const char *var, struct filed_options *options, const char *val) {
	options->fake_newroot = strdup(val);

	return;

	/* var is only used in the macro -- discard it here */
	var = var;
}
#else
#define filed_path_translate(path, options) path
#define filed_path_translate_set_root(var, options, val) var = strdup(val)
#endif

/* Open a file and return file information */
static struct filed_fileinfo *filed_open_file(const char *path, struct filed_fileinfo *buffer, struct filed_options *options) {
	struct filed_fileinfo *cache;
	unsigned int cache_idx;
	off_t len;
	int fd;

	if (filed_fileinfo_fdcache_size != 0) {
		cache_idx = filed_hash((const unsigned char *) path, filed_fileinfo_fdcache_size);

		cache = &filed_fileinfo_fdcache[cache_idx];

		filed_log_msg_debug("Locking mutex for idx: %lu", (unsigned long) cache_idx);

		pthread_mutex_lock(&cache->mutex);

		filed_log_msg_debug("Completed locking mutex for idx: %lu", (unsigned long) cache_idx);
	} else {
		cache_idx = 0;
		cache = buffer;
		cache->path[0] = '\0';
		cache->fd = -1;
	}

	if (strcmp(path, cache->path) != 0) {
		filed_log_msg_debug("Cache miss for idx: %lu: OLD \"%s\", NEW \"%s\"", (unsigned long) cache_idx, cache->path, path);

		fd = open(filed_path_translate(path, options), O_RDONLY | O_LARGEFILE);
		if (fd < 0) {
			if (filed_fileinfo_fdcache_size != 0) {
				pthread_mutex_unlock(&cache->mutex);
			}

			return(NULL);
		}

		if (cache->fd >= 0) {
			close(cache->fd);
		}
................................................................................

		/* XXX:TODO: Determine */
		cache->lastmod = filed_format_time(cache->lastmod_b, sizeof(cache->lastmod_b), time(NULL) - 30);
	} else {
		filed_log_msg_debug("Cache hit for idx: %lu: PATH \"%s\"", (unsigned long) cache_idx, path);
	}

	if (filed_fileinfo_fdcache_size != 0) {
		/*
		 * We have to make a duplicate FD, because once we release the cache
		 * mutex, the file descriptor may be closed
		 */
		fd = dup(cache->fd);
		if (fd < 0) {
			pthread_mutex_unlock(&cache->mutex);

			return(NULL);
		}

		buffer->fd = fd;
		buffer->len = cache->len;
		buffer->type = cache->type;
		memcpy(buffer->lastmod_b, cache->lastmod_b, sizeof(buffer->lastmod_b));
		memcpy(buffer->etag, cache->etag, sizeof(buffer->etag));
		buffer->lastmod = buffer->lastmod_b + (cache->lastmod - cache->lastmod_b);

		pthread_mutex_unlock(&cache->mutex);
	}

	return(buffer);

	/* options is only used if fake chroot is enabled, confuse the compiler */
	options = options;
}

/* Process an HTTP request and return the path requested */
static struct filed_http_request *filed_get_http_request(FILE *fp, struct filed_http_request *buffer_st, struct filed_options *options) {
	char *method, *path;
	char *buffer, *workbuffer, *workbuffer_next;
	char *fgets_ret;
................................................................................

	/* Set to default values */
	range_start = 0;
	range_end   = 0;
	range_request = 0;
	range_length = -1;
	buffer_st->headers.host.present = 0;
	buffer_st->headers.connection = FILED_CONNECTION_CLOSE;

	buffer = buffer_st->tmpbuf;
	buffer_len = sizeof(buffer_st->tmpbuf);

	fgets_ret = fgets(buffer, buffer_len, fp);
	if (fgets_ret == NULL) {
		return(NULL);
................................................................................

			workbuffer = buffer + 5;
			while (*workbuffer == ' ') {
				workbuffer++;
			}

			strcpy(buffer_st->headers.host.host, workbuffer);
		} else if (strncasecmp(buffer, "Connection: Keep-Alive", 22) == 0) {
			buffer_st->headers.connection = FILED_CONNECTION_KEEP_ALIVE;
		}

		if (memcmp(buffer, "\r\n", 2) == 0) {
			break;
		}
	}

................................................................................
	/** reason must point to a globally allocated value **/
	log->reason = reason;
	log->http_code = error_number;

	filed_log_entry(log);

	/* Close connection */
	filed_sockettimeout_close(fileno(fp), 0);

	fclose(fp);

	return;
}

/* Return a redirect to index.html */
#ifndef FILED_DONT_REDIRECT_DIRECTORIES
static void filed_redirect_index(FILE *fp, const char *date_current, const char *path, struct filed_log_entry *log) {
	int http_code = 302;
	fprintf(fp, "HTTP/1.1 %i OK\r\nDate: %s\r\nServer: filed\r\nLast-Modified: %s\r\nContent-Length: 0\r\nConnection: close\r\nLocation: %s\r\n\r\n",
		http_code,
		date_current,
		date_current,
		"index.html"
	);

................................................................................
	/* Log redirect */
	log->reason = "redirect";
	log->http_code = http_code;

	filed_log_entry(log);

	/* Close connection */
	filed_sockettimeout_close(fileno(fp), 0);

	fclose(fp);

	return;

	/* Currently unused: path */
	path = path;
}
#endif

/* Convert an enum representing the "Connection" header value to a string */
static const char *filed_connection_str(int connection_value) {
	switch (connection_value) {
		case FILED_CONNECTION_CLOSE:
			return("close");
		case FILED_CONNECTION_KEEP_ALIVE:
			return("keep-alive");
	}

	return("close");
}

/* Handle a single request from a client */
static int filed_handle_client(int fd, struct filed_http_request *request, struct filed_log_entry *log, struct filed_options *options) {
	struct filed_fileinfo *fileinfo;
	ssize_t sendfile_ret;
	size_t sendfile_size;
	off_t sendfile_offset, sendfile_sent, sendfile_len;
	char *path;
	char *date_current, date_current_b[64];
	int http_code;
	FILE *fp;

	/* Indicate the connection start time */
	log->connecttime = time(NULL);

	/* Determine current time */
	date_current = filed_format_time(date_current_b, sizeof(date_current_b), time(NULL));

	/* Open socket as ANSI I/O for ease of use */
	fp = fdopen(fd, "w+b");
	if (fp == NULL) {
		filed_sockettimeout_close(fd, 0);

		close(fd);

		log->buffer[0] = '\0';
		log->http_code = -1;
		log->reason = "fdopen_failed";

		filed_log_entry(log);

		return(FILED_CONNECTION_CLOSE);
	}

	request = filed_get_http_request(fp, request, options);

	if (request == NULL) {
		log->buffer[0] = '\0';

		filed_error_page(fp, date_current, 500, FILED_REQUEST_METHOD_GET, "format", log);

		return(FILED_CONNECTION_CLOSE);
	}

	filed_sockettimeout_processing_start(fd);

	path = request->path;
	strcpy(log->buffer, path);
	log->method = request->method;

	/* If the requested path is a directory, redirect to index page */
	if (request->type == FILED_REQUEST_TYPE_DIRECTORY) {
#ifdef FILED_DONT_REDIRECT_DIRECTORIES
		char localpath[8192];
		int snprintf_ret;

		snprintf_ret = snprintf(localpath, sizeof(localpath), "%s/index.html", path);

		if (snprintf_ret <= 0 || snprintf_ret > (sizeof(localpath) - 1)) {
			filed_error_page(fp, date_current, 500, request->method, "path_format", log);

			return(FILED_CONNECTION_CLOSE);
		}

		path = localpath;
#else
		filed_redirect_index(fp, date_current, path, log);


		return(FILED_CONNECTION_CLOSE);
#endif
	}

	fileinfo = filed_open_file(path, &request->fileinfo, options);
	if (fileinfo == NULL) {
		filed_error_page(fp, date_current, 404, request->method, "open_failed", log);

		return(FILED_CONNECTION_CLOSE);
	}

	if (request->headers.range.present) {
		if (request->headers.range.offset != 0 || request->headers.range.length >= 0) {
			if (request->headers.range.offset >= fileinfo->len) {
				filed_error_page(fp, date_current, 416, request->method, "range_invalid", log);

				close(fileinfo->fd);

				return(FILED_CONNECTION_CLOSE);
			}

			if (request->headers.range.length == ((off_t) -1)) {
				filed_log_msg_debug("Computing length to fit in bounds: fileinfo->len = %llu, request->headers.range.offset = %llu",
					(unsigned long long) fileinfo->len,
					(unsigned long long) request->headers.range.offset
				);
................................................................................
		http_code = 200;

		/* Compute fake range parameters that includes the entire file */
		request->headers.range.offset = 0;
		request->headers.range.length = fileinfo->len;
	}

	fprintf(fp, "HTTP/1.1 %i OK\r\nDate: %s\r\nServer: filed\r\nLast-Modified: %s\r\nContent-Length: %llu\r\nAccept-Ranges: bytes\r\nContent-Type: %s\r\nConnection: %s\r\nETag: \"%s\"\r\n",
		http_code,
		date_current,
		fileinfo->lastmod,
		(unsigned long long) request->headers.range.length,
		fileinfo->type,
		filed_connection_str(request->headers.connection),
		fileinfo->etag
	);

	if (http_code == 206) {
		fprintf(fp, "Content-Range: bytes %llu-%llu/%llu\r\n",
			(unsigned long long) request->headers.range.offset,
			(unsigned long long) (request->headers.range.offset + request->headers.range.length - 1),
................................................................................
	log->endtime = (time_t) -1;
	log->sent_length = sendfile_sent;

	filed_log_entry(log);

	close(fileinfo->fd);

	if (request->headers.connection != FILED_CONNECTION_KEEP_ALIVE) {
		filed_sockettimeout_close(fd, 0);

		fclose(fp);


		return(FILED_CONNECTION_CLOSE);
	}

	filed_sockettimeout_processing_end(fd);

	return(FILED_CONNECTION_KEEP_ALIVE);
}

/* Handle incoming connections */
static void *filed_worker_thread(void *arg_v) {
	struct filed_worker_thread_args *arg;
	struct filed_http_request request;
	struct filed_log_entry *log, local_dummy_log;
	struct filed_options *options;
	struct sockaddr_in6 addr;
	socklen_t addrlen;
	int failure_count = 0, max_failure_count = FILED_MAX_FAILURE_COUNT;
	int connection_state = FILED_CONNECTION_CLOSE;
	int master_fd, fd = -1;

	/* Read arguments */
	arg = arg_v;

	master_fd = arg->fd;
	options = &arg->options;

................................................................................
			filed_log_msg("ALLOCATE_LOG_MSG_FAILED");

			break;
		}

		log->type = FILED_LOG_TYPE_TRANSFER;

		/* If we closed the old connection, accept a new one */
		if (connection_state == FILED_CONNECTION_CLOSE) {
			/* Accept a new client */
			addrlen = sizeof(addr);

			fd = accept(master_fd, (struct sockaddr *) &addr, &addrlen);
		}

		/*
		 * If we fail, make a note of it so we don't go into a loop of
		 * accept() failing
		 */
		if (fd < 0) {
			/* Log the new connection */
			filed_log_msg("ACCEPT_FAILED");

			failure_count++;

			filed_log_free(log);

			continue;
		}

		filed_sockettimeout_accept(fd);

		/* Fill in log structure */
		if (filed_log_ip((struct sockaddr *) &addr, log->ip, sizeof(log->ip)) == NULL) {
			log->ip[0] = '\0';
			log->port = 0;
		} else {
			log->port = addr.sin6_port;
		}

		/* Reset failure count*/
		failure_count = 0;

		/* Handle socket */
		connection_state = filed_handle_client(fd, &request, log, options);
	}

	/* Report error */
	filed_log_msg("THREAD_DIED ABNORMAL");

	return(NULL);

................................................................................

	return(0);
}

/* Run process */
int main(int argc, char **argv) {
	struct option options[12];
	struct filed_options thread_options = {0};
	const char *bind_addr = BIND_ADDR, *newroot = NULL, *log_file = LOG_FILE;
	FILE *log_fp;
	uid_t user = 0;
	int port = PORT, thread_count = THREAD_COUNT;
	int cache_size = CACHE_SIZE;
	int init_ret, chroot_ret, setuid_ret, lookup_ret, chdir_ret;
	int setuid_enabled = 0, daemon_enabled = 0;
	int ch;
	int fd;




	/* Process arguments */
	filed_getopt_long_setopt(&options[0], "port", required_argument, 'p');
	filed_getopt_long_setopt(&options[1], "threads", required_argument, 't');
	filed_getopt_long_setopt(&options[2], "cache", required_argument, 'c');
	filed_getopt_long_setopt(&options[3], "bind", required_argument, 'b');
	filed_getopt_long_setopt(&options[4], "user", required_argument, 'u');
	filed_getopt_long_setopt(&options[5], "root", required_argument, 'r');
................................................................................
				if (lookup_ret != 0) {
					filed_print_help(stderr, 0, "Invalid username specified");

					return(1);
				}
				break;
			case 'r':
				filed_path_translate_set_root(newroot, &thread_options, optarg);
				break;
			case 'l':
				log_file = strdup(optarg);
				break;
			case 'd':
				daemon_enabled = 1;
				break;
................................................................................
	/* Create listening socket */
	fd = filed_listen(bind_addr, port);
	if (fd < 0) {
		perror("filed_listen");

		return(1);
	}

	/* Initialize timeout structures */
	init_ret = filed_sockettimeout_init();
	if (init_ret != 0) {
		perror("filed_sockettimeout_init");

		return(8);
	}

	/* Become a daemon */
	if (daemon_enabled) {
		init_ret = filed_daemonize();
		if (init_ret != 0) {
			perror("filed_daemonize");

................................................................................
	/* Create logging thread */
	init_ret = filed_logging_thread_init(log_fp);
	if (init_ret != 0) {
		perror("filed_logging_thread_init");

		return(4);
	}

	/* Create socket termination thread */
	init_ret = filed_sockettimeout_thread_init();
	if (init_ret != 0) {
		perror("filed_sockettimeout_thread_init");

		return(7);
	}

	/* Create worker threads */
	init_ret = filed_worker_threads_init(fd, thread_count, &thread_options);
	if (init_ret != 0) {
		perror("filed_worker_threads_init");

		return(5);
	}

	/* Wait for threads to exit */
	/* XXX:TODO: Monitor thread usage */
	while (1) {
		sleep(86400);
	}

	/* Return in failure */
	return(2);
}