Blob


1 /*
2 * Copyright (c) 2021 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 /*
18 * Handles the data in ~/.telescope
19 *
20 * TODO: add some form of locking on the files
21 */
23 #include "compat.h"
25 #include <sys/stat.h>
26 #include <sys/types.h>
28 #include <dirent.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <limits.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
37 #include "telescope.h"
38 #include "pages.h"
40 static void die(void) __attribute__((__noreturn__));
41 static void send_file(uint32_t, FILE *);
42 static void handle_get(struct imsg*, size_t);
43 static int select_non_dot(const struct dirent *);
44 static int select_non_dotdot(const struct dirent *);
45 static void handle_get_file(struct imsg*, size_t);
46 static void handle_quit(struct imsg*, size_t);
47 static void handle_bookmark_page(struct imsg*, size_t);
48 static void handle_save_cert(struct imsg*, size_t);
49 static void handle_update_cert(struct imsg*, size_t);
50 static void handle_file_open(struct imsg*, size_t);
51 static void handle_session_start(struct imsg*, size_t);
52 static void handle_session_tab(struct imsg*, size_t);
53 static void handle_session_tab_title(struct imsg*, size_t);
54 static void handle_session_end(struct imsg*, size_t);
55 static void handle_dispatch_imsg(int, short, void*);
56 static int fs_send_ui(int, uint32_t, int, const void *, uint16_t);
58 static struct imsgev *iev_ui;
59 static FILE *session;
61 static char base_path[PATH_MAX];
62 static char lockfile_path[PATH_MAX];
63 static char bookmark_file[PATH_MAX];
64 static char known_hosts_file[PATH_MAX], known_hosts_tmp[PATH_MAX];
65 static char crashed_file[PATH_MAX];
67 char session_file[PATH_MAX];
69 static imsg_handlerfn *handlers[] = {
70 [IMSG_GET] = handle_get,
71 [IMSG_GET_FILE] = handle_get_file,
72 [IMSG_QUIT] = handle_quit,
73 [IMSG_BOOKMARK_PAGE] = handle_bookmark_page,
74 [IMSG_SAVE_CERT] = handle_save_cert,
75 [IMSG_UPDATE_CERT] = handle_update_cert,
76 [IMSG_FILE_OPEN] = handle_file_open,
77 [IMSG_SESSION_START] = handle_session_start,
78 [IMSG_SESSION_TAB] = handle_session_tab,
79 [IMSG_SESSION_TAB_TITLE] = handle_session_tab_title,
80 [IMSG_SESSION_END] = handle_session_end,
81 };
83 static void __attribute__((__noreturn__))
84 die(void)
85 {
86 abort(); /* TODO */
87 }
89 static void
90 send_file(uint32_t peerid, FILE *f)
91 {
92 ssize_t r;
93 char buf[BUFSIZ];
95 for (;;) {
96 r = fread(buf, 1, sizeof(buf), f);
97 if (r != 0)
98 fs_send_ui(IMSG_BUF, peerid, -1, buf, r);
99 if (r != sizeof(buf))
100 break;
102 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
103 fclose(f);
106 static void
107 handle_get(struct imsg *imsg, size_t datalen)
109 const char *bpath = "bookmarks.gmi";
110 char path[PATH_MAX];
111 FILE *f;
112 const char *data, *p;
113 size_t i;
114 struct page {
115 const char *name;
116 const char *path;
117 const uint8_t *data;
118 size_t len;
119 } pages[] = {
120 {"about", NULL, about_about, about_about_len},
121 {"blank", NULL, about_blank, about_blank_len},
122 {"bookmarks", bpath, bookmarks, bookmarks_len},
123 {"crash", NULL, about_crash, about_crash_len},
124 {"help", NULL, about_help, about_help_len},
125 {"license", NULL, about_license, about_license_len},
126 {"new", NULL, about_new, about_new_len},
127 }, *page = NULL;
129 data = imsg->data;
130 if (data[datalen-1] != '\0') /* make sure it's NUL-terminated */
131 die();
132 if ((data = strchr(data, ':')) == NULL)
133 goto notfound;
134 data++;
136 for (i = 0; i < sizeof(pages)/sizeof(pages[0]); ++i)
137 if (!strcmp(data, pages[i].name)) {
138 page = &pages[i];
139 break;
142 if (page == NULL)
143 goto notfound;
145 strlcpy(path, base_path, sizeof(path));
146 strlcat(path, "/", sizeof(path));
147 if (page->path != NULL)
148 strlcat(path, page->path, sizeof(path));
149 else {
150 strlcat(path, "pages/about_", sizeof(path));
151 strlcat(path, page->name, sizeof(path));
152 strlcat(path, ".gmi", sizeof(path));
155 if ((f = fopen(path, "r")) == NULL) {
156 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1,
157 page->data, page->len);
158 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1,
159 NULL, 0);
160 return;
163 send_file(imsg->hdr.peerid, f);
164 return;
166 notfound:
167 p = "# not found!\n";
168 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1, p, strlen(p));
169 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1, NULL, 0);
172 static inline void
173 send_hdr(uint32_t peerid, int code, const char *meta)
175 fs_send_ui(IMSG_GOT_CODE, peerid, -1, &code, sizeof(code));
176 fs_send_ui(IMSG_GOT_META, peerid, -1, meta, strlen(meta)+1);
179 static inline const char *
180 file_type(const char *path)
182 struct mapping {
183 const char *ext;
184 const char *mime;
185 } ms[] = {
186 {"diff", "text/x-patch"},
187 {"gemini", "text/gemini"},
188 {"gmi", "text/gemini"},
189 {"markdown", "text/plain"},
190 {"md", "text/plain"},
191 {"patch", "text/x-patch"},
192 {"txt", "text/plain"},
193 {NULL, NULL},
194 }, *m;
195 char *dot;
197 if ((dot = strrchr(path, '.')) == NULL)
198 return NULL;
200 dot++;
202 for (m = ms; m->ext != NULL; ++m)
203 if (!strcmp(m->ext, dot))
204 return m->mime;
206 return NULL;
209 static int
210 select_non_dot(const struct dirent *d)
212 return strcmp(d->d_name, ".");
215 static int
216 select_non_dotdot(const struct dirent *d)
218 return strcmp(d->d_name, ".") && strcmp(d->d_name, "..");
221 static inline void
222 send_dir(uint32_t peerid, const char *path)
224 struct dirent **names;
225 struct evbuffer *ev;
226 char *s;
227 int (*selector)(const struct dirent *) = select_non_dot;
228 int i, len;
230 if (!has_suffix(path, "/")) {
231 if (asprintf(&s, "%s/", path) == -1)
232 die();
233 send_hdr(peerid, 30, s);
234 free(s);
235 return;
238 if (!strcmp(path, "/"))
239 selector = select_non_dotdot;
241 if ((ev = evbuffer_new()) == NULL ||
242 (len = scandir(path, &names, selector, alphasort)) == -1) {
243 evbuffer_free(ev);
244 send_hdr(peerid, 40, "failure reading the directory");
245 return;
248 evbuffer_add_printf(ev, "# Index of %s\n\n", path);
249 for (i = 0; i < len; ++i) {
250 evbuffer_add_printf(ev, "=> %s", names[i]->d_name);
251 if (names[i]->d_type == DT_DIR)
252 evbuffer_add(ev, "/", 1);
253 evbuffer_add(ev, "\n", 1);
256 send_hdr(peerid, 20, "text/gemini");
257 fs_send_ui(IMSG_BUF, peerid, -1,
258 EVBUFFER_DATA(ev), EVBUFFER_LENGTH(ev));
259 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
261 evbuffer_free(ev);
262 free(names);
265 static void
266 handle_get_file(struct imsg *imsg, size_t datalen)
268 struct stat sb;
269 FILE *f;
270 char *data;
271 const char *meta = NULL;
273 data = imsg->data;
274 data[datalen-1] = '\0';
276 if ((f = fopen(data, "r")) == NULL) {
277 send_hdr(imsg->hdr.peerid, 51, "can't open the file");
278 return;
281 if (fstat(fileno(f), &sb) == -1) {
282 send_hdr(imsg->hdr.peerid, 40, "fstat failed");
283 return;
286 if (S_ISDIR(sb.st_mode)) {
287 fclose(f);
288 send_dir(imsg->hdr.peerid, data);
289 return;
292 if ((meta = file_type(data)) == NULL) {
293 fclose(f);
294 send_hdr(imsg->hdr.peerid, 51,
295 "don't know how to visualize this file");
296 return;
299 send_hdr(imsg->hdr.peerid, 20, meta);
300 send_file(imsg->hdr.peerid, f);
303 static void
304 handle_quit(struct imsg *imsg, size_t datalen)
306 event_loopbreak();
309 static void
310 handle_bookmark_page(struct imsg *imsg, size_t datalen)
312 char *data;
313 int res;
314 FILE *f;
316 data = imsg->data;
317 if (data[datalen-1] != '\0')
318 die();
320 if ((f = fopen(bookmark_file, "a")) == NULL) {
321 res = errno;
322 goto end;
324 fprintf(f, "=> %s\n", data);
325 fclose(f);
327 res = 0;
328 end:
329 fs_send_ui(IMSG_BOOKMARK_OK, 0, -1, &res, sizeof(res));
332 static void
333 handle_save_cert(struct imsg *imsg, size_t datalen)
335 struct tofu_entry e;
336 FILE *f;
337 int res;
339 /* TODO: traverse the file to avoid duplications? */
341 if (datalen != sizeof(e))
342 die();
343 memcpy(&e, imsg->data, datalen);
345 if ((f = fopen(known_hosts_file, "a")) == NULL) {
346 res = errno;
347 goto end;
349 fprintf(f, "%s %s %d\n", e.domain, e.hash, e.verified);
350 fclose(f);
352 res = 0;
353 end:
354 fs_send_ui(IMSG_SAVE_CERT_OK, imsg->hdr.peerid, -1,
355 &res, sizeof(res));
358 static void
359 handle_update_cert(struct imsg *imsg, size_t datalen)
361 FILE *tmp, *f;
362 struct tofu_entry entry;
363 char sfn[PATH_MAX], *line = NULL, *t;
364 size_t l, linesize = 0;
365 ssize_t linelen;
366 int fd, e, res = 0;
368 if (datalen != sizeof(entry))
369 die();
370 memcpy(&entry, imsg->data, datalen);
372 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
373 if ((fd = mkstemp(sfn)) == -1 ||
374 (tmp = fdopen(fd, "w")) == NULL) {
375 if (fd != -1) {
376 unlink(sfn);
377 close(fd);
379 res = 0;
380 goto end;
383 if ((f = fopen(known_hosts_file, "r")) == NULL) {
384 unlink(sfn);
385 fclose(tmp);
386 res = 0;
387 goto end;
390 l = strlen(entry.domain);
391 while ((linelen = getline(&line, &linesize, f)) != -1) {
392 if ((t = strstr(line, entry.domain)) != NULL &&
393 (line[l] == ' ' || line[l] == '\t'))
394 continue;
395 /* line has a trailing \n */
396 fprintf(tmp, "%s", line);
398 fprintf(tmp, "%s %s %d\n", entry.domain, entry.hash, entry.verified);
400 free(line);
401 e = ferror(tmp);
403 fclose(tmp);
404 fclose(f);
406 if (e) {
407 unlink(sfn);
408 res = 0;
409 goto end;
412 res = rename(sfn, known_hosts_file) != -1;
414 end:
415 fs_send_ui(IMSG_UPDATE_CERT_OK, imsg->hdr.peerid, -1,
416 &res, sizeof(res));
419 static void
420 handle_file_open(struct imsg *imsg, size_t datalen)
422 char *path, *e;
423 int fd;
425 path = imsg->data;
426 if (path[datalen-1] != '\0')
427 die();
429 if ((fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
430 e = strerror(errno);
431 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, -1,
432 e, strlen(e)+1);
433 } else
434 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, fd,
435 NULL, 0);
438 static void
439 handle_session_start(struct imsg *imsg, size_t datalen)
441 if (datalen != 0)
442 die();
444 if ((session = fopen(session_file, "w")) == NULL)
445 die();
448 static void
449 handle_session_tab(struct imsg *imsg, size_t datalen)
451 char *url;
452 uint32_t flags;
454 if (session == NULL)
455 die();
457 flags = imsg->hdr.peerid;
458 url = imsg->data;
459 if (datalen == 0 || url[datalen-1] != '\0')
460 die();
461 fprintf(session, "%s", url);
463 if (flags & TAB_CURRENT)
464 fprintf(session, " current ");
465 else
466 fprintf(session, " - ");
469 static void
470 handle_session_tab_title(struct imsg *imsg, size_t datalen)
472 const char *title;
474 title = imsg->data;
475 if (title == NULL) {
476 datalen = 1;
477 title = "";
480 if (title[datalen-1] != '\0')
481 die();
483 fprintf(session, "%s\n", title);
486 static void
487 handle_session_end(struct imsg *imsg, size_t datalen)
489 if (session == NULL)
490 die();
491 fclose(session);
492 session = NULL;
495 static void
496 handle_dispatch_imsg(int fd, short ev, void *d)
498 struct imsgev *iev = d;
499 int e;
501 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1) {
502 /*
503 * This should leave a ~/.telescope/crashed file to
504 * trigger about:crash on next run. Unfortunately, if
505 * the main process dies the fs sticks around and
506 * doesn't notice that the fd was closed. Why EV_READ
507 * is not triggered when a fd is closed on the other end?
508 */
509 e = errno;
510 if ((fd = open(crashed_file, O_CREAT|O_TRUNC|O_WRONLY, 0600))
511 == -1)
512 err(1, "open");
513 close(fd);
514 errx(1, "connection closed: %s", strerror(e));
518 static int
519 fs_send_ui(int type, uint32_t peerid, int fd, const void *data,
520 uint16_t datalen)
522 return imsg_compose_event(iev_ui, type, peerid, 0, fd,
523 data, datalen);
526 int
527 fs_init(void)
529 strlcpy(base_path, getenv("HOME"), sizeof(base_path));
530 strlcat(base_path, "/.telescope", sizeof(base_path));
531 mkdir(base_path, 0700);
533 strlcpy(lockfile_path, base_path, sizeof(lockfile_path));
534 strlcat(lockfile_path, "/lock", sizeof(lockfile_path));
536 strlcpy(bookmark_file, base_path, sizeof(bookmark_file));
537 strlcat(bookmark_file, "/bookmarks.gmi", sizeof(bookmark_file));
539 strlcpy(known_hosts_file, base_path, sizeof(known_hosts_file));
540 strlcat(known_hosts_file, "/known_hosts", sizeof(known_hosts_file));
542 strlcpy(known_hosts_tmp, base_path, sizeof(known_hosts_tmp));
543 strlcat(known_hosts_tmp, "/known_hosts.tmp.XXXXXXXXXX",
544 sizeof(known_hosts_file));
546 strlcpy(session_file, base_path, sizeof(session_file));
547 strlcat(session_file, "/session", sizeof(session_file));
549 strlcpy(crashed_file, base_path, sizeof(crashed_file));
550 strlcat(crashed_file, "/crashed", sizeof(crashed_file));
552 return 1;
555 int
556 fs_main(void)
558 setproctitle("fs");
560 fs_init();
562 event_init();
564 /* Setup pipe and event handler to the main process */
565 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
566 die();
567 imsg_init(&iev_ui->ibuf, 3);
568 iev_ui->handler = handle_dispatch_imsg;
569 iev_ui->events = EV_READ;
570 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
571 iev_ui->handler, iev_ui);
572 event_add(&iev_ui->ev, NULL);
574 sandbox_fs_process();
576 event_dispatch();
577 return 0;
582 int
583 last_time_crashed(void)
585 int fd;
587 if ((fd = open(crashed_file, O_RDONLY)) == -1)
588 return 0;
590 close(fd);
591 unlink(crashed_file);
592 return 1;
595 int
596 lock_session(void)
598 struct flock lock;
599 int fd;
601 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
602 return -1;
604 lock.l_start = 0;
605 lock.l_len = 0;
606 lock.l_type = F_WRLCK;
607 lock.l_whence = SEEK_SET;
609 if (fcntl(fd, F_SETLK, &lock) == -1) {
610 close(fd);
611 return -1;
614 return fd;
617 static int
618 parse_khost_line(char *line, char *tmp[3])
620 char **ap;
622 for (ap = tmp; ap < &tmp[3] &&
623 (*ap = strsep(&line, " \t\n")) != NULL;) {
624 if (**ap != '\0')
625 ap++;
628 return ap == &tmp[3] && *line == '\0';
631 int
632 load_certs(struct ohash *h)
634 char *tmp[3], *line = NULL;
635 const char *errstr;
636 size_t lineno = 0, linesize = 0;
637 ssize_t linelen;
638 FILE *f;
639 struct tofu_entry *e;
641 if ((f = fopen(known_hosts_file, "r")) == NULL)
642 return 0;
644 while ((linelen = getline(&line, &linesize, f)) != -1) {
645 if ((e = calloc(1, sizeof(*e))) == NULL)
646 abort();
648 lineno++;
650 if (parse_khost_line(line, tmp)) {
651 strlcpy(e->domain, tmp[0], sizeof(e->domain));
652 strlcpy(e->hash, tmp[1], sizeof(e->hash));
654 e->verified = strtonum(tmp[2], 0, 1, &errstr);
655 if (errstr != NULL)
656 errx(1, "%s:%zu verification for %s is %s: %s",
657 known_hosts_file, lineno,
658 e->domain, errstr, tmp[2]);
659 tofu_add(h, e);
660 } else {
661 warnx("%s:%zu invalid entry",
662 known_hosts_file, lineno);
663 free(e);
667 free(line);
668 return ferror(f);