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 <sys/socket.h>
18 #include <sys/stat.h>
20 #include <netinet/in.h>
22 #include <assert.h>
23 #include <err.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <tls.h>
29 #include <unistd.h>
31 #ifndef __OpenBSD__
32 # define pledge(a, b) 0
33 # define unveil(a, b) 0
34 #endif /* __OpenBSD__ */
36 #define GEMINI_URL_LEN (1024+3) /* URL max len + \r\n + \0 */
38 /* large enough to hold a copy of a gemini URL and still have extra room */
39 #define PATHBUF 2048
41 #define FILEBUF 1024
43 #define SUCCESS 20
44 #define NOT_FOUND 51
45 #define BAD_REQUEST 59
47 int dirfd;
49 char *
50 url_after_proto(char *url)
51 {
52 char *s;
53 const char *proto = "gemini";
54 const char *marker = "://";
56 if ((s = strstr(url, marker)) == NULL)
57 return url;
59 /* not a gemini:// URL */
61 if (s - strlen(proto) < url)
62 return NULL;
63 /* TODO: */
64 /* if (strcmp(s - strlen(proto), proto)) */
65 /* return NULL; */
67 /* a valid gemini:// URL */
68 return s + strlen(marker);
69 }
71 char *
72 url_start_of_request(char *url)
73 {
74 char *s, *t;
76 if ((s = url_after_proto(url)) == NULL)
77 return NULL;
79 if ((t = strstr(s, "/")) == NULL)
80 return s + strlen(s);
81 return t;
82 }
84 int
85 url_trim(char *url)
86 {
87 const char *e = "\r\n";
88 char *s;
90 if ((s = strstr(url, e)) == NULL)
91 return 0;
92 s[0] = '\0';
93 s[1] = '\0';
95 if (s[2] != '\0') {
96 fprintf(stderr, "the request was longer than 1024 bytes\n");
97 return 0;
98 }
100 return 1;
103 void
104 adjust_path(char *path)
106 char *s;
107 size_t len;
109 /* /.. -> / */
110 len = strlen(path);
111 if (len >= 3) {
112 if (!strcmp(&path[len-3], "/..")) {
113 path[len-2] = '\0';
117 /* if the path is only `..` trim out and exit */
118 if (!strcmp(path, "..")) {
119 path[0] = '\0';
120 return;
123 /* remove every ../ in the path */
124 while (1) {
125 if ((s = strstr(path, "../")) == NULL)
126 return;
127 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
131 int
132 path_isdir(char *path)
134 if (*path == '\0')
135 return 1;
136 return path[strlen(path)-1] == '/';
139 void
140 start_reply(struct tls *ctx, int code, const char *reason)
142 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
143 int len;
145 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
146 assert(len < (int)sizeof(buf));
147 tls_write(ctx, buf, len);
150 int
151 isdir(int fd)
153 struct stat sb;
155 if (fstat(fd, &sb) == -1) {
156 warn("fstat");
157 return 1; /* we'll probably fail later on anyway */
160 return S_ISDIR(sb.st_mode);
163 void send_dir(char*, struct tls*);
165 void
166 send_file(char *path, struct tls *ctx)
168 int fd;
169 char fpath[PATHBUF];
170 char buf[FILEBUF];
171 size_t i;
172 ssize_t t, w;
174 bzero(fpath, sizeof(fpath));
176 if (*path != '.')
177 fpath[0] = '.';
179 strlcat(fpath, path, PATHBUF);
181 if ((fd = openat(dirfd, fpath, O_RDONLY | O_NOFOLLOW)) == -1) {
182 warn("open: %s", fpath);
183 start_reply(ctx, NOT_FOUND, "not found");
184 return;
187 if (isdir(fd)) {
188 warnx("%s is a directory, trying %s/index.gmi", fpath, fpath);
189 close(fd);
190 send_dir(fpath, ctx);
191 return;
194 /* assume it's a text/gemini file */
195 start_reply(ctx, SUCCESS, "text/gemini");
197 while (1) {
198 if ((w = read(fd, buf, sizeof(buf))) == -1) {
199 warn("read: %s", fpath);
200 goto exit;
203 if (w == 0)
204 break;
206 t = w;
207 i = 0;
209 while (w > 0) {
210 if ((t = tls_write(ctx, buf + i, w)) == -1) {
211 warnx("tls_write (path=%s) : %s",
212 fpath,
213 tls_error(ctx));
214 goto exit;
216 w -= t;
217 i += t;
221 exit:
222 close(fd);
225 void
226 send_dir(char *path, struct tls *ctx)
228 char fpath[PATHBUF];
229 size_t len;
231 bzero(fpath, PATHBUF);
233 if (*path != '.')
234 fpath[0] = '.';
236 /* this cannot fail since sizeof(fpath) > maxlen of path */
237 strlcat(fpath, path, PATHBUF);
238 len = strlen(fpath);
240 /* add a trailing / in case. */
241 if (fpath[len-1] != '/') {
242 fpath[len] = '/';
245 strlcat(fpath, "index.gmi", sizeof(fpath));
247 send_file(fpath, ctx);
250 void
251 handle(char *url, struct tls *ctx)
253 char *path;
255 if (!url_trim(url)) {
256 start_reply(ctx, BAD_REQUEST, "bad request");
257 return;
260 if ((path = url_start_of_request(url)) == NULL) {
261 start_reply(ctx, BAD_REQUEST, "bad request");
262 return;
265 adjust_path(path);
267 fprintf(stderr, "requested path: %s\n", path);
269 if (path_isdir(path))
270 send_dir(path, ctx);
271 else
272 send_file(path, ctx);
275 int
276 make_socket(int port)
278 int sock, v;
279 struct sockaddr_in addr;
281 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
282 err(1, "socket");
284 v = 1;
285 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
286 err(1, "setsockopt(SO_REUSEADDR)");
288 v = 1;
289 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
290 err(1, "setsockopt(SO_REUSEPORT)");
292 bzero(&addr, sizeof(addr));
293 addr.sin_family = AF_INET;
294 addr.sin_port = htons(port);
295 addr.sin_addr.s_addr = INADDR_ANY;
297 if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1)
298 err(1, "bind");
300 if (listen(sock, 16) == -1)
301 err(1, "listen");
303 return sock;
306 void
307 loop(struct tls *ctx, int sock)
309 int fd;
310 struct sockaddr_in client;
311 socklen_t len;
312 struct tls *clientctx;
313 char buf[GEMINI_URL_LEN];
315 for (;;) {
316 len = sizeof(client);
317 if ((fd = accept(sock, (struct sockaddr*)&client, &len)) == -1)
318 err(1, "accept");
320 if (tls_accept_socket(ctx, &clientctx, fd) == -1) {
321 warnx("tls_accept_socket: %s", tls_error(ctx));
322 continue;
325 bzero(buf, GEMINI_URL_LEN);
326 if (tls_read(clientctx, buf, sizeof(buf)-1) == -1) {
327 warnx("tls_read: %s", tls_error(clientctx));
328 goto clientend;
331 handle(buf, clientctx);
333 clientend:
334 if (tls_close(clientctx) == -1)
335 warn("tls_close: client");
336 tls_free(clientctx);
337 close(fd);
341 void
342 usage(const char *me)
344 fprintf(stderr,
345 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
346 me);
349 int
350 main(int argc, char **argv)
352 const char *cert = "cert.pem", *key = "key.pem", *dir = "docs";
353 struct tls *ctx = NULL;
354 struct tls_config *conf;
355 int sock, ch;
357 while ((ch = getopt(argc, argv, "c:d:hk:")) != -1) {
358 switch (ch) {
359 case 'c':
360 cert = optarg;
361 break;
363 case 'd':
364 dir = optarg;
365 break;
367 case 'h':
368 usage(*argv);
369 return 0;
371 case 'k':
372 key = optarg;
373 break;
375 default:
376 usage(*argv);
377 return 1;
381 if ((conf = tls_config_new()) == NULL)
382 err(1, "tls_config_new");
384 if (tls_config_set_protocols(conf,
385 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
386 err(1, "tls_config_set_protocols");
388 if (tls_config_set_cert_file(conf, cert) == -1)
389 err(1, "tls_config_set_cert_file: %s", cert);
391 if (tls_config_set_key_file(conf, key) == -1)
392 err(1, "tls_config_set_key_file: %s", key);
394 if ((ctx = tls_server()) == NULL)
395 err(1, "tls_server");
397 if (tls_configure(ctx, conf) == -1)
398 errx(1, "tls_configure: %s", tls_error(ctx));
400 sock = make_socket(1965);
402 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
403 err(1, "open: %s", dir);
405 if (unveil(dir, "r") == -1)
406 err(1, "unveil");
408 if (pledge("stdio rpath inet", "") == -1)
409 err(1, "pledge");
411 loop(ctx, sock);
413 close(sock);
414 tls_free(ctx);
415 tls_config_free(conf);