2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
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.
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.
29 int connected_clients;
32 check_path(struct client *c, const char *path, int *fd)
37 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
38 O_RDONLY | O_NOFOLLOW)) == -1) {
42 if (fstat(*fd, &sb) == -1) {
43 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
47 if (S_ISDIR(sb.st_mode))
48 return FILE_DIRECTORY;
50 if (sb.st_mode & S_IXUSR)
51 return FILE_EXECUTABLE;
57 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
59 switch (check_path(c, fpath, &c->fd)) {
61 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
62 return start_cgi(fpath, "", query, fds, c);
67 if ((c->len = filesize(c->fd)) == -1) {
68 LOGE(c, "failed to get file size for %s", fpath);
73 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
74 c->fd, 0)) == MAP_FAILED) {
75 LOGW(c, "mmap: %s: %s", fpath, strerror(errno));
80 return start_reply(fds, c, SUCCESS, mime(c->host, fpath));
83 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
86 send_dir(fpath, fds, c);
90 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
91 return check_for_cgi(fpath, query, fds, c);
93 if (!start_reply(fds, c, NOT_FOUND, "not found"))
106 * the inverse of this algorithm, i.e. starting from the start of the
107 * path + strlen(cgi), and checking if each component, should be
108 * faster. But it's tedious to write. This does the opposite: starts
109 * from the end and strip one component at a time, until either an
110 * executable is found or we emptied the path.
113 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
116 end = strchr(path, '\0');
118 /* NB: assume CGI is enabled and path matches cgi */
121 /* go up one level. UNIX paths are simple and POSIX
122 * dirname, with its ambiguities on if the given path
123 * is changed or not, gives me headaches. */
128 switch (check_path(c, path, &c->fd)) {
129 case FILE_EXECUTABLE:
130 return start_cgi(path, end+1, query, fds,c);
142 if (!start_reply(fds, c, NOT_FOUND, "not found"))
149 mark_nonblock(int fd)
153 if ((flags = fcntl(fd, F_GETFL)) == -1)
154 fatal("fcntl(F_GETFL): %s", strerror(errno));
155 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
156 fatal("fcntl(F_SETFL): %s", strerror(errno));
160 handle_handshake(struct pollfd *fds, struct client *c)
163 const char *servname;
165 switch (tls_handshake(c->ctx)) {
166 case 0: /* success */
167 case -1: /* already handshaked */
169 case TLS_WANT_POLLIN:
170 fds->events = POLLIN;
172 case TLS_WANT_POLLOUT:
173 fds->events = POLLOUT;
180 servname = tls_conn_servername(c->ctx);
181 if (servname == NULL)
184 for (h = hosts; h->domain != NULL; ++h) {
185 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
189 if (h->domain != NULL) {
192 handle_open_conn(fds, c);
197 /* XXX: check the correct response */
198 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
204 handle_open_conn(struct pollfd *fds, struct client *c)
206 char buf[GEMINI_URL_LEN];
207 const char *parse_err = "invalid request";
210 bzero(buf, sizeof(buf));
212 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
214 LOGE(c, "tls_read: %s", tls_error(c->ctx));
218 case TLS_WANT_POLLIN:
219 fds->events = POLLIN;
222 case TLS_WANT_POLLOUT:
223 fds->events = POLLOUT;
227 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
228 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
234 if (strcmp(iri.schema, "gemini") || iri.port_no != conf.port) {
235 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
241 LOGI(c, "GET %s%s%s",
242 *iri.path ? iri.path : "/",
243 *iri.query ? "?" : "",
244 *iri.query ? iri.query : "");
246 send_file(iri.path, iri.query, fds, c);
250 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
252 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
257 c->state = S_INITIALIZING;
259 snprintf(buf, sizeof(buf), "%d ", code);
260 strlcat(buf, meta, sizeof(buf));
261 if (!strcmp(meta, "text/gemini") && c->host->lang != NULL) {
262 strlcat(buf, "; lang=", sizeof(buf));
263 strlcat(buf, c->host->lang, sizeof(buf));
266 len = strlcat(buf, "\r\n", sizeof(buf));
267 assert(len < (int)sizeof(buf));
269 switch (tls_write(c->ctx, buf, len)) {
270 case TLS_WANT_POLLIN:
271 pfd->events = POLLIN;
273 case TLS_WANT_POLLOUT:
274 pfd->events = POLLOUT;
282 start_cgi(const char *spath, const char *relpath, const char *query,
283 struct pollfd *fds, struct client *c)
285 char addr[NI_MAXHOST];
286 const char *ruser, *cissuer, *chash;
289 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
296 if (tls_peer_cert_provided(c->ctx)) {
297 ruser = tls_peer_cert_subject(c->ctx);
298 cissuer = tls_peer_cert_issuer(c->ctx);
299 chash = tls_peer_cert_hash(c->ctx);
306 if (!send_string(exfd, spath)
307 || !send_string(exfd, relpath)
308 || !send_string(exfd, query)
309 || !send_string(exfd, addr)
310 || !send_string(exfd, ruser)
311 || !send_string(exfd, cissuer)
312 || !send_string(exfd, chash)
313 || !send_vhost(exfd, c->host))
317 if ((c->fd = recv_fd(exfd)) == -1) {
318 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
324 c->state = S_SENDING;
325 cgi_poll_on_child(fds, c);
326 /* handle_cgi(fds, c); */
330 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
331 fatal("cannot talk to the executor process");
335 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
340 if (!open_file(path, query, fds, c))
342 c->state = S_SENDING;
345 len = (c->buf + c->len) - c->i;
348 switch (ret = tls_write(c->ctx, c->i, len)) {
350 LOGE(c, "tls_write: %s", tls_error(c->ctx));
354 case TLS_WANT_POLLIN:
355 fds->events = POLLIN;
358 case TLS_WANT_POLLOUT:
359 fds->events = POLLOUT;
373 send_dir(char *path, struct pollfd *fds, struct client *client)
378 bzero(fpath, PATHBUF);
383 /* this cannot fail since sizeof(fpath) > maxlen of path */
384 strlcat(fpath, path, PATHBUF);
387 /* add a trailing / in case. */
388 if (fpath[len-1] != '/') {
392 strlcat(fpath, "index.gmi", sizeof(fpath));
394 send_file(fpath, NULL, fds, client);
398 cgi_poll_on_child(struct pollfd *fds, struct client *c)
402 if (c->waiting_on_child)
404 c->waiting_on_child = 1;
406 fds->events = POLLIN;
414 cgi_poll_on_client(struct pollfd *fds, struct client *c)
418 if (!c->waiting_on_child)
420 c->waiting_on_child = 0;
428 handle_cgi(struct pollfd *fds, struct client *c)
432 /* ensure c->fd is the child and fds->fd the client */
433 cgi_poll_on_client(fds, c);
437 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
440 if (errno == EAGAIN || errno == EWOULDBLOCK) {
441 cgi_poll_on_child(fds, c);
451 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
455 case TLS_WANT_POLLOUT:
456 fds->events = POLLOUT;
459 case TLS_WANT_POLLIN:
460 fds->events = POLLIN;
476 goodbye(struct pollfd *pfd, struct client *c)
478 c->state = S_CLOSING;
480 switch (tls_close(c->ctx)) {
481 case TLS_WANT_POLLIN:
482 pfd->events = POLLIN;
484 case TLS_WANT_POLLOUT:
485 pfd->events = POLLOUT;
494 if (c->buf != MAP_FAILED)
495 munmap(c->buf, c->len);
505 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
508 struct sockaddr_storage addr;
512 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
513 if (errno == EWOULDBLOCK)
515 fatal("accept: %s", strerror(errno));
520 for (i = 0; i < MAX_USERS; ++i) {
521 if (fds[i].fd == -1) {
522 bzero(&clients[i], sizeof(struct client));
523 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
524 break; /* goodbye fd! */
527 fds[i].events = POLLIN;
529 clients[i].state = S_HANDSHAKE;
531 clients[i].child = 0;
532 clients[i].waiting_on_child = 0;
533 clients[i].buf = MAP_FAILED;
534 clients[i].af = AF_INET;
535 clients[i].addr = addr;
546 handle(struct pollfd *fds, struct client *client)
548 switch (client->state) {
550 handle_handshake(fds, client);
554 handle_open_conn(fds, client);
558 if (!start_reply(fds, client, client->code, client->meta))
561 if (client->code != SUCCESS) {
562 /* we don't need a body */
563 goodbye(fds, client);
567 client->state = S_SENDING;
573 handle_cgi(fds, client);
575 send_file(NULL, NULL, fds, client);
579 goodbye(fds, client);
589 loop(struct tls *ctx, int sock4, int sock6)
592 struct client clients[MAX_USERS];
593 struct pollfd fds[MAX_USERS];
595 connected_clients = 0;
597 for (i = 0; i < MAX_USERS; ++i) {
599 fds[i].events = POLLIN;
600 bzero(&clients[i], sizeof(struct client));
607 if (poll(fds, MAX_USERS, INFTIM) == -1) {
608 if (errno == EINTR) {
609 fprintf(stderr, "connected clients: %d\n",
613 fatal("poll: %s", strerror(errno));
616 for (i = 0; i < MAX_USERS; i++) {
617 if (fds[i].revents == 0)
620 if (fds[i].revents & (POLLERR|POLLNVAL))
621 fatal("bad fd %d: %s", fds[i].fd,
624 if (fds[i].revents & POLLHUP) {
625 /* fds[i] may be the fd of the stdin
626 * of a cgi script that has exited. */
627 if (!clients[i].waiting_on_child) {
628 goodbye(&fds[i], &clients[i]);
633 if (fds[i].fd == sock4)
634 do_accept(sock4, ctx, fds, clients);
635 else if (fds[i].fd == sock6)
636 do_accept(sock6, ctx, fds, clients);
638 handle(&fds[i], &clients[i]);