-
Notifications
You must be signed in to change notification settings - Fork 19
/
libhttpd.c
5112 lines (4302 loc) · 126 KB
/
libhttpd.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
/* libhttpd.c - HTTP protocol library
**
** Copyright (C) 1995-2015 Jef Poskanzer <jef@mail.acme.com>
** Copyright (C) 2016-2018 Joachim Nilsson <troglobit@gmail.com>
** 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 OWNERS 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 <config.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#ifdef HAVE_MEMORY_H
#include <memory.h>
#endif
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdint.h> /* int64_t */
#include <inttypes.h> /* PRId64 */
#ifdef HAVE_OSRELDATE_H
#include <osreldate.h>
#endif
#include <wordexp.h>
#ifdef HAVE_DIRENT_H
# include <dirent.h>
# define NAMLEN(dirent) strlen((dirent)->d_name)
#else
# define dirent direct
# define NAMLEN(dirent) (dirent)->d_namlen
# ifdef HAVE_SYS_NDIR_H
# include <sys/ndir.h>
# endif
# ifdef HAVE_SYS_DIR_H
# include <sys/dir.h>
# endif
# ifdef HAVE_NDIR_H
# include <ndir.h>
# endif
#endif
extern char *crypt(const char *key, const char *setting);
#include "base64.h"
#include "file.h"
#include "libhttpd.h"
#include "match.h"
#include "md5.h"
#include "merecat.h"
#include "mmc.h"
#include "ssl.h"
#include "tdate_parse.h"
#include "timers.h"
#ifdef SHOW_SERVER_VERSION
#define EXPOSED_SERVER_SOFTWARE SERVER_SOFTWARE
#else
#define EXPOSED_SERVER_SOFTWARE PACKAGE_NAME
#endif
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
#define STDERR_FILENO 2
#endif
#ifndef SHUT_WR
#define SHUT_WR 1
#endif
#ifdef __CYGWIN__
#define timezone _timezone
#endif
#ifndef MAX
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif
#ifndef MIN
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
#define SETSOCKOPT(sd, level, opt) \
do { \
int val = 1; \
if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \
syslog(LOG_CRIT, "Failed enabling %s: %s", \
#opt, strerror(errno)); \
} while (0)
/* Forwards. */
static void check_options(void);
static void free_httpd_server(struct httpd *hs);
static int initialize_listen_socket(sockaddr_t *sa);
static void add_response(struct http_conn *hc, const char *str);
static void send_mime(struct http_conn *hc, int status, char *title, char *encodings, const char *extraheads, const char *type, off_t length,
time_t mod);
static void send_response(struct http_conn *hc, int status, char *title, const char *extraheads, char *form, char *arg);
static void send_response_tail(struct http_conn *hc);
static void defang(char *str, char *dfstr, int dfsize);
#ifdef ERR_DIR
static int send_err_file(struct http_conn *hc, int status, char *title, const char *extraheads, char *filename);
#endif
#ifdef AUTH_FILE
static void send_authenticate(struct http_conn *hc, char *realm);
static int auth_check(struct http_conn *hc, char *dir);
static int auth_check2(struct http_conn *hc, char *dir);
#endif
#ifdef ACCESS_FILE
static int access_check(struct http_conn *hc, char *dir);
static int access_check2(struct http_conn *hc, char *dir);
#endif
static void send_dirredirect(struct http_conn *hc);
static int hexit(char c);
static void strdecode(char *to, char *from);
#ifdef GENERATE_INDEXES
static void strencode(char *to, int tosize, char *from);
#endif
#ifdef TILDE_MAP_1
static int tilde_map_1(struct http_conn *hc);
#endif
#ifdef TILDE_MAP_2
static int tilde_map_2(struct http_conn *hc);
#endif
static int vhost_map(struct http_conn *hc);
static char *expand_symlinks(char *path, char **trailer, int no_symlink_check, int tildemapped);
static char *bufgets(struct http_conn *hc);
static void de_dotdot(char *file);
static void init_mime(void);
static void figure_mime(struct http_conn *hc);
#ifdef CGI_TIMELIMIT
static void cgi_kill2(arg_t arg, struct timeval *now);
static void cgi_kill(arg_t arg, struct timeval *now);
#endif
#ifdef GENERATE_INDEXES
static int ls(struct http_conn *hc);
#endif
static char *build_env(char *fmt, char *arg);
#ifdef SERVER_NAME_LIST
static char *hostname_map(char *hostname);
#endif
static char **make_envp(struct http_conn *hc);
static char **make_argp(struct http_conn *hc);
static void cgi_interpose_input(struct http_conn *hc, int wfd);
static void post_post_garbage_hack(struct http_conn *hc);
static void cgi_interpose_output(struct http_conn *hc, int rfd);
static void cgi_child(struct http_conn *hc);
static int cgi(struct http_conn *hc);
static void make_log_entry(struct http_conn *hc);
static int check_referer(struct http_conn *hc);
static int really_check_referer(struct http_conn *hc);
static int sockaddr_check(sockaddr_t *sa);
static size_t sockaddr_len(sockaddr_t *sa);
#ifndef HAVE_ATOLL
static long long atoll(const char *str);
#endif
/* This global keeps track of whether we are in the main process or a
** sub-process. The reason is that httpd_send_response() can get called
** in either context; when it is called from the main process it must use
** non-blocking I/O to avoid stalling the server, but when it is called
** from a sub-process it wants to use blocking I/O so that the whole
** response definitely gets written. So, it checks this variable. A bit
** of a hack but it seems to do the right thing.
*/
static int sub_process = 0;
static int set_cloexec(int sd)
{
return fcntl(sd, F_SETFD, FD_CLOEXEC);
}
static int clear_cloexec(int sd)
{
return fcntl(sd, F_SETFD, 0);
}
/* Set no-delay / non-blocking mode on a socket. */
int httpd_set_ndelay(int sd)
{
int flags, newflags;
flags = fcntl(sd, F_GETFL, 0);
if (-1 == flags)
return -1;
newflags = flags | (int)O_NDELAY;
if (newflags != flags)
return fcntl(sd, F_SETFL, newflags);
return 0;
}
/* Clear no-delay / non-blocking mode on a socket. */
int httpd_clear_ndelay(int sd)
{
int flags, newflags;
flags = fcntl(sd, F_GETFL, 0);
if (-1 == flags)
return -1;
newflags = flags & ~(int)O_NDELAY;
if (newflags != flags)
return fcntl(sd, F_SETFL, newflags);
return 0;
}
static void check_options(void)
{
#if defined(TILDE_MAP_1) && defined(TILDE_MAP_2)
syslog(LOG_CRIT, "both TILDE_MAP_1 and TILDE_MAP_2 are defined");
exit(1);
#endif
}
static void free_httpd_server(struct httpd *hs)
{
if (hs->binding_hostname)
free(hs->binding_hostname);
if (hs->cwd)
free(hs->cwd);
if (hs->cgi_pattern)
free(hs->cgi_pattern);
if (hs->cgi_tracker)
free(hs->cgi_tracker);
if (hs->charset)
free(hs->charset);
if (hs->url_pattern)
free(hs->url_pattern);
if (hs->local_pattern)
free(hs->local_pattern);
free(hs);
}
#define ENA(t) t ? "ON" : "OFF"
static void httpd_greeting(struct httpd *hs, sockaddr_t *sav4, sockaddr_t *sav6)
{
char name[202] = { 0 };
char buf[128];
if (hs->binding_hostname) {
sockaddr_t *sa;
if (hs->listen4_fd != -1)
sa = sav4;
else
sa = sav6;
snprintf(name, sizeof(name), "%s, ", httpd_ntoa(sa));
}
/* Port and enabled features in this server */
snprintf(buf, sizeof(buf), "port: %hu, vhost: %s, ssl: %s, php: %s, ssi: %s",
hs->port, ENA(hs->vhost), ENA(hs->ctx), ENA(hs->php_cgi), ENA(hs->ssi_cgi));
syslog(LOG_NOTICE, "%s starting on %s%s", PACKAGE_STRING, name, buf);
}
int httpd_cgi_init(struct httpd *hs, int enabled, char *cgi_pattern, int cgi_limit)
{
char *cp;
if (!hs) {
errno = EINVAL;
return -1;
}
if (!cgi_pattern) {
hs->cgi_enabled = 0;
hs->cgi_pattern = NULL;
hs->cgi_limit = 0;
hs->cgi_count = 0;
return 0;
}
/* Match CGI pattern but never execute */
hs->cgi_enabled = enabled;
/* Nuke any leading slashes. */
if (cgi_pattern[0] == '/')
++cgi_pattern;
hs->cgi_pattern = strdup(cgi_pattern);
if (!hs->cgi_pattern) {
syslog(LOG_CRIT, "Failed initializing CGI: %s", strerror(errno));
return -1;
}
/* Nuke any leading slashes in the cgi pattern. */
while ((cp = strstr(hs->cgi_pattern, "|/")))
/* -2 for the offset, +1 for the '\0' */
memmove(cp + 1, cp + 2, strlen(cp) - 1);
hs->cgi_tracker = calloc(cgi_limit, sizeof(pid_t));
hs->cgi_limit = cgi_limit;
hs->cgi_count = 0;
return 0;
}
/*
** Initialize HTTP redirects
**/
int httpd_redirect_add(struct httpd *hs, int code, char *pattern, char *location)
{
struct http_redir *redirect;
if (!hs || !pattern || !location) {
errno = EINVAL;
return -1;
}
redirect = NEW(struct http_redir, 1);
if (!redirect)
return -1;
redirect->code = code;
redirect->pattern = pattern;
redirect->location = location;
LIST_INSERT(redirect, hs->redirect);
return 0;
}
void httpd_redirect_free(struct httpd *hs)
{
struct http_redir *redirect;
LIST_FOREACH(redirect, hs->redirect)
free(redirect);
}
/*
** Initialize HTTP locations
**/
int httpd_location_add(struct httpd *hs, char *pattern, char *path)
{
struct http_location *loc;
if (!hs || !pattern || !path) {
errno = EINVAL;
return -1;
}
loc = NEW(struct http_location, 1);
if (!loc)
return -1;
loc->pattern = pattern;
loc->path = path;
LIST_INSERT(loc, hs->location);
return 0;
}
void httpd_location_free(struct httpd *hs)
{
struct http_location *loc;
LIST_FOREACH(loc, hs->location)
free(loc);
}
/* Initialize listen sockets. Try v6 first because of a Linux peculiarity;
** like some other systems, it has magical v6 sockets that also listen for
** v4, but in Linux if you bind a v4 socket first then the v6 bind fails.
*/
int httpd_listen(struct httpd *hs, sockaddr_t *sav4, sockaddr_t *sav6)
{
if (!sav6)
hs->listen6_fd = -1;
else
hs->listen6_fd = initialize_listen_socket(sav6);
if (!sav4)
hs->listen4_fd = -1;
else
hs->listen4_fd = initialize_listen_socket(sav4);
/* If we didn't get any valid sockets, fail. */
if (hs->listen4_fd == -1 && hs->listen6_fd == -1)
return -1;
httpd_greeting(hs, sav4, sav6);
return 0;
}
struct httpd *httpd_init(char *hostname, unsigned short port, void *ssl_ctx, char *charset,
int max_age, char *cwd, int no_log, int no_symlink_check,
int vhost, int global_passwd, char *url_pattern,
char *local_pattern, int no_empty_referers, int list_dotfiles)
{
struct httpd *hs;
static char ghnbuf[256];
check_options();
hs = NEW(struct httpd, 1);
if (!hs) {
syslog(LOG_CRIT, "out of memory allocating struct httpd");
return NULL;
}
if (hostname) {
hs->binding_hostname = strdup(hostname);
if (!hs->binding_hostname) {
syslog(LOG_CRIT, "out of memory copying hostname");
free_httpd_server(hs);
return NULL;
}
hs->server_hostname = hs->binding_hostname;
} else {
hs->binding_hostname = NULL;
hs->server_hostname = NULL;
if (gethostname(ghnbuf, sizeof(ghnbuf)) < 0)
ghnbuf[0] = '\0';
#ifdef SERVER_NAME_LIST
if (ghnbuf[0] != '\0')
hs->server_hostname = hostname_map(ghnbuf);
#endif
if (!hs->server_hostname) {
#ifdef SERVER_NAME
hs->server_hostname = SERVER_NAME;
#else
if (ghnbuf[0] != '\0')
hs->server_hostname = ghnbuf;
#endif
}
}
hs->port = port;
hs->ctx = ssl_ctx;
hs->charset = strdup(charset);
hs->max_age = max_age;
hs->cwd = strdup(cwd);
if (!hs->cwd) {
syslog(LOG_CRIT, "out of memory copying cwd");
free_httpd_server(hs);
return NULL;
}
if (!url_pattern) {
hs->url_pattern = NULL;
} else {
hs->url_pattern = strdup(url_pattern);
if (!hs->url_pattern) {
syslog(LOG_CRIT, "out of memory copying url_pattern");
free_httpd_server(hs);
return NULL;
}
}
if (!local_pattern) {
hs->local_pattern = NULL;
} else {
hs->local_pattern = strdup(local_pattern);
if (!hs->local_pattern) {
syslog(LOG_CRIT, "out of memory copying local_pattern");
free_httpd_server(hs);
return NULL;
}
}
hs->no_log = no_log;
hs->no_symlink_check = no_symlink_check;
hs->vhost = vhost;
hs->global_passwd = global_passwd;
hs->no_empty_referers = no_empty_referers;
hs->list_dotfiles = list_dotfiles;
hs->php_cgi = php_cgi;
hs->php_pattern = php_pattern;
hs->ssi_cgi = ssi_cgi;
hs->ssi_pattern = ssi_pattern;
init_mime();
hs->listen4_fd = -1;
hs->listen6_fd = -1;
return hs;
}
static int initialize_listen_socket(sockaddr_t *sa)
{
int listen_fd;
int flags;
/* Check sockaddr. */
if (!sockaddr_check(sa)) {
syslog(LOG_CRIT, "unknown sockaddr family on listen socket");
return -1;
}
/* Create socket. */
listen_fd = socket(sa->sa.sa_family, SOCK_STREAM, 0);
if (listen_fd < 0) {
syslog(LOG_CRIT, "Failed opening socket for %s: %s", httpd_ntoa(sa), strerror(errno));
return -1;
}
if (-1 == set_cloexec(listen_fd))
syslog(LOG_ERR, "failed setting CLOEXEC on listen socket: %s",
strerror(errno));
/* Allow reuse of local addresses. */
SETSOCKOPT(listen_fd, SOL_SOCKET, SO_REUSEADDR);
#ifdef SO_REUSEPORT
SETSOCKOPT(listen_fd, SOL_SOCKET, SO_REUSEPORT);
#endif
/* Bind to it. */
if (bind(listen_fd, &sa->sa, sockaddr_len(sa)) < 0) {
syslog(LOG_CRIT, "Failed binding to %s port %d: %s", httpd_ntoa(sa), httpd_port(sa), strerror(errno));
(void)close(listen_fd);
return -1;
}
/* Set the listen file descriptor to no-delay / non-blocking mode. */
if (-1 == httpd_set_ndelay(listen_fd)) {
syslog(LOG_ERR, "failed setting listen socket non-blocking: %s",
strerror(errno));
(void)close(listen_fd);
return -1;
}
/* Start a listen going. */
if (listen(listen_fd, LISTEN_BACKLOG) < 0) {
syslog(LOG_CRIT, "listen: %s", strerror(errno));
(void)close(listen_fd);
return -1;
}
/* Use accept filtering, if available. */
#ifdef SO_ACCEPTFILTER
{
#if (__FreeBSD_version >= 411000)
#define ACCEPT_FILTER_NAME "httpready"
#else
#define ACCEPT_FILTER_NAME "dataready"
#endif
struct accept_filter_arg af;
memset(&af, 0, sizeof(af));
strcpy(af.af_name, ACCEPT_FILTER_NAME);
setsockopt(listen_fd, SOL_SOCKET, SO_ACCEPTFILTER, &af, sizeof(af));
}
#endif /* SO_ACCEPTFILTER */
return listen_fd;
}
void httpd_exit(struct httpd *hs)
{
httpd_ssl_exit(hs);
httpd_unlisten(hs);
httpd_redirect_free(hs);
httpd_location_free(hs);
free_httpd_server(hs);
}
void httpd_unlisten(struct httpd *hs)
{
if (hs->listen4_fd != -1) {
(void)close(hs->listen4_fd);
hs->listen4_fd = -1;
}
if (hs->listen6_fd != -1) {
(void)close(hs->listen6_fd);
hs->listen6_fd = -1;
}
}
/* Conditional macro to allow two alternate forms for use in the built-in
** error pages. If EXPLICIT_ERROR_PAGES is defined, the second and more
** explicit error form is used; otherwise, the first and more generic
** form is used.
*/
#ifdef EXPLICIT_ERROR_PAGES
#define ERROR_FORM(a,b) b
#else
#define ERROR_FORM(a,b) a
#endif
static char *ok200title = "OK";
static char *ok206title = "Partial Content";
static char *err301title = "Moved Permanently";
static char *err301form = "The actual URL is '%s'.\n";
static char *err302title = "Found";
static char *err302form = "The actual URL is '%s'.\n";
static char *err303title = "See Other";
static char *err303form = "The actual URL is '%s'.\n";
static char *err304title = "Not Modified";
static char *err307title = "Temporary Redirect";
static char *err307form = "The actual URL is '%s'.\n";
char *httpd_err400title = "Bad Request";
char *httpd_err400form = "Your request has bad syntax(%s) or is inherently impossible to satisfy.\n";
#ifdef AUTH_FILE
static char *err401title = "Unauthorized";
static char *err401form = "Authorization required for the URL '%s'.\n";
#endif
static char *err403title = "Forbidden";
#ifndef EXPLICIT_ERROR_PAGES
static char *err403form = "You do not have permission to get URL '%s' from this server.\n";
#endif
static char *err404title = "Not Found";
static char *err404form = "The requested URL '%s' was not found on this server.\n";
char *httpd_err408title = "Request Timeout";
char *httpd_err408form = "No request appeared within a reasonable time period.\n";
static char *err500title = "Internal Error";
static char *err500form = "There was an unusual problem serving the requested URL '%s'.\n";
static char *err501title = "Not Implemented";
static char *err501form = "The requested method '%s' is not implemented by this server.\n";
char *httpd_err503title = "Service Temporarily Overloaded";
char *httpd_err503form = "The requested URL '%s' is temporarily overloaded. Please try again later.\n";
/* Append a string to the buffer waiting to be sent as response. */
static void add_response(struct http_conn *hc, const char *str)
{
size_t len;
len = strlen(str);
httpd_realloc_str(&hc->response, &hc->maxresponse, hc->responselen + len);
memmove(&(hc->response[hc->responselen]), str, len + 1);
hc->responselen += len;
}
/* Send the buffered response. */
void httpd_send_response(struct http_conn *hc)
{
/* If we are in a sub-process, turn off no-delay mode. */
if (sub_process)
(void)httpd_clear_ndelay(hc->conn_fd);
/* Send the response, if necessary. */
if (hc->responselen > 0) {
make_log_entry(hc);
httpd_write(hc, hc->response, hc->responselen);
hc->responselen = 0;
}
}
static int content_encoding(struct http_conn *hc, char *encodings, char *buf, size_t len)
{
char *skip[] = { /* Sorted in order of most likely */
"x-tar",
"octet-stream",
};
size_t i;
int hasenc = 0;
int addgz = 0;
int ret = 0;
int gz;
/* Skip Content-Encoding for Content-Type intended for download */
for (i = 0; i < NELEMS(skip); i++) {
if (strstr(hc->type, skip[i]))
return 0;
}
gz = hc->compression_type == COMPRESSION_GZIP;
if (encodings && encodings[0]) {
hasenc = 1;
addgz = gz && !strstr(encodings, "gzip");
}
if (hasenc)
ret = snprintf(buf, len, "Content-Encoding: %s%s\r\n", encodings, addgz ? ", gzip" : "");
else if (gz)
ret = snprintf(buf, len, "Content-Encoding: gzip\r\n");
return ret;
}
static void
send_mime(struct http_conn *hc, int status, char *title, char *encodings,
const char *extraheads, const char *type, off_t length, time_t mod)
{
time_t now;
const char *rfc1123fmt = "%a, %d %b %Y %H:%M:%S GMT";
char fixed_type[500];
char buf[1000];
int partial_content;
int s100;
if (status != 200)
hc->compression_type = COMPRESSION_NONE;
hc->status = status;
hc->bytes_to_send = length;
if (hc->mime_flag) {
char nowbuf[100];
char modbuf[100];
char etagbuf[45] = { 0 };
if (status == 200 && hc->got_range &&
(hc->last_byte_index >= hc->first_byte_index) &&
((hc->last_byte_index != length - 1) || (hc->first_byte_index != 0)) &&
(hc->range_if == (time_t)-1 || hc->range_if == hc->sb.st_mtime)) {
partial_content = 1;
hc->status = status = 206;
title = ok206title;
hc->compression_type = COMPRESSION_NONE; /* probably some way to get around this... */
} else {
partial_content = 0;
hc->got_range = 0;
}
now = time(NULL);
if (!mod)
mod = now;
strftime(nowbuf, sizeof(nowbuf), rfc1123fmt, gmtime(&now));
strftime(modbuf, sizeof(modbuf), rfc1123fmt, gmtime(&mod));
snprintf(fixed_type, sizeof(fixed_type), type, hc->hs->charset);
/* Match Apache as close as possible, but follow RFC 2616, section 4.2 */
snprintf(buf, sizeof(buf),
"%.20s %d %s\r\n"
"Date: %s\r\n"
"Server: %s\r\n"
"Last-Modified: %s\r\n"
"Accept-Ranges: bytes\r\n",
hc->protocol, status, title, nowbuf, EXPOSED_SERVER_SOFTWARE, modbuf);
add_response(hc, buf);
/* HTTP Strict Transport Security: https://www.chromium.org/hsts */
if (hc->ssl) {
snprintf(buf, sizeof(buf), "Strict-Transport-Security: "
"max-age=31536000; includeSubDomains; "
"preload\r\n");
add_response(hc, buf);
}
if (partial_content) {
snprintf(buf, sizeof(buf),
"Content-Range: bytes %" PRId64 "-%" PRId64 "/%" PRId64 "\r\n"
"Content-Length: %" PRId64 "\r\n",
(int64_t)hc->first_byte_index, (int64_t)hc->last_byte_index,
(int64_t)length, (int64_t)(hc->last_byte_index - hc->first_byte_index + 1));
add_response(hc, buf);
} else if (length >= 0) {
/*
* Avoid sending Content-Length on content we
* deflate or have .gz files of already. In the
* former case we don't know the length yet.
*/
if (hc->compression_type == COMPRESSION_NONE) {
snprintf(buf, sizeof(buf), "Content-Length: %" PRId64 "\r\n", (int64_t)length);
add_response(hc, buf);
}
} else {
// Experimental: Allow keep-alive also for dir listings etc.
// hc->do_keep_alive = 0;
}
snprintf(buf, sizeof(buf), "Content-Type: %s\r\n", fixed_type);
add_response(hc, buf);
if (strstr(fixed_type, "application/pdf")) {
char *ptr = strrchr(hc->expnfilename, '/');
if (ptr)
ptr++;
else
ptr = hc->expnfilename;
snprintf(buf, sizeof(buf), "Content-Disposition: inline; filename=%s\r\n", ptr);
add_response(hc, buf);
}
if (content_encoding(hc, encodings, buf, sizeof(buf)))
add_response(hc, buf);
s100 = status / 100;
if (s100 != 2 && s100 != 3) {
snprintf(buf, sizeof(buf), "Cache-Control: no-cache,no-store\r\n");
add_response(hc, buf);
}
/* EntityTag -- https://en.wikipedia.org/wiki/HTTP_ETag */
if (hc->file_address) {
uint8_t dig[MD5_DIGEST_LENGTH];
MD5_CTX ctx;
MD5Init(&ctx);
MD5Update(&ctx, (const u_int8_t *)hc->file_address, length);
MD5Final(dig, &ctx);
snprintf(etagbuf, sizeof(etagbuf),
"ETag: \"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\"\r\n",
dig[0], dig[1], dig[2], dig[3], dig[4], dig[5], dig[6], dig[7],
dig[8], dig[9], dig[10], dig[11], dig[12], dig[13], dig[14], dig[15]);
}
if (hc->hs->max_age >= 0) {
if (hc->hs->max_age == 0)
snprintf(buf, sizeof(buf), "Cache-Control: no-cache,no-stored\r\n");
else
snprintf(buf, sizeof(buf), "Cache-Control: max-age=%d\r\n%s", hc->hs->max_age, etagbuf);
add_response(hc, buf);
/* Expires was superseded by Cache-Control in HTTP/1.1 */
#ifdef USE_SUPERSEDED_EXPIRES
char expbuf[100];
time_t expires;
/* NOTE: This header requires that the web server's clock is
** properly set, which is very unlikely for many small
** or embedded systems.
*/
expires = now + hc->hs->max_age;
strftime(expbuf, sizeof(expbuf), rfc1123fmt, gmtime(&expires));
snprintf(buf, sizeof(buf), "Expires: %s\r\n", expbuf);
add_response(hc, buf);
#endif
}
if (hc->do_keep_alive)
snprintf(buf, sizeof(buf), "Connection: keep-alive\r\n");
else
snprintf(buf, sizeof(buf), "Connection: close\r\n");
add_response(hc, buf);
if (extraheads[0] != '\0')
add_response(hc, extraheads);
add_response(hc, "\r\n");
}
}
static int str_alloc_count = 0;
static size_t str_alloc_size = 0;
void httpd_realloc_str(char **str, size_t *curr_len, size_t new_len)
{
if (*curr_len == 0) {
*curr_len = MAX(200, new_len + 100);
*str = NEW(char, *curr_len + 1);
++str_alloc_count;
str_alloc_size += *curr_len;
} else if (new_len > *curr_len) {
str_alloc_size -= *curr_len;
*curr_len = MAX(*curr_len * 2, new_len * 5 / 4);
*str = RENEW(*str, char, *curr_len + 1);
str_alloc_size += *curr_len;
} else {
return;
}
if (!*str) {
syslog(LOG_ERR, "out of memory reallocating a string to %zu bytes", *curr_len);
exit(1);
}
}
static void send_response(struct http_conn *hc, int status, char *title, const char *extraheads, char *form, char *arg)
{
char defanged_arg[1000], buf[2000];
send_mime(hc, status, title, "", extraheads, "text/html; charset=%s", (off_t) - 1, (time_t)0);
snprintf(buf, sizeof(buf), "<!DOCTYPE html>\n"
"<html>\n"
" <head>\n"
" <title>%d %s</title>\n"
" <link rel=\"icon\" type=\"image/x-icon\" href=\"/icons/favicon.ico\">\n"
"%s"
" </head>\n"
" <body>\n"
"<div id=\"wrapper\" tabindex=\"-1\">\n"
"<h2>%d %s</h2>\n"
"<p>\n",
status, title,
httpd_css_default(),
status, title);
add_response(hc, buf);
defang(arg, defanged_arg, sizeof(defanged_arg));
snprintf(buf, sizeof(buf), form, defanged_arg);
add_response(hc, buf);
#ifdef MSIE_PADDING
if (match("**MSIE**", hc->useragent)) {
int n;
add_response(hc, "<!--\n");
for (n = 0; n < 6; ++n)
add_response(hc, "Padding so that MSIE deigns to show this error instead of its own canned one.\n");
add_response(hc, "-->\n");
}
#endif
add_response(hc, "</p>");
send_response_tail(hc);
}
static char *get_hostname(struct http_conn *hc)
{
char *host;
static char *fallback = "";
if (hc->hs->vhost && hc->hostname)
host = hc->hostname;
else
host = hc->hs->server_hostname;
if (!host)
host = fallback;
return host;
}
static void send_response_tail(struct http_conn *hc)
{
char buf[1000];
snprintf(buf, sizeof(buf),
" <address>%s httpd at %s port %d</address>\n"
"</div>\n"
"</body>\n"
"</html>\n", EXPOSED_SERVER_SOFTWARE, get_hostname(hc), (int)hc->hs->port);
add_response(hc, buf);
}
static void defang(char *str, char *dfstr, int dfsize)
{
char *cp1;