-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.c
1671 lines (1381 loc) · 35.5 KB
/
server.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
/*
* Copyright (c) 2021, 2022, 2023 Omar Polo <op@omarpolo.com>
*
* 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.
*/
#include "gmid.h"
#include <sys/stat.h>
#include <sys/un.h>
#include <ctype.h>
#include <errno.h>
#include <event.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <limits.h>
#include <string.h>
#include "log.h"
#include "proc.h"
#define MINIMUM(a, b) ((a) < (b) ? (a) : (b))
#ifndef nitems
#define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
#endif
#ifdef SIGINFO
static struct event siginfo;
#endif
static struct event sigusr2;
int connected_clients;
/*
* This function is not publicy exported because it is a hack until libtls
* has a proper privsep setup.
*/
void tls_config_use_fake_private_key(struct tls_config *);
static inline int matches(const char*, const char*);
static void handle_handshake(int, short, void*);
static void fmtbuf(char *, size_t, const char *, struct client *,
const char *);
static int apply_block_return(struct client*);
static int check_matching_certificate(X509_STORE *, struct client *);
static int apply_reverse_proxy(struct client *);
static int apply_fastcgi(struct client*);
static int apply_require_ca(struct client*);
static void open_dir(struct client*);
static void redirect_canonical_dir(struct client*);
static void client_tls_readcb(int, short, void *);
static void client_tls_writecb(int, short, void *);
static void client_read(struct bufferevent *, void *);
void client_write(struct bufferevent *, void *);
static void client_error(struct bufferevent *, short, void *);
static void client_close_ev(int, short, void *);
static void handle_siginfo(int, short, void*);
static int server_dispatch_parent(int, struct privsep_proc *, struct imsg *);
static int server_dispatch_crypto(int, struct privsep_proc *, struct imsg *);
static int server_dispatch_logger(int, struct privsep_proc *, struct imsg *);
static ssize_t read_cb(struct tls *, void *, size_t, void *);
static ssize_t write_cb(struct tls *, const void *, size_t, void *);
static struct privsep_proc procs[] = {
{ "parent", PROC_PARENT, server_dispatch_parent },
{ "crypto", PROC_CRYPTO, server_dispatch_crypto },
{ "logger", PROC_LOGGER, server_dispatch_logger },
};
static uint32_t server_client_id;
struct client_tree_id clients;
static inline int
match_addr(struct address *target, struct address *source)
{
return (target->ai_flags == source->ai_flags &&
target->ai_family == source->ai_family &&
target->ai_socktype == source->ai_socktype &&
target->ai_protocol == source->ai_protocol &&
target->slen == source->slen &&
!memcmp(&target->ss, &source->ss, target->slen));
}
static inline int
matches(const char *pattern, const char *path)
{
if (*path == '/')
path++;
return !fnmatch(pattern, path, 0);
}
static inline int
match_host(struct vhost *v, struct client *c)
{
struct alist *a;
if (matches(v->domain, c->domain))
return 1;
TAILQ_FOREACH(a, &v->aliases, aliases)
if (matches(a->alias, c->domain))
return 1;
return 0;
}
const char *
vhost_lang(struct vhost *v, const char *path)
{
struct location *loc;
if (v == NULL || path == NULL)
return NULL;
loc = TAILQ_FIRST(&v->locations);
while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
if (*loc->lang != '\0') {
if (matches(loc->match, path))
return loc->lang;
}
}
loc = TAILQ_FIRST(&v->locations);
if (*loc->lang == '\0')
return NULL;
return loc->lang;
}
const char *
vhost_default_mime(struct vhost *v, const char *path)
{
struct location *loc;
const char *default_mime = "application/octet-stream";
if (v == NULL || path == NULL)
return default_mime;
loc = TAILQ_FIRST(&v->locations);
while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
if (*loc->default_mime != '\0') {
if (matches(loc->match, path))
return loc->default_mime;
}
}
loc = TAILQ_FIRST(&v->locations);
if (*loc->default_mime != '\0')
return loc->default_mime;
return default_mime;
}
const char *
vhost_index(struct vhost *v, const char *path)
{
struct location *loc;
const char *index = "index.gmi";
if (v == NULL || path == NULL)
return index;
loc = TAILQ_FIRST(&v->locations);
while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
if (*loc->index != '\0') {
if (matches(loc->match, path))
return loc->index;
}
}
loc = TAILQ_FIRST(&v->locations);
if (*loc->index != '\0')
return loc->index;
return index;
}
int
vhost_auto_index(struct vhost *v, const char *path)
{
struct location *loc;
if (v == NULL || path == NULL)
return 0;
loc = TAILQ_FIRST(&v->locations);
while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
if (loc->auto_index != 0) {
if (matches(loc->match, path))
return loc->auto_index == 1;
}
}
loc = TAILQ_FIRST(&v->locations);
return loc->auto_index == 1;
}
int
vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
{
struct location *loc;
if (v == NULL || path == NULL)
return 0;
loc = TAILQ_FIRST(&v->locations);
while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
if (loc->block_code != 0) {
if (matches(loc->match, path)) {
*code = loc->block_code;
*fmt = loc->block_fmt;
return 1;
}
}
}
loc = TAILQ_FIRST(&v->locations);
*code = loc->block_code;
*fmt = loc->block_fmt;
return loc->block_code != 0;
}
struct location *
vhost_fastcgi(struct vhost *v, const char *path)
{
struct location *loc;
if (v == NULL || path == NULL)
return NULL;
loc = TAILQ_FIRST(&v->locations);
while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
if (loc->fcgi != -1)
if (matches(loc->match, path))
return loc;
if (loc->nofcgi && matches(loc->match, path))
return NULL;
}
loc = TAILQ_FIRST(&v->locations);
return loc->fcgi == -1 ? NULL : loc;
}
int
vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
{
struct location *loc;
size_t l = 0;
if (v == NULL || path == NULL)
return -1;
loc = TAILQ_FIRST(&v->locations);
while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
l++;
if (loc->dirfd != -1)
if (matches(loc->match, path)) {
*retloc = l;
return loc->dirfd;
}
}
*retloc = 0;
loc = TAILQ_FIRST(&v->locations);
return loc->dirfd;
}
int
vhost_strip(struct vhost *v, const char *path)
{
struct location *loc;
if (v == NULL || path == NULL)
return 0;
loc = TAILQ_FIRST(&v->locations);
while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
if (loc->strip != 0) {
if (matches(loc->match, path))
return loc->strip;
}
}
loc = TAILQ_FIRST(&v->locations);
return loc->strip;
}
X509_STORE *
vhost_require_ca(struct vhost *v, const char *path)
{
struct location *loc;
if (v == NULL || path == NULL)
return NULL;
loc = TAILQ_FIRST(&v->locations);
while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
if (loc->reqca != NULL) {
if (matches(loc->match, path))
return loc->reqca;
}
}
loc = TAILQ_FIRST(&v->locations);
return loc->reqca;
}
int
vhost_disable_log(struct vhost *v, const char *path)
{
struct location *loc;
if (v == NULL || path == NULL)
return 0;
loc = TAILQ_FIRST(&v->locations);
while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
if (loc->disable_log && matches(loc->match, path))
return 1;
}
loc = TAILQ_FIRST(&v->locations);
return loc->disable_log;
}
void
mark_nonblock(int fd)
{
int flags;
if ((flags = fcntl(fd, F_GETFL)) == -1)
fatal("fcntl(F_GETFL)");
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
fatal("fcntl(F_SETFL)");
}
static void
handle_handshake(int fd, short ev, void *d)
{
struct client *c = d;
struct conf *conf = c->conf;
struct vhost *h;
const char *servname;
const char *parse_err = "unknown error";
switch (tls_handshake(c->ctx)) {
case 0: /* success */
break;
case -1:
log_warnx("(%s:%s) tls_handshake failed: %s",
c->rhost, c->rserv, tls_error(c->ctx));
client_close(c);
return;
case TLS_WANT_POLLIN:
event_once(c->fd, EV_READ, handle_handshake, c, NULL);
return;
case TLS_WANT_POLLOUT:
event_once(c->fd, EV_WRITE, handle_handshake, c, NULL);
return;
default:
/* unreachable */
fatalx("unexpected return value from tls_handshake");
}
c->bev = bufferevent_new(fd, client_read, client_write,
client_error, c);
if (c->bev == NULL)
fatal("%s: failed to allocate client buffer", __func__);
event_set(&c->bev->ev_read, c->fd, EV_READ,
client_tls_readcb, c->bev);
event_set(&c->bev->ev_write, c->fd, EV_WRITE,
client_tls_writecb, c->bev);
#if HAVE_LIBEVENT2
evbuffer_unfreeze(c->bev->input, 0);
evbuffer_unfreeze(c->bev->output, 1);
#endif
if ((servname = tls_conn_servername(c->ctx)) == NULL)
log_debug("handshake: missing SNI");
if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
log_info("puny_decode: %s", parse_err);
start_reply(c, BAD_REQUEST, "Wrong/malformed host");
return;
}
if (*c->domain == '\0') {
if (strlcpy(c->domain, c->addr->pp, sizeof(c->domain))
>= sizeof(c->domain)) {
log_warnx("%s: domain too long: %s", __func__,
c->addr->pp);
*c->domain = '\0';
}
}
TAILQ_FOREACH(h, &conf->hosts, vhosts)
if (match_host(h, c))
break;
log_debug("handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
servname != NULL ? servname : "(null)",
c->domain,
h != NULL ? h->domain : "(null)");
if (h != NULL) {
c->host = h;
bufferevent_enable(c->bev, EV_READ);
return;
}
start_reply(c, BAD_REQUEST, "Wrong/malformed host");
}
static void
fmtbuf(char *buf, size_t buflen, const char *fmt, struct client *c,
const char *path)
{
size_t i;
char tmp[32];
*buf = '\0';
memset(tmp, 0, sizeof(tmp));
for (i = 0; *fmt; ++fmt) {
if (i == sizeof(tmp)-1 || *fmt == '%') {
strlcat(buf, tmp, buflen);
memset(tmp, 0, sizeof(tmp));
i = 0;
}
if (*fmt != '%') {
tmp[i++] = *fmt;
continue;
}
switch (*++fmt) {
case '%':
strlcat(buf, "%", buflen);
break;
case 'p':
if (*path != '/')
strlcat(buf, "/", buflen);
strlcat(buf, path, buflen);
break;
case 'q':
strlcat(buf, c->iri.query, buflen);
break;
case 'P':
snprintf(tmp, sizeof(tmp), "%d", c->addr->port);
strlcat(buf, tmp, buflen);
memset(tmp, 0, sizeof(tmp));
break;
case 'N':
strlcat(buf, c->domain, buflen);
break;
default:
log_warnx("%s: unknown fmt specifier %c",
__func__, *fmt);
}
}
if (i != 0)
strlcat(buf, tmp, buflen);
}
/* 1 if a matching `block return' (and apply it), 0 otherwise */
static int
apply_block_return(struct client *c)
{
char buf[GEMINI_URL_LEN];
const char *fmt, *path;
int code;
if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
return 0;
path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
fmtbuf(buf, sizeof(buf), fmt, c, path);
start_reply(c, code, buf);
return 1;
}
static struct proxy *
matched_proxy(struct client *c)
{
struct proxy *p;
const char *proto;
const char *host;
const char *port;
TAILQ_FOREACH(p, &c->host->proxies, proxies) {
if (*(proto = p->match_proto) == '\0')
proto = "gemini";
if (*(host = p->match_host) == '\0')
host = "*";
if (*(port = p->match_port) == '\0')
port = "*";
if (matches(proto, c->iri.schema) &&
matches(host, c->domain) &&
matches(port, c->iri.port))
return p;
}
return NULL;
}
static int
check_matching_certificate(X509_STORE *store, struct client *c)
{
const uint8_t *cert;
size_t len;
if (!tls_peer_cert_provided(c->ctx)) {
start_reply(c, CLIENT_CERT_REQ, "client certificate required");
return 1;
}
cert = tls_peer_cert_chain_pem(c->ctx, &len);
if (!validate_against_ca(store, cert, len)) {
start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
return 1;
}
return 0;
}
static int
proxy_socket(struct client *c, struct proxy *p)
{
struct addrinfo hints, *res, *res0;
int r, sock, save_errno;
const char *cause = NULL;
char to[NI_MAXHOST], to_port[NI_MAXSERV];
int err;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
/* XXX: asr_run? :> */
r = getaddrinfo(p->host, p->port, &hints, &res0);
if (r != 0) {
log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
p->host, p->port, gai_strerror(r));
return -1;
}
for (res = res0; res; res = res->ai_next) {
sock = socket(res->ai_family, res->ai_socktype,
res->ai_protocol);
if (sock == -1) {
cause = "socket";
continue;
}
if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
cause = "connect";
save_errno = errno;
close(sock);
errno = save_errno;
sock = -1;
continue;
}
break;
}
if (sock == -1)
log_warn("can't connect to %s:%s: %s", p->host, p->port, cause);
if (res && sock != -1 && p->proxy) {
err = getnameinfo(res->ai_addr, res->ai_addrlen,
to, sizeof(to), to_port, sizeof(to_port),
NI_NUMERICHOST|NI_NUMERICSERV);
if (err != 0) {
log_warnx("%s: getnameinfo failed: %s", __func__,
gai_strerror(err));
strlcpy(to, c->rhost, sizeof(to));
strlcpy(to_port, c->rserv, sizeof(to_port));
}
r = snprintf(c->buf.data, sizeof(c->buf.data),
"PROXY TCP%c %s %s %s %s\r\n",
c->addr->ai_family == AF_INET ? '4' : '6',
c->rhost, to, c->rserv, to_port);
if (r < 0 || (size_t)r >= sizeof(c->buf.data)) {
log_warnx("failed serialize info for the proxy protocol");
c->buf.data[0] = '\0';
} else
c->buf.len = r;
}
freeaddrinfo(res0);
return sock;
}
/* 1 if matching a proxy relay-to (and apply it), 0 otherwise */
static int
apply_reverse_proxy(struct client *c)
{
struct proxy *p;
if ((p = matched_proxy(c)) == NULL)
return 0;
c->proxy = p;
if (p->reqca != NULL && check_matching_certificate(p->reqca, c))
return 1;
log_debug("opening proxy connection for %s:%s", p->host, p->port);
if ((c->pfd = proxy_socket(c, p)) == -1) {
start_reply(c, PROXY_ERROR, "proxy error");
return 1;
}
mark_nonblock(c->pfd);
if (proxy_init(c) == -1)
start_reply(c, PROXY_ERROR, "proxy error");
return 1;
}
static int
fcgi_open_sock(struct fcgi *f)
{
struct sockaddr_un addr;
int fd;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
log_warn("socket");
return -1;
}
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
log_warn("failed to connect to %s", f->path);
close(fd);
return -1;
}
return fd;
}
static int
fcgi_open_conn(struct fcgi *f)
{
struct addrinfo hints, *servinfo, *p;
int r, sock, save_errno;
const char *cause = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_ADDRCONFIG;
if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
log_warnx("getaddrinfo %s:%s: %s", f->path, f->port,
gai_strerror(r));
return -1;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sock == -1) {
cause = "socket";
continue;
}
if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
cause = "connect";
save_errno = errno;
close(sock);
errno = save_errno;
continue;
}
break;
}
if (p == NULL) {
log_warn("couldn't connect to %s:%s: %s", f->path, f->port,
cause);
sock = -1;
}
freeaddrinfo(servinfo);
return sock;
}
/* 1 if matching `fcgi' (and apply it), 0 otherwise */
static int
apply_fastcgi(struct client *c)
{
int i = 0;
struct fcgi *f;
struct location *loc;
if ((loc = vhost_fastcgi(c->host, c->iri.path)) == NULL)
return 0;
TAILQ_FOREACH(f, &c->conf->fcgi, fcgi) {
if (i == loc->fcgi)
break;
++i;
}
if (f == NULL) {
log_warnx("can't find fcgi #%d", loc->fcgi);
return 0;
}
log_debug("opening fastcgi connection for (%s,%s)", f->path, f->port);
if (*f->port == '\0')
c->pfd = fcgi_open_sock(f);
else
c->pfd = fcgi_open_conn(f);
if (c->pfd == -1) {
start_reply(c, CGI_ERROR, "CGI error");
return 1;
}
mark_nonblock(c->pfd);
c->cgibev = bufferevent_new(c->pfd, fcgi_read, fcgi_write,
fcgi_error, c);
if (c->cgibev == NULL) {
start_reply(c, TEMP_FAILURE, "internal server error");
return 1;
}
bufferevent_enable(c->cgibev, EV_READ|EV_WRITE);
fcgi_req(c, loc);
return 1;
}
/* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
static int
apply_require_ca(struct client *c)
{
X509_STORE *store;
if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
return 0;
return check_matching_certificate(store, c);
}
static void
server_dir_listing(struct client *c)
{
int root;
root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
if (!vhost_auto_index(c->host, c->iri.path)) {
start_reply(c, NOT_FOUND, "not found");
return;
}
c->dirlen = scandir_fd(c->pfd, &c->dir,
root ? select_non_dotdot : select_non_dot,
alphasort);
if (c->dirlen == -1) {
log_warn("scandir_fd(%d) (vhost:%s) %s",
c->pfd, c->host->domain, c->iri.path);
start_reply(c, TEMP_FAILURE, "internal server error");
return;
}
c->type = REQUEST_DIR;
start_reply(c, SUCCESS, "text/gemini");
evbuffer_add_printf(EVBUFFER_OUTPUT(c->bev),
"# Index of /%s\n\n", c->iri.path);
}
static void
open_dir(struct client *c)
{
struct stat sb;
const char *index;
char path[PATH_MAX];
int fd = -1;
if (*c->iri.path != '\0' && !ends_with(c->iri.path, "/")) {
redirect_canonical_dir(c);
return;
}
index = vhost_index(c->host, c->iri.path);
fd = openat(c->pfd, index, O_RDONLY);
if (fd == -1) {
server_dir_listing(c);
return;
}
if (fstat(fd, &sb) == -1) {
log_warn("fstat");
close(fd);
start_reply(c, TEMP_FAILURE, "internal server error");
return;
}
if (!S_ISREG(sb.st_mode)) {
close(fd);
server_dir_listing(c);
return;
}
snprintf(path, sizeof(path), "%s%s", c->iri.path, index);
close(c->pfd);
c->pfd = fd;
c->type = REQUEST_FILE;
start_reply(c, SUCCESS, mime(c->conf, c->host, path));
}
static void
redirect_canonical_dir(struct client *c)
{
char buf[GEMINI_URL_LEN];
int r;
r = snprintf(buf, sizeof(buf), "/%s/", c->iri.path);
if (r < 0 || (size_t)r >= sizeof(buf)) {
start_reply(c, TEMP_FAILURE, "internal server error");
return;
}
start_reply(c, TEMP_REDIRECT, buf);
}
static void
client_tls_readcb(int fd, short event, void *d)
{
struct bufferevent *bufev = d;
struct client *client = bufev->cbarg;
ssize_t ret;
size_t len;
int what = EVBUFFER_READ;
int howmuch = IBUF_READ_SIZE;
char buf[IBUF_READ_SIZE];
if (event == EV_TIMEOUT) {
what |= EVBUFFER_TIMEOUT;
goto err;
}
if (bufev->wm_read.high != 0)
howmuch = MINIMUM(sizeof(buf), bufev->wm_read.high);
switch (ret = tls_read(client->ctx, buf, howmuch)) {
case TLS_WANT_POLLIN:
case TLS_WANT_POLLOUT:
goto retry;
case -1:
what |= EVBUFFER_ERROR;
goto err;
}
len = ret;
if (len == 0) {
what |= EVBUFFER_EOF;
goto err;
}
if (evbuffer_add(bufev->input, buf, len) == -1) {
what |= EVBUFFER_ERROR;
goto err;
}
event_add(&bufev->ev_read, NULL);
if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
return;
if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
/*
* here we could implement a read pressure policy.
*/
}
if (bufev->readcb != NULL)
(*bufev->readcb)(bufev, bufev->cbarg);
return;
retry:
event_add(&bufev->ev_read, NULL);
return;
err:
(*bufev->errorcb)(bufev, what, bufev->cbarg);
}
static void
client_tls_writecb(int fd, short event, void *d)
{
struct bufferevent *bufev = d;
struct client *client = bufev->cbarg;
ssize_t ret;
size_t len;
short what = EVBUFFER_WRITE;
if (event == EV_TIMEOUT) {
what |= EVBUFFER_TIMEOUT;
goto err;
}
if (EVBUFFER_LENGTH(bufev->output) != 0) {
ret = tls_write(client->ctx,
EVBUFFER_DATA(bufev->output),
EVBUFFER_LENGTH(bufev->output));
switch (ret) {
case TLS_WANT_POLLIN:
case TLS_WANT_POLLOUT:
goto retry;
case -1:
what |= EVBUFFER_ERROR;
goto err;
}
len = ret;
evbuffer_drain(bufev->output, len);
}
if (EVBUFFER_LENGTH(bufev->output) != 0)
event_add(&bufev->ev_write, NULL);
if (bufev->writecb != NULL &&
EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
(*bufev->writecb)(bufev, bufev->cbarg);
return;
retry:
event_add(&bufev->ev_write, NULL);
return;
err:
log_warnx("tls error: %s", tls_error(client->ctx));
(*bufev->errorcb)(bufev, what, bufev->cbarg);
}
static void
client_read(struct bufferevent *bev, void *d)
{
struct stat sb;
struct client *c = d;
struct evbuffer *src = EVBUFFER_INPUT(bev);
const char *path, *p, *parse_err = "invalid request";
char decoded[DOMAIN_NAME_LEN];
char *nul;
size_t len;
bufferevent_disable(bev, EVBUFFER_READ);
/*
* libevent2 can still somehow call this function, even
* though I never enable EV_READ in the bufferevent. If
* that's the case, bail out.
*/
if (c->type != REQUEST_UNDECIDED)
return;
/* max url len + \r\n */
if (EVBUFFER_LENGTH(src) > 1024 + 2) {
log_debug("too much data received");
start_reply(c, BAD_REQUEST, "bad request");
return;
}
c->req = evbuffer_readln(src, &c->reqlen, EVBUFFER_EOL_CRLF_STRICT);
if (c->req == NULL) {
/* not enough data yet. */
bufferevent_enable(bev, EVBUFFER_READ);
return;
}
if (c->reqlen > 1024+2) {
log_debug("URL too long");
start_reply(c, BAD_REQUEST, "bad request");
return;