summaryrefslogtreecommitdiff
path: root/src/fileserv.c
blob: 98c0c33656647f601f171532788819a8eb8fd7c6 (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
/* This file is part of fileserv.
   Copyright (C) 2017, 2018 Sergey Poznyakoff

   Fileserv 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 3, or (at your option)
   any later version.

   Fileserv is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with fileserv.  If not, see <http://www.gnu.org/licenses/>. */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <inttypes.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <signal.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <ctype.h>
#define MHD_PLATFORM_H
#include <microhttpd.h>

#include "fileserv.h"
#include "mimetypes.h"
#include <sys/queue.h>

#ifndef DEFAULT_ADDRESS
# define DEFAULT_ADDRESS "0.0.0.0"
#endif
#ifndef DEFAULT_SERVICE
# define DEFAULT_SERVICE "8080"
#endif

char const *progname;
int verbose; /* reserved for future use */
char *address = DEFAULT_ADDRESS;
char *forwarded_header = "X-Forwarded-For";
char *index_css;
char *tmpdir;
char *user;
char *group;
char *mime_types_file;

static void
fileserv_panic(void *cls, const char *file, unsigned int line,
	     const char *reason)
{
        if (reason)
		error("%s:%d: MHD PANIC: %s", file, line, reason);
	else
		error("%s:%d: MHD PANIC", file, line);
	abort();
}

void
usage(void)
{
	printf("usage: %s [OPTIONS] [HOST:]URL:DIR...\n", progname);
	printf("OPTIONS are:\n\n");
	printf("  -c FILE              read configuration from FILE\n");
	printf("  -f                   remain in the foreground\n");
	printf("  -h                   show this help summary\n");
	printf("  -v                   increase verbosity\n");
}

int
open_node(char const *node, char const *serv, struct sockaddr **saddr)
{
	struct addrinfo hints;
	struct addrinfo *res;
	int reuse;
	int fd;
	int rc;
	
	memset(&hints, 0, sizeof (hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	rc = getaddrinfo(node, serv, &hints, &res);
	if (rc) {
		error("%s: %s", node, gai_strerror(rc));
		exit(1);
	}

	fd = socket(res->ai_family, res->ai_socktype, 0);
	if (fd == -1) {
		error("socket: %s", strerror(errno));
		exit(1);
	}

	reuse = 1;
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
		   &reuse, sizeof(reuse));
	if (bind(fd, res->ai_addr, res->ai_addrlen) == -1) {
		error("bind: %s", strerror(errno));
		exit(1);
	}

	if (listen(fd, 8) == -1) {
		error("listen: %s", strerror(errno));
		exit(1);
	}

        if (saddr) {
		*saddr = xmalloc(res->ai_addrlen);
		memcpy(*saddr, res->ai_addr, res->ai_addrlen);
	}
	freeaddrinfo(res);

	return fd;
}

int
open_listener(char const *addr, struct sockaddr **saddr)
{
	size_t len;
	int fd;
	
	len = strcspn(addr, ":");
	if (len == 0)
		fd = open_node(DEFAULT_ADDRESS, addr + 1, saddr);
	else if (addr[len] == 0)
		fd = open_node(addr, DEFAULT_SERVICE, saddr);
	else {
		char *node;
		node = xmalloc(len + 1);
		memcpy(node, addr, len);
		node[len] = 0;
		fd = open_node(node, addr + len + 1, saddr);
		free(node);
	}
	return fd;
}

struct urimap {
	char *host;
	char *uri;
	size_t uri_len;
	char *dir;
	size_t dir_len;
	TAILQ_ENTRY(urimap) next;
};

TAILQ_HEAD(,urimap) map_head = TAILQ_HEAD_INITIALIZER(map_head);

struct urimap const *
urimap_find(char const *host, char const *url)
{
	struct urimap *map;
	size_t len = strlen(url);

	TAILQ_FOREACH(map, &map_head, next) {
		if (map->host && strcasecmp(map->host, host))
			continue;
		if (map->uri_len > len)
			continue;
		if (memcmp(url, map->uri, map->uri_len) == 0
		    && (url[map->uri_len] == '/' || url[map->uri_len] == 0))
			return map;
	}
	return NULL;
}	

struct urimap const *
urimap_find_dir(char const *host, char const *filename)
{
	struct urimap *map;
	size_t len = strlen(filename);

	TAILQ_FOREACH(map, &map_head, next) {
		if (map->host && strcasecmp(map->host, host))
			continue;
		if (map->dir_len > len)
			continue;
		if (memcmp(filename, map->dir, map->dir_len) == 0
		    && (filename[map->dir_len] == 0
			|| filename[map->dir_len] == '/'))
			return map;
	}
	return NULL;
}	

void
urimap_add(char *arg)
{
	struct urimap *map, *cur;
	char *copy, *p;
	
	map = xmalloc(sizeof(*map) + strlen(arg) + 1);
	copy = (char*)(map + 1);
	strcpy(copy, arg);
	p = strchr(copy, ':');
	if (p) {
		*p++ = 0;
		map->dir = strchr(p, ':');
		if (map->dir) {
			map->host = copy;
			map->uri = p;
			*map->dir++ = 0;
		} else {
			map->host = NULL;
			map->uri = copy;
			map->dir = p;
		}
	} else {
		map->host = NULL;
		map->uri = copy;
		map->dir = NULL;
	}
	map->uri_len = strlen(map->uri);
	while (map->uri_len > 0 && map->uri[map->uri_len-1] == '/')
		map->uri[--map->uri_len] = 0;
	if (map->dir) {
		map->dir_len = strlen(map->dir);
		while (map->dir_len > 0 && map->dir[map->dir_len-1] == '/')
			map->dir[--map->dir_len] = 0;
	}

	/* Make sure the list is sorted by uri_len in descending order */
	TAILQ_FOREACH(cur, &map_head, next) {
		if (cur->uri_len < map->uri_len) {
			TAILQ_INSERT_BEFORE(cur, map, next);
			return;
		}
	}
	TAILQ_INSERT_TAIL(&map_head, map, next);
}

static char *
cfname(char const *fname)
{
	/* FIXME */
	return realpath(fname, NULL);
}


static inline int
errno_to_http_code(int ec)
{
	return ec == ENOENT ? MHD_HTTP_NOT_FOUND : MHD_HTTP_FORBIDDEN;
}

static int
find_index_file(char const *dir, CONFIG *conf, char **index_file,
		struct stat *pst)
{
	char *cf;
	
	if (conf->index_files_v) {
		int i;
		int lasterr = 0;
		for (i = 0; conf->index_files_v[i]; i++) {
			struct stat st;
			cf = catfile(dir, conf->index_files_v[i]);
			if (access(cf, F_OK) || lstat(cf, &st)) {
				free(cf);
				lasterr = errno;
				continue;
			}
			if (S_ISDIR(st.st_mode)) {
				free(cf);
				lasterr = ENOENT;
				continue;
			}
			*index_file = cf;
			*pst = st;
			return MHD_HTTP_OK;
		}
		return errno_to_http_code(lasterr);
	}
	return MHD_HTTP_FORBIDDEN;
}

typedef struct file_resp {
	int fd;
	char *file_name;
	CONFIG *conf;
	struct stat st;
	char const *type;
	char *location;
} FILE_RESP;

static void
file_resp_init(FILE_RESP *resp)
{
	memset(resp, 0, sizeof(*resp));
	resp->fd = -1;
}

static void
file_resp_free(FILE_RESP *resp)
{
	if (resp->fd >= 0)
		close(resp->fd);
	free(resp->file_name);
	config_free(resp->conf);
	free(resp->location);
}

static char *
make_location(char const *proto, char const *host, char const *url)
{
	size_t len;
	char *buf;

	len = strlen(proto) + 3 + strlen(host) + strlen(url) + 1;
	if (url[0] != '/')
		len++;
	buf = malloc(len + 1);
	if (buf) {
		strcpy(buf, proto);
		strcat(buf, "://");
		strcat(buf, host);
		if (url[0] != '/')
			strcat(buf, "/");
		strcat(buf, url);
		strcat(buf, "/");
	}
	return buf;
}

static INDEX_SORT_COL
get_sort_col(struct MHD_Connection *conn)
{
	char const *s = MHD_lookup_connection_value(conn,
						    MHD_GET_ARGUMENT_KIND,
						    "C");
	return s ? index_sort_col_from_arg(s[0]) : ISC_NAME;
}

static INDEX_SORT_COL
get_sort_ord(struct MHD_Connection *conn)
{
	char const *s = MHD_lookup_connection_value(conn,
						    MHD_GET_ARGUMENT_KIND,
						    "O");
	return s ? index_sort_ord_from_arg(s[0]) : ISO_ASC;
}

static char const *
basename(char const *s)
{
	char *p = strrchr(s, '/');
	return p ? p + 1 : s;
}

int
get_file_resp(struct MHD_Connection *conn, char const *url, FILE_RESP *resp)
{
	struct urimap const *map;
	char *cf;
	char const *host = MHD_lookup_connection_value(conn,
						       MHD_HEADER_KIND,
						       MHD_HTTP_HEADER_HOST);

	file_resp_init(resp);

	if (!filename_is_valid(url))
		return MHD_HTTP_NOT_FOUND;
	
	map = urimap_find(host, url);
	if (!map)
		return MHD_HTTP_NOT_FOUND;
	resp->file_name = catfile_n(map->dir, map->dir_len,
				    url + map->uri_len);
	if (lstat(resp->file_name, &resp->st))
		return errno_to_http_code(errno);
	
	resp->conf = dirconfig(resp->file_name, map->dir_len);

	if (filename_is_hidden(basename(resp->file_name), resp->conf))
		return MHD_HTTP_NOT_FOUND;		

	if (S_ISLNK(resp->st.st_mode)) {
		if (!resp->conf->follow)
			return MHD_HTTP_FORBIDDEN;

		cf = cfname(resp->file_name);
		if (!cf) {
			return MHD_HTTP_NOT_FOUND;
		} else if (urimap_find_dir(host, cf)) {
			free(resp->file_name);
			resp->file_name = cf;
			stat(cf, &resp->st);
		} else {
			free(cf);
			return MHD_HTTP_NOT_FOUND;
		}
	}

	if (S_ISDIR(resp->st.st_mode)) {
		int res;
		
		if (url[strlen(url) - 1] != '/') {
			resp->location = make_location("http",
						       host, url);
			if (!resp->location)
				return MHD_HTTP_INTERNAL_SERVER_ERROR;
			
			return MHD_HTTP_MOVED_PERMANENTLY;
		}

		res = find_index_file(resp->file_name, resp->conf, &cf,
				      &resp->st);
		if (res == MHD_HTTP_OK) {
			free(resp->file_name);
			resp->file_name = cf;
		} else if (resp->conf->listing) {
			char *template;
			int fd;
			
			template = catfile(tmpdir, "idxXXXXXX");
			fd = mkstemp(template);
			if (fd == -1) {
				error("can't create temporary file name: %s",
				      strerror(errno));
				return MHD_HTTP_INTERNAL_SERVER_ERROR;
			}
			unlink(template);
			free(template);

			res = directory_index(fd, resp->conf, url,
					      resp->file_name,
					      get_sort_col(conn),
					      get_sort_ord(conn));
			if (res) {
				close(fd);
				return MHD_HTTP_FORBIDDEN;
			}
			fstat(fd, &resp->st);
			resp->fd = fd;
			resp->type = "text/html";
			return MHD_HTTP_OK;
		} else 
			return res;
	} else if (!S_ISREG(resp->st.st_mode)) {
		return MHD_HTTP_FORBIDDEN;
	}

	resp->fd = open(resp->file_name, O_RDONLY);
	if (resp->fd == -1) {
		error("can't open %s: %s",
		      resp->file_name, strerror(errno));
		return errno_to_http_code(errno);
	}
	fstat(resp->fd, &resp->st);
	resp->type = get_file_type(resp->file_name);

	return MHD_HTTP_OK;
}

void 
http_log(struct MHD_Connection *connection,
	 char const *method, char const *url,
	 int status, struct stat const *st)
{
        char *ipstr;
	char const *host, *referer, *user_agent;
	time_t t;
	struct tm *tm;
	char tbuf[30];

	ipstr = get_remote_ip(connection);

	host = MHD_lookup_connection_value(connection,
					   MHD_HEADER_KIND,
					   MHD_HTTP_HEADER_HOST);
	referer = MHD_lookup_connection_value(connection,
					      MHD_HEADER_KIND,
					      MHD_HTTP_HEADER_REFERER);
	user_agent = MHD_lookup_connection_value(connection,
						 MHD_HEADER_KIND,
						 MHD_HTTP_HEADER_USER_AGENT);

	t = time(NULL);
	tm = localtime(&t);
	strftime(tbuf, sizeof(tbuf), "[%d/%b/%Y:%H:%M:%S %z]", tm);
	
	info("%s %s - - %s \"%s %s\" %3d %lu \"%s\" \"%s\"",
	     host, ipstr, tbuf, method, url, status, st ? st->st_size : 0,
	     referer ? referer : "",
	     user_agent ? user_agent : "");
	free(ipstr);
}

static int
http_error(struct MHD_Connection *connection,
	   char const *method, char const *url,
	   int status, char const *errtext)
{
	int ret;
	struct MHD_Response *response;
	if (!errtext)
		errtext = "";
	http_log(connection, method, url, status, NULL);
	response = MHD_create_response_from_buffer (strlen(errtext),
						    (void *) errtext,
						    MHD_RESPMEM_PERSISTENT);
	ret = MHD_queue_response(connection, status, response);
	MHD_destroy_response(response);
	return ret;
}

static int
http_redirect(struct MHD_Connection *connection,
	      char const *method, char const *url,
	      int status, char const *loc)
{
	int ret;
	struct MHD_Response *response;

	http_log(connection, method, url, status, NULL);
	response = MHD_create_response_from_buffer (strlen(loc),
						    xstrdup(loc),
						    MHD_RESPMEM_MUST_FREE);
	MHD_add_response_header(response,
				MHD_HTTP_HEADER_LOCATION,
				loc);

	ret = MHD_queue_response(connection, status, response);
	MHD_destroy_response(response);
	return ret;
}

static int
fileserv_handler(void *cls,
		 struct MHD_Connection *conn,
		 const char *url, const char *method,
		 const char *version,
		 const char *upload_data, size_t *upload_data_size,
		 void **con_cls)
{
	static int aptr;
	FILE_RESP resp;
	struct MHD_Response *response;
	int ret;
	int status;
	
	if (strcmp(method, MHD_HTTP_METHOD_GET) &&
	    strcmp(method, MHD_HTTP_METHOD_HEAD))
		return MHD_NO;              /* unexpected method */

	if (&aptr != *con_cls) {
		*con_cls = &aptr;
		return MHD_YES;
	}
	*con_cls = NULL;

	status = get_file_resp(conn, url, &resp);
	switch (status) {
	case MHD_HTTP_OK:
		break;
	case MHD_HTTP_MOVED_PERMANENTLY:
	case MHD_HTTP_FOUND:
		ret = http_redirect(conn, method, url, status,
				    resp.location);
		file_resp_free(&resp);
		return ret;
	default:
		file_resp_free(&resp);
		return http_error(conn, method, url, status, NULL);
	}
	
	response = MHD_create_response_from_fd64(resp.st.st_size, resp.fd);
	if (response) {
		resp.fd = -1;
		if (resp.type)
			MHD_add_response_header(response,
						MHD_HTTP_HEADER_CONTENT_TYPE,
						resp.type);
		ret = MHD_queue_response(conn, MHD_HTTP_OK, response);
		MHD_destroy_response(response);
		http_log(conn, method, url, MHD_HTTP_OK, &resp.st);
	} else
		ret = MHD_NO;
	file_resp_free(&resp);
	
	return ret;
}

static void
fileserv_error_printer (char const *msg)
{
	error("%s", msg);
}

int
main(int argc, char **argv)
{
	int c, i;
	int fd = -1;
	struct MHD_Daemon *mhd;
	struct sockaddr *server_addr;
	int foreground = 0;
	sigset_t sigs;
	static int fatal_signals[] = {
		SIGHUP,
		SIGINT,
		SIGQUIT,
		SIGTERM,
		0
	};

	progname = basename(argv[0]);

	mimetypes_error_printer = fileserv_error_printer;
	tmpdir = getenv("TMP");
	if (!tmpdir)
		tmpdir = "/tmp";
	
	while ((c = getopt(argc, argv, "c:fhv")) != EOF) {
		switch (c) {
		case 'c':
			config_file = optarg;
			break;
		case 'f':
			foreground = 1;
			break;
		case 'h':
			usage();
			exit(0);
		case 'v':
			verbose++;
			break;
		default:
			exit(1);
		}
	}

	readconfig();
	
	pidfile_check();

	if (mime_types_file) {
		mimetypes_parse (mime_types_file); //FIXME: diag
	}
	
	fd = open_listener(address, &server_addr);

	runas(user, group);
	
	for (i = optind; i < argc; i++)
		urimap_add(argv[i]);

	if (TAILQ_EMPTY(&map_head)) {
		error("no mappings");
		exit(1);
	}
	
	if (!foreground) {
		int i;

		if (daemon(0, 1)) {
			error("daemon failed: %s", strerror(errno));
			exit(1);
		}
		for (i = 0; i < fd; i++)
			close(i);
		syslog_enable();
	}
	pidfile_create();
	
	/* Block the 'fatal signals' and SIGPIPE in the handling thread */
	sigemptyset(&sigs);
	for (i = 0; fatal_signals[i]; i++)
		sigaddset(&sigs, fatal_signals[i]);
	sigaddset(&sigs, SIGPIPE);
	
	pthread_sigmask(SIG_BLOCK, &sigs, NULL);
	MHD_set_panic_func(fileserv_panic, NULL);

	mhd = MHD_start_daemon(MHD_USE_INTERNAL_POLLING_THREAD
			       | MHD_USE_ERROR_LOG, 0,
			       fileserv_acl, server_addr, 
			       fileserv_handler, NULL,
			       MHD_OPTION_LISTEN_SOCKET, fd,
			       MHD_OPTION_EXTERNAL_LOGGER, fileserv_logger,
			       NULL,
			       MHD_OPTION_END);
	/* Unblock only the fatal signals */
	sigdelset(&sigs, SIGPIPE);
	pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
	/* Wait for signal to arrive */
	sigwait(&sigs, &c);
	MHD_stop_daemon(mhd);
	pidfile_remove();
	return 0;
}

Return to:

Send suggestions and report system problems to the System administrator.