Blob


1 /*
2 * Copyright (c) 2020 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <limits.h>
20 #include <netdb.h>
21 #include <signal.h>
22 #include <stdarg.h>
23 #include <string.h>
25 #include "gmid.h"
27 struct vhost hosts[HOSTSLEN];
29 int goterror;
31 int exfd;
33 struct conf conf;
35 void
36 fatal(const char *fmt, ...)
37 {
38 va_list ap;
40 va_start(ap, fmt);
42 if (conf.foreground) {
43 vfprintf(stderr, fmt, ap);
44 fprintf(stderr, "\n");
45 } else
46 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
48 va_end(ap);
49 exit(1);
50 }
52 void
53 logs(int priority, struct client *c,
54 const char *fmt, ...)
55 {
56 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
57 char *fmted, *s;
58 size_t len;
59 int ec;
60 va_list ap;
62 va_start(ap, fmt);
64 if (c == NULL) {
65 strncpy(hbuf, "<internal>", sizeof(hbuf));
66 sbuf[0] = '\0';
67 } else {
68 len = sizeof(c->addr);
69 ec = getnameinfo((struct sockaddr*)&c->addr, len,
70 hbuf, sizeof(hbuf),
71 sbuf, sizeof(sbuf),
72 NI_NUMERICHOST | NI_NUMERICSERV);
73 if (ec != 0)
74 fatal("getnameinfo: %s", gai_strerror(ec));
75 }
77 if (vasprintf(&fmted, fmt, ap) == -1)
78 fatal("vasprintf: %s", strerror(errno));
80 if (conf.foreground)
81 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
82 else {
83 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
84 fatal("asprintf: %s", strerror(errno));
85 syslog(priority | LOG_DAEMON, "%s", s);
86 free(s);
87 }
89 free(fmted);
91 va_end(ap);
92 }
94 /* strchr, but with a bound */
95 static char *
96 gmid_strnchr(char *s, int c, size_t len)
97 {
98 size_t i;
100 for (i = 0; i < len; ++i)
101 if (s[i] == c)
102 return &s[i];
103 return NULL;
106 void
107 log_request(struct client *c, char *meta, size_t l)
109 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
110 char *t;
111 size_t len;
112 int ec;
114 len = sizeof(c->addr);
115 ec = getnameinfo((struct sockaddr*)&c->addr, len,
116 hbuf, sizeof(hbuf),
117 sbuf, sizeof(sbuf),
118 NI_NUMERICHOST | NI_NUMERICSERV);
119 if (ec != 0)
120 fatal("getnameinfo: %s", gai_strerror(ec));
122 if (c->iri.schema != NULL) {
123 /* serialize the IRI */
124 strlcpy(b, c->iri.schema, sizeof(b));
125 strlcat(b, "://", sizeof(b));
126 strlcat(b, c->iri.host, sizeof(b));
127 strlcat(b, "/", sizeof(b));
128 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
129 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
130 strlcat(b, "?", sizeof(b));
131 strlcat(b, c->iri.query, sizeof(b));
133 } else {
134 strlcpy(b, c->req, sizeof(b));
137 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
138 t = meta + len;
140 if (conf.foreground)
141 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
142 (int)(t - meta), meta);
143 else
144 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
145 hbuf, sbuf, b, (int)(t - meta), meta);
148 void
149 sig_handler(int sig)
151 (void)sig;
154 int
155 starts_with(const char *str, const char *prefix)
157 size_t i;
159 for (i = 0; prefix[i] != '\0'; ++i)
160 if (str[i] != prefix[i])
161 return 0;
162 return 1;
165 ssize_t
166 filesize(int fd)
168 ssize_t len;
170 if ((len = lseek(fd, 0, SEEK_END)) == -1)
171 return -1;
172 if (lseek(fd, 0, SEEK_SET) == -1)
173 return -1;
174 return len;
177 char *
178 absolutify_path(const char *path)
180 char *wd, *r;
182 if (*path == '/')
183 return strdup(path);
185 wd = getcwd(NULL, 0);
186 if (asprintf(&r, "%s/%s", wd, path) == -1)
187 fatal("asprintf: %s", strerror(errno));
188 free(wd);
189 return r;
192 void
193 yyerror(const char *msg)
195 goterror = 1;
196 fprintf(stderr, "%d: %s\n", yylineno, msg);
199 int
200 parse_portno(const char *p)
202 char *ep;
203 long lval;
205 errno = 0;
206 lval = strtol(p, &ep, 10);
207 if (p[0] == '\0' || *ep != '\0')
208 fatal("not a number: %s", p);
209 if (lval < 0 || lval > UINT16_MAX)
210 fatal("port number out of range for domain %s: %ld", p, lval);
211 return lval;
214 void
215 parse_conf(const char *path)
217 if ((yyin = fopen(path, "r")) == NULL)
218 fatal("cannot open config %s", path);
219 yyparse();
220 fclose(yyin);
222 if (goterror)
223 exit(1);
226 void
227 load_vhosts(struct tls_config *tlsconf)
229 struct vhost *h;
231 /* we need to set something, then we can add how many key we want */
232 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
233 fatal("tls_config_set_keypair_file failed");
235 for (h = hosts; h->domain != NULL; ++h) {
236 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
237 fatal("failed to load the keypair (%s, %s)",
238 h->cert, h->key);
240 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
241 fatal("open %s for domain %s", h->dir, h->domain);
245 int
246 make_socket(int port, int family)
248 int sock, v;
249 struct sockaddr_in addr4;
250 struct sockaddr_in6 addr6;
251 struct sockaddr *addr;
252 socklen_t len;
254 switch (family) {
255 case AF_INET:
256 bzero(&addr4, sizeof(addr4));
257 addr4.sin_family = family;
258 addr4.sin_port = htons(port);
259 addr4.sin_addr.s_addr = INADDR_ANY;
260 addr = (struct sockaddr*)&addr4;
261 len = sizeof(addr4);
262 break;
264 case AF_INET6:
265 bzero(&addr6, sizeof(addr6));
266 addr6.sin6_family = AF_INET6;
267 addr6.sin6_port = htons(port);
268 addr6.sin6_addr = in6addr_any;
269 addr = (struct sockaddr*)&addr6;
270 len = sizeof(addr6);
271 break;
273 default:
274 /* unreachable */
275 abort();
278 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
279 fatal("socket: %s", strerror(errno));
281 v = 1;
282 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
283 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
285 v = 1;
286 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
287 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
289 mark_nonblock(sock);
291 if (bind(sock, addr, len) == -1)
292 fatal("bind: %s", strerror(errno));
294 if (listen(sock, 16) == -1)
295 fatal("listen: %s", strerror(errno));
297 return sock;
300 int
301 listener_main()
303 int sock4, sock6;
304 struct tls *ctx = NULL;
305 struct tls_config *tlsconf;
307 load_default_mime(&conf.mime);
309 if ((tlsconf = tls_config_new()) == NULL)
310 fatal("tls_config_new");
312 /* optionally accept client certs, but don't try to verify them */
313 tls_config_verify_client_optional(tlsconf);
314 tls_config_insecure_noverifycert(tlsconf);
316 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
317 fatal("tls_config_set_protocols");
319 if ((ctx = tls_server()) == NULL)
320 fatal("tls_server failure");
322 load_vhosts(tlsconf);
324 if (tls_configure(ctx, tlsconf) == -1)
325 fatal("tls_configure: %s", tls_error(ctx));
327 if (!conf.foreground && daemon(0, 1) == -1)
328 exit(1);
330 sock4 = make_socket(conf.port, AF_INET);
331 sock6 = -1;
332 if (conf.ipv6)
333 sock6 = make_socket(conf.port, AF_INET6);
335 sandbox();
336 loop(ctx, sock4, sock6);
338 return 0;
341 void
342 usage(const char *me)
344 fprintf(stderr,
345 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
346 "[-p port] [-x cgi-bin]\n",
347 me);
350 int
351 main(int argc, char **argv)
353 int ch, p[2];
354 const char *config_path = NULL;
355 size_t i;
356 int conftest = 0;
358 bzero(hosts, sizeof(hosts));
359 for (i = 0; i < HOSTSLEN; ++i)
360 hosts[i].dirfd = -1;
362 conf.foreground = 1;
363 conf.port = 1965;
364 conf.ipv6 = 0;
365 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
367 init_mime(&conf.mime);
369 while ((ch = getopt(argc, argv, "6C:c:d:fhK:np:x:")) != -1) {
370 switch (ch) {
371 case '6':
372 conf.ipv6 = 1;
373 break;
375 case 'C':
376 hosts[0].cert = optarg;
377 break;
379 case 'c':
380 config_path = optarg;
381 break;
383 case 'd':
384 free((char*)hosts[0].dir);
385 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
386 fatal("absolutify_path");
387 break;
389 case 'f':
390 conf.foreground = 1;
391 break;
393 case 'h':
394 usage(*argv);
395 return 0;
397 case 'K':
398 hosts[0].key = optarg;
399 break;
401 case 'n':
402 conftest = 1;
403 break;
405 case 'p':
406 conf.port = parse_portno(optarg);
407 break;
409 case 'x':
410 /* drop the starting / (if any) */
411 if (*optarg == '/')
412 optarg++;
413 hosts[0].cgi = optarg;
414 break;
416 default:
417 usage(*argv);
418 return 1;
422 if (config_path != NULL) {
423 if (hosts[0].cert != NULL || hosts[0].key != NULL ||
424 hosts[0].dir != NULL)
425 fatal("can't specify options in conf mode");
426 parse_conf(config_path);
427 } else {
428 if (hosts[0].cert == NULL || hosts[0].key == NULL ||
429 hosts[0].dir == NULL)
430 fatal("missing cert, key or root directory to serve");
431 hosts[0].domain = "*";
434 if (conftest) {
435 puts("config OK");
436 return 0;
439 signal(SIGPIPE, SIG_IGN);
440 signal(SIGCHLD, SIG_IGN);
442 #ifdef SIGINFO
443 signal(SIGINFO, sig_handler);
444 #endif
445 signal(SIGUSR2, sig_handler);
447 if (!conf.foreground) {
448 signal(SIGHUP, SIG_IGN);
449 if (daemon(1, 1) == -1)
450 fatal("daemon: %s", strerror(errno));
453 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
454 fatal("socketpair: %s", strerror(errno));
456 switch (fork()) {
457 case -1:
458 fatal("fork: %s", strerror(errno));
460 case 0: /* child */
461 close(p[0]);
462 exfd = p[1];
463 listener_main();
464 _exit(0);
466 default: /* parent */
467 close(p[1]);
468 return executor_main(p[0]);