forked from ryanmjacobs/darkhttpd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
darkhttpd.c
2841 lines (2500 loc) · 85.7 KB
/
darkhttpd.c
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
/* darkhttpd - a simple, single-threaded, static content webserver.
* https://unix4lyfe.org/darkhttpd/
* Copyright (c) 2003-2019 Emil Mikulic <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
static const char
pkgname[] = "darkhttpd/1.12.from.git",
copyright[] = "https://github.com/ryanmjacobs/darkhttpd\n"
"copyright (c) 2003-2019 Emil Mikulic\n"
"2014-2019 Ryan Jacobs (Basic-Auth / .deb)\n";
/* Possible build options: -DDEBUG -DNO_IPV6 */
#ifndef NO_IPV6
# define HAVE_INET6
#endif
#ifndef DEBUG
# define NDEBUG
static const int debug = 0;
#else
static const int debug = 1;
#endif
#ifdef __linux
# define _GNU_SOURCE /* for strsignal() and vasprintf() */
# define _FILE_OFFSET_BITS 64 /* stat() files bigger than 2GB */
# include <sys/sendfile.h>
#endif
#ifdef __sun__
# include <sys/sendfile.h>
#endif
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/param.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <assert.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <limits.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#ifdef __sun__
# ifndef INADDR_NONE
# define INADDR_NONE -1
# endif
#endif
#ifndef MAXNAMLEN
# ifdef NAME_MAX
# define MAXNAMLEN NAME_MAX
# else
# define MAXNAMLEN 255
# endif
#endif
#if defined(O_EXCL) && !defined(O_EXLOCK)
# define O_EXLOCK O_EXCL
#endif
#ifndef __printflike
# ifdef __GNUC__
/* [->] borrowed from FreeBSD's src/sys/sys/cdefs.h,v 1.102.2.2.2.1 */
# define __printflike(fmtarg, firstvararg) \
__attribute__((__format__(__printf__, fmtarg, firstvararg)))
/* [<-] */
# else
# define __printflike(fmtarg, firstvararg)
# endif
#endif
#if defined(__GNUC__) || defined(__INTEL_COMPILER)
# define unused __attribute__((__unused__))
#else
# define unused
#endif
/* [->] borrowed from FreeBSD's src/sys/sys/systm.h,v 1.276.2.7.4.1 */
#ifndef CTASSERT /* Allow lint to override */
# define CTASSERT(x) _CTASSERT(x, __LINE__)
# define _CTASSERT(x, y) __CTASSERT(x, y)
# define __CTASSERT(x, y) typedef char __assert ## y[(x) ? 1 : -1]
#endif
/* [<-] */
CTASSERT(sizeof(unsigned long long) >= sizeof(off_t));
#define llu(x) ((unsigned long long)(x))
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__linux)
# include <err.h>
#else
/* err - prints "error: format: strerror(errno)" to stderr and exit()s with
* the given code.
*/
static void err(const int code, const char *format, ...) __printflike(2, 3);
static void err(const int code, const char *format, ...) {
va_list va;
va_start(va, format);
fprintf(stderr, "error: ");
vfprintf(stderr, format, va);
fprintf(stderr, ": %s\n", strerror(errno));
va_end(va);
exit(code);
}
/* errx - err() without the strerror */
static void errx(const int code, const char *format, ...) __printflike(2, 3);
static void errx(const int code, const char *format, ...) {
va_list va;
va_start(va, format);
fprintf(stderr, "error: ");
vfprintf(stderr, format, va);
fprintf(stderr, "\n");
va_end(va);
exit(code);
}
/* warn - err() without the exit */
static void warn(const char *format, ...) __printflike(1, 2);
static void warn(const char *format, ...) {
va_list va;
va_start(va, format);
fprintf(stderr, "warning: ");
vfprintf(stderr, format, va);
fprintf(stderr, ": %s\n", strerror(errno));
va_end(va);
}
#endif
/* [->] LIST_* macros taken from FreeBSD's src/sys/sys/queue.h,v 1.56
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Under a BSD license.
*/
#define LIST_HEAD(name, type) \
struct name { \
struct type *lh_first; /* first element */ \
}
#define LIST_HEAD_INITIALIZER(head) \
{ NULL }
#define LIST_ENTRY(type) \
struct { \
struct type *le_next; /* next element */ \
struct type **le_prev; /* address of previous next element */ \
}
#define LIST_FIRST(head) ((head)->lh_first)
#define LIST_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = LIST_FIRST((head)); \
(var) && ((tvar) = LIST_NEXT((var), field), 1); \
(var) = (tvar))
#define LIST_INSERT_HEAD(head, elm, field) do { \
if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL) \
LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\
LIST_FIRST((head)) = (elm); \
(elm)->field.le_prev = &LIST_FIRST((head)); \
} while (0)
#define LIST_NEXT(elm, field) ((elm)->field.le_next)
#define LIST_REMOVE(elm, field) do { \
if (LIST_NEXT((elm), field) != NULL) \
LIST_NEXT((elm), field)->field.le_prev = \
(elm)->field.le_prev; \
*(elm)->field.le_prev = LIST_NEXT((elm), field); \
} while (0)
/* [<-] */
static LIST_HEAD(conn_list_head, connection) connlist =
LIST_HEAD_INITIALIZER(conn_list_head);
struct connection {
LIST_ENTRY(connection) entries;
int socket;
#ifdef HAVE_INET6
struct in6_addr client;
#else
in_addr_t client;
#endif
time_t last_active;
enum {
RECV_REQUEST, /* receiving request */
SEND_HEADER, /* sending generated header */
SEND_REPLY, /* sending reply */
DONE /* connection closed, need to remove from queue */
} state;
/* char request[request_length+1] is null-terminated */
char *request;
size_t request_length;
/* request fields */
char *method, *url, *referer, *user_agent, *authorization;
off_t range_begin, range_end;
off_t range_begin_given, range_end_given;
char *header;
size_t header_length, header_sent;
int header_dont_free, header_only, http_code, conn_close;
enum { REPLY_GENERATED, REPLY_FROMFILE } reply_type;
char *reply;
int reply_dont_free;
int reply_fd;
off_t reply_start, reply_length, reply_sent,
total_sent; /* header + body = total, for logging */
};
struct forward_mapping {
const char *host, *target_url; /* These point at argv. */
};
static struct forward_mapping *forward_map = NULL;
static size_t forward_map_size = 0;
static const char *forward_all_url = NULL;
struct mime_mapping {
char *extension, *mimetype;
};
static struct mime_mapping *mime_map = NULL;
static size_t mime_map_size = 0;
static size_t longest_ext = 0;
/* If a connection is idle for timeout_secs or more, it gets closed and
* removed from the connlist.
*/
static int timeout_secs = 30;
static char *keep_alive_field = NULL;
/* Time is cached in the event loop to avoid making an excessive number of
* gettimeofday() calls.
*/
static time_t now;
/* To prevent a malformed request from eating up too much memory, die once the
* request exceeds this many bytes:
*/
#define MAX_REQUEST_LENGTH 4000
/* Defaults can be overridden on the command-line */
static const char *bindaddr;
static uint16_t bindport = 8080; /* or 80 if running as root */
static int max_connections = -1; /* kern.ipc.somaxconn */
static const char *index_name = "index.html";
static int no_listing = 0;
static int sockin = -1; /* socket to accept connections from */
#ifdef HAVE_INET6
static int inet6 = 0; /* whether the socket uses inet6 */
#endif
static char *wwwroot = NULL; /* a path name */
static char *logfile_name = NULL; /* NULL = no logging */
static FILE *logfile = NULL;
static char *pidfile_name = NULL; /* NULL = no pidfile */
static int want_chroot = 0, want_daemon = 0, want_accf = 0,
want_keepalive = 1, want_server_id = 1;
static char *server_hdr = NULL;
static char *auth_key = NULL;
static uint64_t num_requests = 0, total_in = 0, total_out = 0;
static int accepting = 1; /* set to 0 to stop accept()ing */
static volatile int running = 1; /* signal handler sets this to false */
#define INVALID_UID ((uid_t) -1)
#define INVALID_GID ((gid_t) -1)
static uid_t drop_uid = INVALID_UID;
static gid_t drop_gid = INVALID_GID;
/* file with specified extension name will be ignored,directory is not affected. */
#define MAX_EXTENSIONS_NUM 64
static char *ignored_file_exts[MAX_EXTENSIONS_NUM];
/* Default mimetype mappings - make sure this array is NULL terminated. */
static const char *default_extension_map[] = {
"application/ogg" " ogg",
"application/pdf" " pdf",
"application/xml" " xsl xml",
"application/xml-dtd" " dtd",
"application/xslt+xml" " xslt",
"application/zip" " zip",
"audio/mpeg" " mp2 mp3 mpga",
"image/gif" " gif",
"image/jpeg" " jpeg jpe jpg",
"image/png" " png",
"image/webp" " webp",
"text/css" " css",
"text/html" " html htm",
"text/javascript" " js",
"text/plain" " txt asc",
"video/mpeg" " mpeg mpe mpg",
"video/quicktime" " qt mov",
"video/x-msvideo" " avi",
NULL
};
static const char octet_stream[] = "application/octet-stream";
static const char *default_mimetype = octet_stream;
/* Prototypes. */
static void poll_recv_request(struct connection *conn);
static void poll_send_header(struct connection *conn);
static void poll_send_reply(struct connection *conn);
/* close() that dies on error. */
static void xclose(const int fd) {
if (close(fd) == -1)
err(1, "close()");
}
/* malloc that dies if it can't allocate. */
static void *xmalloc(const size_t size) {
void *ptr = malloc(size);
if (ptr == NULL)
errx(1, "can't allocate %zu bytes", size);
return ptr;
}
/* realloc() that dies if it can't reallocate. */
static void *xrealloc(void *original, const size_t size) {
void *ptr = realloc(original, size);
if (ptr == NULL)
errx(1, "can't reallocate %zu bytes", size);
return ptr;
}
/* strdup() that dies if it can't allocate.
* Implement this ourselves since regular strdup() isn't C89.
*/
static char *xstrdup(const char *src) {
size_t len = strlen(src) + 1;
char *dest = xmalloc(len);
memcpy(dest, src, len);
return dest;
}
#ifdef __sun /* unimpressed by Solaris */
static int vasprintf(char **strp, const char *fmt, va_list ap) {
char tmp;
int result = vsnprintf(&tmp, 1, fmt, ap);
*strp = xmalloc(result+1);
result = vsnprintf(*strp, result+1, fmt, ap);
return result;
}
#endif
/* vasprintf() that dies if it fails. */
static unsigned int xvasprintf(char **ret, const char *format, va_list ap)
__printflike(2,0);
static unsigned int xvasprintf(char **ret, const char *format, va_list ap) {
int len = vasprintf(ret, format, ap);
if (ret == NULL || len == -1)
errx(1, "out of memory in vasprintf()");
return (unsigned int)len;
}
/* asprintf() that dies if it fails. */
static unsigned int xasprintf(char **ret, const char *format, ...)
__printflike(2,3);
static unsigned int xasprintf(char **ret, const char *format, ...) {
va_list va;
unsigned int len;
va_start(va, format);
len = xvasprintf(ret, format, va);
va_end(va);
return len;
}
/* Append buffer code. A somewhat efficient string buffer with pool-based
* reallocation.
*/
#ifndef APBUF_INIT
# define APBUF_INIT 4096
#endif
#define APBUF_GROW APBUF_INIT
struct apbuf {
size_t length, pool;
char *str;
};
static struct apbuf *make_apbuf(void) {
struct apbuf *buf = xmalloc(sizeof(struct apbuf));
buf->length = 0;
buf->pool = APBUF_INIT;
buf->str = xmalloc(buf->pool);
return buf;
}
/* Append s (of length len) to buf. */
static void appendl(struct apbuf *buf, const char *s, const size_t len) {
size_t need = buf->length + len;
if (buf->pool < need) {
/* pool has dried up */
while (buf->pool < need)
buf->pool += APBUF_GROW;
buf->str = xrealloc(buf->str, buf->pool);
}
memcpy(buf->str + buf->length, s, len);
buf->length += len;
}
#ifdef __GNUC__
#define append(buf, s) appendl(buf, s, \
(__builtin_constant_p(s) ? sizeof(s)-1 : strlen(s)) )
#else
static void append(struct apbuf *buf, const char *s) {
appendl(buf, s, strlen(s));
}
#endif
static void appendf(struct apbuf *buf, const char *format, ...)
__printflike(2, 3);
static void appendf(struct apbuf *buf, const char *format, ...) {
char *tmp;
va_list va;
size_t len;
va_start(va, format);
len = xvasprintf(&tmp, format, va);
va_end(va);
appendl(buf, tmp, len);
free(tmp);
}
/* Make the specified socket non-blocking. */
static void nonblock_socket(const int sock) {
int flags = fcntl(sock, F_GETFL);
if (flags == -1)
err(1, "fcntl(F_GETFL)");
flags |= O_NONBLOCK;
if (fcntl(sock, F_SETFL, flags) == -1)
err(1, "fcntl() to set O_NONBLOCK");
}
/* Split string out of src with range [left:right-1] */
static char *split_string(const char *src,
const size_t left, const size_t right) {
char *dest;
assert(left <= right);
assert(left < strlen(src)); /* [left means must be smaller */
assert(right <= strlen(src)); /* right) means can be equal or smaller */
dest = xmalloc(right - left + 1);
memcpy(dest, src+left, right-left);
dest[right-left] = '\0';
return dest;
}
/* Resolve /./ and /../ in a URL, in-place. Also strip out query params.
* Returns NULL if the URL is invalid/unsafe, or the original buffer if
* successful.
*/
static char *make_safe_url(char *const url) {
char *src = url, *dst;
#define ends(c) ((c) == '/' || (c) == '\0')
/* URLs not starting with a slash are illegal. */
if (*src != '/')
return NULL;
/* Fast case: skip until first double-slash or dot-dir. */
for ( ; *src && *src != '?'; ++src) {
if (*src == '/') {
if (src[1] == '/')
break;
else if (src[1] == '.') {
if (ends(src[2]))
break;
else if (src[2] == '.' && ends(src[3]))
break;
}
}
}
/* Copy to dst, while collapsing multi-slashes and handling dot-dirs. */
dst = src;
while (*src && *src != '?') {
if (*src != '/')
*dst++ = *src++;
else if (*++src == '/')
;
else if (*src != '.')
*dst++ = '/';
else if (ends(src[1]))
/* Ignore single-dot component. */
++src;
else if (src[1] == '.' && ends(src[2])) {
/* Double-dot component. */
src += 2;
if (dst == url)
return NULL; /* Illegal URL */
else
/* Backtrack to previous slash. */
while (*--dst != '/' && dst > url);
}
else
*dst++ = '/';
}
if (dst == url)
++dst;
*dst = '\0';
return url;
#undef ends
}
static void add_forward_mapping(const char * const host,
const char * const target_url) {
forward_map_size++;
forward_map = xrealloc(forward_map,
sizeof(*forward_map) * forward_map_size);
forward_map[forward_map_size - 1].host = host;
forward_map[forward_map_size - 1].target_url = target_url;
}
/* Associates an extension with a mimetype in the mime_map. Entries are in
* unsorted order. Makes copies of extension and mimetype strings.
*/
static void add_mime_mapping(const char *extension, const char *mimetype) {
size_t i;
assert(strlen(extension) > 0);
assert(strlen(mimetype) > 0);
/* update longest_ext */
i = strlen(extension);
if (i > longest_ext)
longest_ext = i;
/* look through list and replace an existing entry if possible */
for (i = 0; i < mime_map_size; i++)
if (strcmp(mime_map[i].extension, extension) == 0) {
free(mime_map[i].mimetype);
mime_map[i].mimetype = xstrdup(mimetype);
return;
}
/* no replacement - add a new entry */
mime_map_size++;
mime_map = xrealloc(mime_map,
sizeof(struct mime_mapping) * mime_map_size);
mime_map[mime_map_size - 1].extension = xstrdup(extension);
mime_map[mime_map_size - 1].mimetype = xstrdup(mimetype);
}
/* qsort() the mime_map. The map must be sorted before it can be
* binary-searched.
*/
static int mime_mapping_cmp(const void *a, const void *b) {
return strcmp(((const struct mime_mapping *)a)->extension,
((const struct mime_mapping *)b)->extension);
}
static void sort_mime_map(void) {
qsort(mime_map, mime_map_size, sizeof(struct mime_mapping),
mime_mapping_cmp);
}
/* Parses a mime.types line and adds the parsed data to the mime_map. */
static void parse_mimetype_line(const char *line) {
unsigned int pad, bound1, lbound, rbound;
/* parse mimetype */
for (pad=0; (line[pad] == ' ') || (line[pad] == '\t'); pad++)
;
if (line[pad] == '\0' || /* empty line */
line[pad] == '#') /* comment */
return;
for (bound1=pad+1;
(line[bound1] != ' ') &&
(line[bound1] != '\t');
bound1++) {
if (line[bound1] == '\0')
return; /* malformed line */
}
lbound = bound1;
for (;;) {
char *mimetype, *extension;
/* find beginning of extension */
for (; (line[lbound] == ' ') || (line[lbound] == '\t'); lbound++)
;
if (line[lbound] == '\0')
return; /* end of line */
/* find end of extension */
for (rbound = lbound;
line[rbound] != ' ' &&
line[rbound] != '\t' &&
line[rbound] != '\0';
rbound++)
;
mimetype = split_string(line, pad, bound1);
extension = split_string(line, lbound, rbound);
add_mime_mapping(extension, mimetype);
free(mimetype);
free(extension);
if (line[rbound] == '\0')
return; /* end of line */
else
lbound = rbound + 1;
}
}
/* Adds contents of default_extension_map[] to mime_map list. The array must
* be NULL terminated.
*/
static void parse_default_extension_map(void) {
size_t i;
for (i = 0; default_extension_map[i] != NULL; i++)
parse_mimetype_line(default_extension_map[i]);
}
/* read a line from fp, return its contents in a dynamically allocated buffer,
* not including the line ending.
*
* Handles CR, CRLF and LF line endings, as well as NOEOL correctly. If
* already at EOF, returns NULL. Will err() or errx() in case of
* unexpected file error or running out of memory.
*/
static char *read_line(FILE *fp) {
char *buf;
long startpos, endpos;
size_t linelen, numread;
int c;
startpos = ftell(fp);
if (startpos == -1)
err(1, "ftell()");
/* find end of line (or file) */
linelen = 0;
for (;;) {
c = fgetc(fp);
if ((c == EOF) || (c == (int)'\n') || (c == (int)'\r'))
break;
linelen++;
}
/* return NULL on EOF (and empty line) */
if (linelen == 0 && c == EOF)
return NULL;
endpos = ftell(fp);
if (endpos == -1)
err(1, "ftell()");
/* skip CRLF */
if ((c == (int)'\r') && (fgetc(fp) == (int)'\n'))
endpos++;
buf = xmalloc(linelen + 1);
/* rewind file to where the line stared and load the line */
if (fseek(fp, startpos, SEEK_SET) == -1)
err(1, "fseek()");
numread = fread(buf, 1, linelen, fp);
if (numread != linelen)
errx(1, "fread() %zu bytes, expecting %zu bytes", numread, linelen);
/* terminate buffer */
buf[linelen] = 0;
/* advance file pointer over the endline */
if (fseek(fp, endpos, SEEK_SET) == -1)
err(1, "fseek()");
return buf;
}
/* ---------------------------------------------------------------------------
* Adds contents of specified file to mime_map list.
*/
static void parse_extension_map_file(const char *filename) {
char *buf;
FILE *fp = fopen(filename, "rb");
if (fp == NULL)
err(1, "fopen(\"%s\")", filename);
while ((buf = read_line(fp)) != NULL) {
parse_mimetype_line(buf);
free(buf);
}
fclose(fp);
}
/* Uses the mime_map to determine a Content-Type: for a requested URL. This
* bsearch()es mime_map, so make sure it's sorted first.
*/
static int mime_mapping_cmp_str(const void *a, const void *b) {
return strcmp((const char *)a,
((const struct mime_mapping *)b)->extension);
}
static const char *url_content_type(const char *url) {
int period, urllen = (int)strlen(url);
for (period = urllen - 1;
(period > 0) && (url[period] != '.') &&
(urllen - period - 1 <= (int)longest_ext);
period--)
;
if ((period >= 0) && (url[period] == '.')) {
struct mime_mapping *result =
bsearch((url + period + 1), mime_map, mime_map_size,
sizeof(struct mime_mapping), mime_mapping_cmp_str);
if (result != NULL) {
assert(strcmp(url + period + 1, result->extension) == 0);
return result->mimetype;
}
}
/* else no period found in the string */
return default_mimetype;
}
static const char *get_address_text(const void *addr) {
#ifdef HAVE_INET6
if (inet6) {
static char text_addr[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, (const struct in6_addr *)addr, text_addr,
INET6_ADDRSTRLEN);
return text_addr;
} else
#endif
{
return inet_ntoa(*(const struct in_addr *)addr);
}
}
/* Initialize the sockin global. This is the socket that we accept
* connections from.
*/
static void init_sockin(void) {
struct sockaddr_in addrin;
#ifdef HAVE_INET6
struct sockaddr_in6 addrin6;
#endif
socklen_t addrin_len;
int sockopt;
#ifdef HAVE_INET6
if (inet6) {
memset(&addrin6, 0, sizeof(addrin6));
if (inet_pton(AF_INET6, bindaddr ? bindaddr : "::",
&addrin6.sin6_addr) == -1) {
errx(1, "malformed --addr argument");
}
sockin = socket(PF_INET6, SOCK_STREAM, 0);
} else
#endif
{
memset(&addrin, 0, sizeof(addrin));
addrin.sin_addr.s_addr = bindaddr ? inet_addr(bindaddr) : INADDR_ANY;
if (addrin.sin_addr.s_addr == (in_addr_t)INADDR_NONE)
errx(1, "malformed --addr argument");
sockin = socket(PF_INET, SOCK_STREAM, 0);
}
if (sockin == -1)
err(1, "socket()");
/* reuse address */
sockopt = 1;
if (setsockopt(sockin, SOL_SOCKET, SO_REUSEADDR,
&sockopt, sizeof(sockopt)) == -1)
err(1, "setsockopt(SO_REUSEADDR)");
#if 0
/* disable Nagle since we buffer everything ourselves */
sockopt = 1;
if (setsockopt(sockin, IPPROTO_TCP, TCP_NODELAY,
&sockopt, sizeof(sockopt)) == -1)
err(1, "setsockopt(TCP_NODELAY)");
#endif
#ifdef TORTURE
/* torture: cripple the kernel-side send buffer so we can only squeeze out
* one byte at a time (this is for debugging)
*/
sockopt = 1;
if (setsockopt(sockin, SOL_SOCKET, SO_SNDBUF,
&sockopt, sizeof(sockopt)) == -1)
err(1, "setsockopt(SO_SNDBUF)");
#endif
/* bind socket */
#ifdef HAVE_INET6
if (inet6) {
addrin6.sin6_family = AF_INET6;
addrin6.sin6_port = htons(bindport);
if (bind(sockin, (struct sockaddr *)&addrin6,
sizeof(struct sockaddr_in6)) == -1)
err(1, "bind(port %u)", bindport);
addrin_len = sizeof(addrin6);
if (getsockname(sockin, (struct sockaddr *)&addrin6, &addrin_len) == -1)
err(1, "getsockname()");
printf("listening on: http://[%s]:%u/\n",
get_address_text(&addrin6.sin6_addr), bindport);
} else
#endif
{
addrin.sin_family = (u_char)PF_INET;
addrin.sin_port = htons(bindport);
if (bind(sockin, (struct sockaddr *)&addrin,
sizeof(struct sockaddr_in)) == -1)
err(1, "bind(port %u)", bindport);
addrin_len = sizeof(addrin);
if (getsockname(sockin, (struct sockaddr *)&addrin, &addrin_len) == -1)
err(1, "getsockname()");
printf("listening on: http://%s:%u/\n",
get_address_text(&addrin.sin_addr), bindport);
}
/* listen on socket */
if (listen(sockin, max_connections) == -1)
err(1, "listen()");
/* enable acceptfilter (this is only available on FreeBSD) */
if (want_accf) {
#if defined(__FreeBSD__)
struct accept_filter_arg filt = {"httpready", ""};
if (setsockopt(sockin, SOL_SOCKET, SO_ACCEPTFILTER,
&filt, sizeof(filt)) == -1)
fprintf(stderr, "cannot enable acceptfilter: %s\n",
strerror(errno));
else
printf("enabled acceptfilter\n");
#else
printf("this platform doesn't support acceptfilter\n");
#endif
}
}
static void usage(const char *argv0) {
printf("usage:\t%s /path/to/wwwroot [flags]\n\n", argv0);
printf("flags:\t--port number (default: %u, or 80 if running as root)\n"
"\t\tSpecifies which port to listen on for connections.\n"
"\t\tPass 0 to let the system choose any free port for you.\n\n", bindport);
printf("\t--addr ip (default: all)\n"
"\t\tIf multiple interfaces are present, specifies\n"
"\t\twhich one to bind the listening port to.\n\n");
printf("\t--maxconn number (default: system maximum)\n"
"\t\tSpecifies how many concurrent connections to accept.\n\n");
printf("\t--log filename (default: stdout)\n"
"\t\tSpecifies which file to append the request log to.\n\n");
printf("\t--chroot (default: don't chroot)\n"
"\t\tLocks server into wwwroot directory for added security.\n\n");
printf("\t--daemon (default: don't daemonize)\n"
"\t\tDetach from the controlling terminal and run in the background.\n\n");
printf("\t--index filename (default: %s)\n"
"\t\tDefault file to serve when a directory is requested.\n\n",
index_name);
printf("\t--no-listing\n"
"\t\tDo not serve listing if directory is requested.\n\n");
printf("\t--ignored-extensions (optional)\n"
"\t\tfile with specified extension name will not be indexed and showed,\n"
"\t\textension name starts with '.' and is separated by ','.\n\n");
printf("\t--mimetypes filename (optional)\n"
"\t\tParses specified file for extension-MIME associations.\n\n");
printf("\t--default-mimetype string (optional, default: %s)\n"
"\t\tFiles with unknown extensions are served as this mimetype.\n\n",
octet_stream);
printf("\t--uid uid/uname, --gid gid/gname (default: don't privdrop)\n"
"\t\tDrops privileges to given uid:gid after initialization.\n\n");
printf("\t--pidfile filename (default: no pidfile)\n"
"\t\tWrite PID to the specified file. Note that if you are\n"
"\t\tusing --chroot, then the pidfile must be relative to,\n"
"\t\tand inside the wwwroot.\n\n");
printf("\t--no-keepalive\n"
"\t\tDisables HTTP Keep-Alive functionality.\n\n");
#ifdef __FreeBSD__
printf("\t--accf (default: don't use acceptfilter)\n"
"\t\tUse acceptfilter. Needs the accf_http module loaded.\n\n");
#endif
printf("\t--forward host url (default: don't forward)\n"
"\t\tWeb forward (301 redirect).\n"
"\t\tRequests to the host are redirected to the corresponding url.\n"
"\t\tThe option may be specified multiple times, in which case\n"
"\t\tthe host is matched in order of appearance.\n\n");
printf("\t--forward-all url (default: don't forward)\n"
"\t\tWeb forward (301 redirect).\n"
"\t\tAll requests are redirected to the corresponding url.\n\n");
printf("\t--no-server-id\n"
"\t\tDon't identify the server type in headers\n"
"\t\tor directory listings.\n\n");
printf("\t--auth username:password\n"
"\t\tEnable basic authentication.\n\n");
printf("\t--timeout secs (default: %d)\n"
"\t\tIf a connection is idle for more than this many seconds,\n"
"\t\tit will be closed. Set to zero to disable timeouts.\n\n",
timeout_secs);
#ifdef HAVE_INET6
printf("\t--ipv6\n"
"\t\tListen on IPv6 address.\n\n");
#else
printf("\t(This binary was built without IPv6 support: -DNO_IPV6)\n\n");
#endif
}
static char *base64_encode(char *str) {
const char base64_table[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'};
int input_length = strlen(str);
int output_length = 4 * ((input_length + 2) / 3);
char *encoded_data = malloc(output_length+1);
if (encoded_data == NULL) return NULL;
for (int i = 0, j = 0; i < input_length;) {
uint32_t octet_a = i < input_length ? (unsigned char)str[i++] : 0;
uint32_t octet_b = i < input_length ? (unsigned char)str[i++] : 0;
uint32_t octet_c = i < input_length ? (unsigned char)str[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = base64_table[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = base64_table[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = base64_table[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = base64_table[(triple >> 0 * 6) & 0x3F];
}
const int mod_table[] = {0, 2, 1};
for (int i = 0; i < mod_table[input_length % 3]; i++)
encoded_data[output_length - 1 - i] = '=';
encoded_data[output_length] = '\0';
return encoded_data;
}
/* Returns 1 if string is a number, 0 otherwise. Set num to NULL if
* disinterested in value.
*/
static int str_to_num(const char *str, long long *num) {
char *endptr;
long long n;
errno = 0;
n = strtoll(str, &endptr, 10);
if (*endptr != '\0')
return 0;
if (n == LLONG_MIN && errno == ERANGE)