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 /* serialize the IRI */
123 strlcpy(b, c->iri.schema, sizeof(b));
124 strlcat(b, "://", sizeof(b));
125 strlcat(b, c->iri.host, sizeof(b));
126 strlcat(b, "/", sizeof(b));
127 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
128 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
129 strlcat(b, "?", sizeof(b));
130 strlcat(b, c->iri.query, sizeof(b));
133 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
134 t = meta + len;
136 if (conf.foreground)
137 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
138 (int)(t - meta), meta);
139 else
140 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
141 hbuf, sbuf, b, (int)(t - meta), meta);
144 void
145 sig_handler(int sig)
147 (void)sig;
150 int
151 starts_with(const char *str, const char *prefix)
153 size_t i;
155 for (i = 0; prefix[i] != '\0'; ++i)
156 if (str[i] != prefix[i])
157 return 0;
158 return 1;
161 ssize_t
162 filesize(int fd)
164 ssize_t len;
166 if ((len = lseek(fd, 0, SEEK_END)) == -1)
167 return -1;
168 if (lseek(fd, 0, SEEK_SET) == -1)
169 return -1;
170 return len;
173 char *
174 absolutify_path(const char *path)
176 char *wd, *r;
178 if (*path == '/')
179 return strdup(path);
181 wd = getcwd(NULL, 0);
182 if (asprintf(&r, "%s/%s", wd, path) == -1)
183 fatal("asprintf: %s", strerror(errno));
184 free(wd);
185 return r;
188 void
189 yyerror(const char *msg)
191 goterror = 1;
192 fprintf(stderr, "%d: %s\n", yylineno, msg);
195 int
196 parse_portno(const char *p)
198 char *ep;
199 long lval;
201 errno = 0;
202 lval = strtol(p, &ep, 10);
203 if (p[0] == '\0' || *ep != '\0')
204 fatal("not a number: %s", p);
205 if (lval < 0 || lval > UINT16_MAX)
206 fatal("port number out of range for domain %s: %ld", p, lval);
207 return lval;
210 void
211 parse_conf(const char *path)
213 if ((yyin = fopen(path, "r")) == NULL)
214 fatal("cannot open config %s", path);
215 yyparse();
216 fclose(yyin);
218 if (goterror)
219 exit(1);
222 void
223 load_vhosts(struct tls_config *tlsconf)
225 struct vhost *h;
227 /* we need to set something, then we can add how many key we want */
228 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
229 fatal("tls_config_set_keypair_file failed");
231 for (h = hosts; h->domain != NULL; ++h) {
232 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
233 fatal("failed to load the keypair (%s, %s)",
234 h->cert, h->key);
236 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
237 fatal("open %s for domain %s", h->dir, h->domain);
241 int
242 make_socket(int port, int family)
244 int sock, v;
245 struct sockaddr_in addr4;
246 struct sockaddr_in6 addr6;
247 struct sockaddr *addr;
248 socklen_t len;
250 switch (family) {
251 case AF_INET:
252 bzero(&addr4, sizeof(addr4));
253 addr4.sin_family = family;
254 addr4.sin_port = htons(port);
255 addr4.sin_addr.s_addr = INADDR_ANY;
256 addr = (struct sockaddr*)&addr4;
257 len = sizeof(addr4);
258 break;
260 case AF_INET6:
261 bzero(&addr6, sizeof(addr6));
262 addr6.sin6_family = AF_INET6;
263 addr6.sin6_port = htons(port);
264 addr6.sin6_addr = in6addr_any;
265 addr = (struct sockaddr*)&addr6;
266 len = sizeof(addr6);
267 break;
269 default:
270 /* unreachable */
271 abort();
274 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
275 fatal("socket: %s", strerror(errno));
277 v = 1;
278 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
279 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
281 v = 1;
282 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
283 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
285 mark_nonblock(sock);
287 if (bind(sock, addr, len) == -1)
288 fatal("bind: %s", strerror(errno));
290 if (listen(sock, 16) == -1)
291 fatal("listen: %s", strerror(errno));
293 return sock;
296 int
297 listener_main()
299 int sock4, sock6;
300 struct tls *ctx = NULL;
301 struct tls_config *tlsconf;
303 load_default_mime();
305 if ((tlsconf = tls_config_new()) == NULL)
306 fatal("tls_config_new");
308 /* optionally accept client certs, but don't try to verify them */
309 tls_config_verify_client_optional(tlsconf);
310 tls_config_insecure_noverifycert(tlsconf);
312 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
313 fatal("tls_config_set_protocols");
315 if ((ctx = tls_server()) == NULL)
316 fatal("tls_server failure");
318 load_vhosts(tlsconf);
320 if (tls_configure(ctx, tlsconf) == -1)
321 fatal("tls_configure: %s", tls_error(ctx));
323 if (!conf.foreground && daemon(0, 1) == -1)
324 exit(1);
326 sock4 = make_socket(conf.port, AF_INET);
327 sock6 = -1;
328 if (conf.ipv6)
329 sock6 = make_socket(conf.port, AF_INET6);
331 sandbox();
332 loop(ctx, sock4, sock6);
334 return 0;
337 void
338 usage(const char *me)
340 fprintf(stderr,
341 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
342 "[-p port] [-x cgi-bin]\n",
343 me);
346 int
347 main(int argc, char **argv)
349 int ch, p[2];
350 const char *config_path = NULL;
351 size_t i;
352 int conftest = 0;
354 bzero(hosts, sizeof(hosts));
355 for (i = 0; i < HOSTSLEN; ++i)
356 hosts[i].dirfd = -1;
358 conf.foreground = 1;
359 conf.port = 1965;
360 conf.ipv6 = 0;
361 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
363 init_mime();
365 while ((ch = getopt(argc, argv, "6C:c:d:fhK:np:x:")) != -1) {
366 switch (ch) {
367 case '6':
368 conf.ipv6 = 1;
369 break;
371 case 'C':
372 hosts[0].cert = optarg;
373 break;
375 case 'c':
376 config_path = optarg;
377 break;
379 case 'd':
380 free((char*)hosts[0].dir);
381 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
382 fatal("absolutify_path");
383 break;
385 case 'f':
386 conf.foreground = 1;
387 break;
389 case 'h':
390 usage(*argv);
391 return 0;
393 case 'K':
394 hosts[0].key = optarg;
395 break;
397 case 'n':
398 conftest = 1;
399 break;
401 case 'p':
402 conf.port = parse_portno(optarg);
403 break;
405 case 'x':
406 /* drop the starting / (if any) */
407 if (*optarg == '/')
408 optarg++;
409 hosts[0].cgi = optarg;
410 break;
412 default:
413 usage(*argv);
414 return 1;
418 if (config_path != NULL) {
419 if (hosts[0].cert != NULL || hosts[0].key != NULL ||
420 hosts[0].dir != NULL)
421 fatal("can't specify options in conf mode");
422 parse_conf(config_path);
423 } else {
424 if (hosts[0].cert == NULL || hosts[0].key == NULL ||
425 hosts[0].dir == NULL)
426 fatal("missing cert, key or root directory to serve");
427 hosts[0].domain = "*";
430 if (conftest) {
431 puts("config OK");
432 return 0;
435 signal(SIGPIPE, SIG_IGN);
436 signal(SIGCHLD, SIG_IGN);
438 #ifdef SIGINFO
439 signal(SIGINFO, sig_handler);
440 #endif
441 signal(SIGUSR2, sig_handler);
443 if (!conf.foreground) {
444 signal(SIGHUP, SIG_IGN);
445 if (daemon(1, 1) == -1)
446 fatal("daemon: %s", strerror(errno));
449 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
450 fatal("socketpair: %s", strerror(errno));
452 switch (fork()) {
453 case -1:
454 fatal("fork: %s", strerror(errno));
456 case 0: /* child */
457 close(p[0]);
458 exfd = p[1];
459 listener_main();
460 _exit(0);
462 default: /* parent */
463 close(p[1]);
464 return executor_main(p[0]);