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 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, "last byte of request isn't NULL\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 - 3, s, strlen(s)+1); /* copy also the \0 */
131 int
132 path_isdir(char *path)
134 size_t len;
136 if (*path == '\0')
137 return 1;
139 len = strlen(path);
141 /* len >= 1 */
142 if (path[len-1] == '/')
143 return 1;
145 return 0;
148 void
149 start_reply(struct tls *ctx, int code, const char *reason)
151 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
152 int len;
154 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
155 assert(len < (int)sizeof(buf));
156 tls_write(ctx, buf, len);
159 int
160 isdir(int fd)
162 struct stat sb;
164 if (fstat(fd, &sb) == -1) {
165 warn("fstat");
166 return 1; /* we'll fail later on anyway */
169 return S_ISDIR(sb.st_mode);
172 void senddir(char*, struct tls*);
174 void
175 sendfile(char *path, struct tls *ctx)
177 int fd;
178 char fpath[PATHBUF];
179 char buf[FILEBUF];
180 size_t i;
181 ssize_t t, w;
183 bzero(fpath, sizeof(fpath));
185 if (*path != '.')
186 strlcpy(fpath, ".", PATHBUF);
188 strlcat(fpath, path, PATHBUF);
190 if ((fd = openat(dirfd, fpath, O_RDONLY | O_NOFOLLOW)) == -1) {
191 warn("open: %s", fpath);
192 start_reply(ctx, NOT_FOUND, "not found");
193 return;
196 if (isdir(fd)) {
197 warnx("%s is a directory, trying %s/index.gmi", fpath, fpath);
198 close(fd);
199 senddir(fpath, ctx);
200 return;
203 /* assume it's a text/gemini file */
204 start_reply(ctx, SUCCESS, "text/gemini");
206 while (1) {
207 if ((w = read(fd, buf, sizeof(buf))) == -1) {
208 warn("read: %s", fpath);
209 goto exit;
212 if (w == 0)
213 break;
215 t = w;
216 i = 0;
218 while (w > 0) {
219 if ((t = tls_write(ctx, buf + i, w)) == -1) {
220 warnx("tls_write (path=%s) : %s",
221 fpath,
222 tls_error(ctx));
223 goto exit;
225 w -= t;
226 i += t;
230 exit:
231 close(fd);
234 void
235 senddir(char *path, struct tls *ctx)
237 char fpath[PATHBUF];
238 size_t len;
240 bzero(fpath, PATHBUF);
242 if (*path != '.')
243 fpath[0] = '.';
245 /* this cannot fail since sizeof(fpath) > maxlen of path */
246 strlcat(fpath, path, PATHBUF);
247 len = strlen(fpath);
249 /* add a trailing / in case. */
250 if (fpath[len-1] != '/') {
251 fpath[len] = '/';
254 strlcat(fpath, "index.gmi", sizeof(fpath));
256 sendfile(fpath, ctx);
259 void
260 handle(char *url, struct tls *ctx)
262 char *path;
264 if (!url_trim(url)) {
265 start_reply(ctx, BAD_REQUEST, "bad request");
266 return;
269 if ((path = url_start_of_request(url)) == NULL)
270 return;
272 adjust_path(path);
274 fprintf(stderr, "requested path: %s\n", path);
276 if (path_isdir(path))
277 senddir(path, ctx);
278 else
279 sendfile(path, ctx);
282 int
283 make_socket(int port)
285 int sock, v;
286 struct sockaddr_in addr;
288 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
289 err(1, "socket");
291 v = 1;
292 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
293 err(1, "setsockopt(SO_REUSEADDR)");
295 v = 1;
296 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
297 err(1, "setsockopt(SO_REUSEPORT)");
299 bzero(&addr, sizeof(addr));
300 addr.sin_family = AF_INET;
301 addr.sin_port = htons(port);
302 addr.sin_addr.s_addr = INADDR_ANY;
304 if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1)
305 err(1, "bind");
307 if (listen(sock, 16) == -1)
308 err(1, "listen");
310 return sock;
313 void
314 loop(struct tls *ctx, int sock)
316 int fd;
317 struct sockaddr_in client;
318 socklen_t len;
319 struct tls *clientctx;
320 char buf[GEMINI_URL_LEN];
321 ssize_t r;
323 for (;;) {
324 len = sizeof(client);
325 if ((fd = accept(sock, (struct sockaddr*)&client, &len)) == -1)
326 err(1, "accept");
328 if (tls_accept_socket(ctx, &clientctx, fd) == -1) {
329 warnx("tls_accept_socket: %s", tls_error(ctx));
330 continue;
333 bzero(buf, GEMINI_URL_LEN);
334 if ((r = tls_read(clientctx, buf, sizeof(buf)-1)) == -1) {
335 warnx("tls_read: %s", tls_error(clientctx));
336 goto clienterr;
339 handle(buf, clientctx);
341 clienterr:
342 if (tls_close(clientctx) == -1)
343 warn("tls_close: client");
344 tls_free(clientctx);
345 close(fd);
349 void
350 usage(const char *me)
352 fprintf(stderr,
353 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
354 me);
357 int
358 main(int argc, char **argv)
360 const char *cert = "cert.pem", *key = "key.pem", *dir = "docs";
361 struct tls *ctx = NULL;
362 struct tls_config *conf;
363 void *m;
364 size_t mlen;
365 int sock, ch;
367 while ((ch = getopt(argc, argv, "c:d:hk:")) != -1) {
368 switch (ch) {
369 case 'c':
370 cert = optarg;
371 break;
373 case 'd':
374 dir = optarg;
375 break;
377 case 'h':
378 usage(*argv);
379 return 0;
381 case 'k':
382 key = optarg;
383 break;
385 default:
386 usage(*argv);
387 return 1;
391 if ((conf = tls_config_new()) == NULL)
392 err(1, "tls_config_new");
394 if ((m = tls_load_file(cert, &mlen, NULL)) == NULL)
395 err(1, "tls_load_file: %s", cert);
396 if (tls_config_set_cert_mem(conf, m, mlen) == -1)
397 err(1, "tls_config_set_cert_mem: server certificate");
399 if ((m = tls_load_file(key, &mlen, NULL)) == NULL)
400 err(1, "tls_load_file: %s", key);
401 if (tls_config_set_key_mem(conf, m, mlen) == -1)
402 err(1, "tls_config_set_cert_mem: server key");
404 if ((ctx = tls_server()) == NULL)
405 err(1, "tls_server");
407 if (tls_configure(ctx, conf) == -1)
408 errx(1, "tls_configure: %s", tls_error(ctx));
410 sock = make_socket(1965);
412 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
413 err(1, "open: %s", dir);
415 if (unveil(dir, "r") == -1)
416 err(1, "unveil");
418 if (pledge("stdio rpath inet", "") == -1)
419 err(1, "pledge");
421 loop(ctx, sock);
423 if (1) {
424 printf("why im I here?\n");
425 abort();
428 close(sock);
429 tls_free(ctx);
430 tls_config_free(conf);