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 config and runtime files
19 */
21 #include "compat.h"
23 #include <sys/stat.h>
24 #include <sys/types.h>
26 #include <dirent.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <limits.h>
30 #include <libgen.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
36 #include "fs.h"
37 #include "pages.h"
38 #include "telescope.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);
57 static size_t join_path(char*, const char*, const char*, size_t);
58 static void getenv_default(char*, const char*, const char*, size_t);
59 static void mkdirs(const char*, mode_t);
60 static void xdg_init(void);
62 static struct imsgev *iev_ui;
63 static FILE *session;
65 /* WARNING: xdg_*_base variables are not initialized if ~/.telescope exists */
66 static char xdg_config_base[PATH_MAX];
67 static char xdg_data_base[PATH_MAX];
68 static char xdg_cache_base[PATH_MAX];
70 /* *_path_base variables are all equal to $HOME/.telescope if it exists */
71 static char config_path_base[PATH_MAX];
72 static char data_path_base[PATH_MAX];
73 static char cache_path_base[PATH_MAX];
75 char config_path[PATH_MAX];
76 static char lockfile_path[PATH_MAX];
77 static char bookmark_file[PATH_MAX];
78 static char known_hosts_file[PATH_MAX], known_hosts_tmp[PATH_MAX];
79 static char crashed_file[PATH_MAX];
81 char session_file[PATH_MAX];
83 static imsg_handlerfn *handlers[] = {
84 [IMSG_GET] = handle_get,
85 [IMSG_GET_FILE] = handle_get_file,
86 [IMSG_QUIT] = handle_quit,
87 [IMSG_BOOKMARK_PAGE] = handle_bookmark_page,
88 [IMSG_SAVE_CERT] = handle_save_cert,
89 [IMSG_UPDATE_CERT] = handle_update_cert,
90 [IMSG_FILE_OPEN] = handle_file_open,
91 [IMSG_SESSION_START] = handle_session_start,
92 [IMSG_SESSION_TAB] = handle_session_tab,
93 [IMSG_SESSION_TAB_TITLE] = handle_session_tab_title,
94 [IMSG_SESSION_END] = handle_session_end,
95 };
97 static void __attribute__((__noreturn__))
98 die(void)
99 {
100 abort(); /* TODO */
103 static void
104 send_file(uint32_t peerid, FILE *f)
106 ssize_t r;
107 char buf[BUFSIZ];
109 for (;;) {
110 r = fread(buf, 1, sizeof(buf), f);
111 if (r != 0)
112 fs_send_ui(IMSG_BUF, peerid, -1, buf, r);
113 if (r != sizeof(buf))
114 break;
116 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
117 fclose(f);
120 static void
121 handle_get(struct imsg *imsg, size_t datalen)
123 const char *bpath = "bookmarks.gmi";
124 char path[PATH_MAX];
125 FILE *f;
126 const char *data, *p;
127 size_t i;
128 struct page {
129 const char *name;
130 const char *path;
131 const uint8_t *data;
132 size_t len;
133 } pages[] = {
134 {"about", NULL, about_about, about_about_len},
135 {"blank", NULL, about_blank, about_blank_len},
136 {"bookmarks", bpath, bookmarks, bookmarks_len},
137 {"crash", NULL, about_crash, about_crash_len},
138 {"help", NULL, about_help, about_help_len},
139 {"license", NULL, about_license, about_license_len},
140 {"new", NULL, about_new, about_new_len},
141 }, *page = NULL;
143 data = imsg->data;
144 if (data[datalen-1] != '\0') /* make sure it's NUL-terminated */
145 die();
146 if ((data = strchr(data, ':')) == NULL)
147 goto notfound;
148 data++;
150 for (i = 0; i < sizeof(pages)/sizeof(pages[0]); ++i)
151 if (!strcmp(data, pages[i].name)) {
152 page = &pages[i];
153 break;
156 if (page == NULL)
157 goto notfound;
159 strlcpy(path, config_path_base, sizeof(path));
160 strlcat(path, "/", sizeof(path));
161 if (page->path != NULL)
162 strlcat(path, page->path, sizeof(path));
163 else {
164 strlcat(path, "pages/about_", sizeof(path));
165 strlcat(path, page->name, sizeof(path));
166 strlcat(path, ".gmi", sizeof(path));
169 if ((f = fopen(path, "r")) == NULL) {
170 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1,
171 page->data, page->len);
172 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1,
173 NULL, 0);
174 return;
177 send_file(imsg->hdr.peerid, f);
178 return;
180 notfound:
181 p = "# not found!\n";
182 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1, p, strlen(p));
183 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1, NULL, 0);
186 static inline void
187 send_hdr(uint32_t peerid, int code, const char *meta)
189 fs_send_ui(IMSG_GOT_CODE, peerid, -1, &code, sizeof(code));
190 fs_send_ui(IMSG_GOT_META, peerid, -1, meta, strlen(meta)+1);
193 static inline void
194 send_errno(uint32_t peerid, int code, const char *str, int no)
196 char *s;
198 if (asprintf(&s, "%s: %s", str, strerror(no)) == -1)
199 s = NULL;
201 send_hdr(peerid, code, s == NULL ? str : s);
202 free(s);
205 static inline const char *
206 file_type(const char *path)
208 struct mapping {
209 const char *ext;
210 const char *mime;
211 } ms[] = {
212 {"diff", "text/x-patch"},
213 {"gemini", "text/gemini"},
214 {"gmi", "text/gemini"},
215 {"markdown", "text/plain"},
216 {"md", "text/plain"},
217 {"patch", "text/x-patch"},
218 {"txt", "text/plain"},
219 {NULL, NULL},
220 }, *m;
221 char *dot;
223 if ((dot = strrchr(path, '.')) == NULL)
224 return NULL;
226 dot++;
228 for (m = ms; m->ext != NULL; ++m)
229 if (!strcmp(m->ext, dot))
230 return m->mime;
232 return NULL;
235 static int
236 select_non_dot(const struct dirent *d)
238 return strcmp(d->d_name, ".");
241 static int
242 select_non_dotdot(const struct dirent *d)
244 return strcmp(d->d_name, ".") && strcmp(d->d_name, "..");
247 static inline void
248 send_dir(uint32_t peerid, const char *path)
250 struct dirent **names;
251 struct evbuffer *ev;
252 char *s;
253 int (*selector)(const struct dirent *) = select_non_dot;
254 int i, len, no;
256 if (!has_suffix(path, "/")) {
257 if (asprintf(&s, "%s/", path) == -1)
258 die();
259 send_hdr(peerid, 30, s);
260 free(s);
261 return;
264 if (!strcmp(path, "/"))
265 selector = select_non_dotdot;
267 if ((ev = evbuffer_new()) == NULL ||
268 (len = scandir(path, &names, selector, alphasort)) == -1) {
269 no = errno;
270 evbuffer_free(ev);
271 send_errno(peerid, 40, "failure reading the directory", no);
272 return;
275 evbuffer_add_printf(ev, "# Index of %s\n\n", path);
276 for (i = 0; i < len; ++i) {
277 evbuffer_add_printf(ev, "=> %s", names[i]->d_name);
278 if (names[i]->d_type == DT_DIR)
279 evbuffer_add(ev, "/", 1);
280 evbuffer_add(ev, "\n", 1);
283 send_hdr(peerid, 20, "text/gemini");
284 fs_send_ui(IMSG_BUF, peerid, -1,
285 EVBUFFER_DATA(ev), EVBUFFER_LENGTH(ev));
286 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
288 evbuffer_free(ev);
289 free(names);
292 static void
293 handle_get_file(struct imsg *imsg, size_t datalen)
295 struct stat sb;
296 FILE *f;
297 char *data;
298 const char *meta = NULL;
300 data = imsg->data;
301 data[datalen-1] = '\0';
303 if ((f = fopen(data, "r")) == NULL) {
304 send_errno(imsg->hdr.peerid, 51, "can't open", errno);
305 return;
308 if (fstat(fileno(f), &sb) == -1) {
309 send_errno(imsg->hdr.peerid, 40, "fstat", errno);
310 return;
313 if (S_ISDIR(sb.st_mode)) {
314 fclose(f);
315 send_dir(imsg->hdr.peerid, data);
316 return;
319 if ((meta = file_type(data)) == NULL) {
320 fclose(f);
321 send_hdr(imsg->hdr.peerid, 51,
322 "don't know how to visualize this file");
323 return;
326 send_hdr(imsg->hdr.peerid, 20, meta);
327 send_file(imsg->hdr.peerid, f);
330 static void
331 handle_quit(struct imsg *imsg, size_t datalen)
333 if (!safe_mode)
334 unlink(crashed_file);
336 event_loopbreak();
339 static void
340 handle_bookmark_page(struct imsg *imsg, size_t datalen)
342 char *data;
343 int res;
344 FILE *f;
346 data = imsg->data;
347 if (data[datalen-1] != '\0')
348 die();
350 if ((f = fopen(bookmark_file, "a")) == NULL) {
351 res = errno;
352 goto end;
354 fprintf(f, "=> %s\n", data);
355 fclose(f);
357 res = 0;
358 end:
359 fs_send_ui(IMSG_BOOKMARK_OK, 0, -1, &res, sizeof(res));
362 static void
363 handle_save_cert(struct imsg *imsg, size_t datalen)
365 struct tofu_entry e;
366 FILE *f;
367 int res;
369 /* TODO: traverse the file to avoid duplications? */
371 if (datalen != sizeof(e))
372 die();
373 memcpy(&e, imsg->data, datalen);
375 if ((f = fopen(known_hosts_file, "a")) == NULL) {
376 res = errno;
377 goto end;
379 fprintf(f, "%s %s %d\n", e.domain, e.hash, e.verified);
380 fclose(f);
382 res = 0;
383 end:
384 fs_send_ui(IMSG_SAVE_CERT_OK, imsg->hdr.peerid, -1,
385 &res, sizeof(res));
388 static void
389 handle_update_cert(struct imsg *imsg, size_t datalen)
391 FILE *tmp, *f;
392 struct tofu_entry entry;
393 char sfn[PATH_MAX], *line = NULL, *t;
394 size_t l, linesize = 0;
395 ssize_t linelen;
396 int fd, e, res = 0;
398 if (datalen != sizeof(entry))
399 die();
400 memcpy(&entry, imsg->data, datalen);
402 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
403 if ((fd = mkstemp(sfn)) == -1 ||
404 (tmp = fdopen(fd, "w")) == NULL) {
405 if (fd != -1) {
406 unlink(sfn);
407 close(fd);
409 res = 0;
410 goto end;
413 if ((f = fopen(known_hosts_file, "r")) == NULL) {
414 unlink(sfn);
415 fclose(tmp);
416 res = 0;
417 goto end;
420 l = strlen(entry.domain);
421 while ((linelen = getline(&line, &linesize, f)) != -1) {
422 if ((t = strstr(line, entry.domain)) != NULL &&
423 (line[l] == ' ' || line[l] == '\t'))
424 continue;
425 /* line has a trailing \n */
426 fprintf(tmp, "%s", line);
428 fprintf(tmp, "%s %s %d\n", entry.domain, entry.hash, entry.verified);
430 free(line);
431 e = ferror(tmp);
433 fclose(tmp);
434 fclose(f);
436 if (e) {
437 unlink(sfn);
438 res = 0;
439 goto end;
442 res = rename(sfn, known_hosts_file) != -1;
444 end:
445 fs_send_ui(IMSG_UPDATE_CERT_OK, imsg->hdr.peerid, -1,
446 &res, sizeof(res));
449 static void
450 handle_file_open(struct imsg *imsg, size_t datalen)
452 char *path, *e;
453 int fd;
455 path = imsg->data;
456 if (path[datalen-1] != '\0')
457 die();
459 if ((fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
460 e = strerror(errno);
461 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, -1,
462 e, strlen(e)+1);
463 } else
464 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, fd,
465 NULL, 0);
468 static void
469 handle_session_start(struct imsg *imsg, size_t datalen)
471 if (datalen != 0)
472 die();
474 if ((session = fopen(session_file, "w")) == NULL)
475 die();
478 static void
479 handle_session_tab(struct imsg *imsg, size_t datalen)
481 char *url;
482 uint32_t flags;
484 if (session == NULL)
485 die();
487 flags = imsg->hdr.peerid;
488 url = imsg->data;
489 if (datalen == 0 || url[datalen-1] != '\0')
490 die();
491 fprintf(session, "%s", url);
493 if (flags & TAB_CURRENT)
494 fprintf(session, " current ");
495 else
496 fprintf(session, " - ");
499 static void
500 handle_session_tab_title(struct imsg *imsg, size_t datalen)
502 const char *title;
504 title = imsg->data;
505 if (title == NULL) {
506 datalen = 1;
507 title = "";
510 if (title[datalen-1] != '\0')
511 die();
513 fprintf(session, "%s\n", title);
516 static void
517 handle_session_end(struct imsg *imsg, size_t datalen)
519 if (session == NULL)
520 die();
521 fclose(session);
522 session = NULL;
525 static void
526 handle_dispatch_imsg(int fd, short ev, void *d)
528 struct imsgev *iev = d;
529 int e;
531 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1) {
532 /*
533 * This should leave a ~/.cache/telescope/crashed file to
534 * trigger about:crash on next run. Unfortunately, if
535 * the main process dies the fs sticks around and
536 * doesn't notice that the fd was closed. Why EV_READ
537 * is not triggered when a fd is closed on the other end?
538 */
539 e = errno;
540 if ((fd = open(crashed_file, O_CREAT|O_TRUNC|O_WRONLY, 0600))
541 == -1)
542 err(1, "open");
543 close(fd);
544 errx(1, "connection closed: %s", strerror(e));
548 static int
549 fs_send_ui(int type, uint32_t peerid, int fd, const void *data,
550 uint16_t datalen)
552 return imsg_compose_event(iev_ui, type, peerid, 0, fd,
553 data, datalen);
556 static size_t
557 join_path(char *buf, const char *lhs, const char *rhs, size_t buflen)
559 strlcpy(buf, lhs, buflen);
560 return strlcat(buf, rhs, buflen);
563 static void
564 getenv_default(char *buf, const char *name, const char *def, size_t buflen)
566 size_t ret;
567 char *home, *env;
569 if ((home = getenv("HOME")) == NULL)
570 errx(1, "HOME is not defined");
572 if ((env = getenv(name)) != NULL)
573 ret = strlcpy(buf, env, buflen);
574 else
575 ret = join_path(buf, home, def, buflen);
577 if (ret >= buflen)
578 errx(1, "buffer too small for %s", name);
581 static void
582 mkdirs(const char *path, mode_t mode)
584 char copy[PATH_MAX+1], *parent;
586 strlcpy(copy, path, sizeof(copy));
587 parent = dirname(copy);
588 if (!strcmp(parent, "/"))
589 return;
590 mkdirs(parent, mode);
592 if (mkdir(path, mode) != 0) {
593 if (errno == EEXIST)
594 return;
595 err(1, "can't mkdir %s", path);
599 static void
600 xdg_init(void)
602 char *home, old_path[PATH_MAX];
603 struct stat info;
605 /* old path */
606 if ((home = getenv("HOME")) == NULL)
607 errx(1, "HOME is not defined");
608 join_path(old_path, home, "/.telescope", sizeof(old_path));
610 /* if ~/.telescope exists, use that instead of xdg dirs */
611 if (stat(old_path, &info) == 0 && S_ISDIR(info.st_mode)) {
612 join_path(config_path_base, home, "/.telescope",
613 sizeof(config_path_base));
614 join_path(data_path_base, home, "/.telescope",
615 sizeof(data_path_base));
616 join_path(cache_path_base, home, "/.telescope",
617 sizeof(cache_path_base));
618 return;
621 /* xdg paths */
622 getenv_default(xdg_config_base, "XDG_CONFIG_HOME", "/.config",
623 sizeof(xdg_config_base));
624 getenv_default(xdg_data_base, "XDG_DATA_HOME", "/.local/share",
625 sizeof(xdg_data_base));
626 getenv_default(xdg_cache_base, "XDG_CACHE_HOME", "/.cache",
627 sizeof(xdg_cache_base));
629 join_path(config_path_base, xdg_config_base, "/telescope",
630 sizeof(config_path_base));
631 join_path(data_path_base, xdg_data_base, "/telescope",
632 sizeof(data_path_base));
633 join_path(cache_path_base, xdg_cache_base, "/telescope",
634 sizeof(cache_path_base));
636 mkdirs(xdg_config_base, S_IRWXU);
637 mkdirs(xdg_data_base, S_IRWXU);
638 mkdirs(xdg_cache_base, S_IRWXU);
640 mkdirs(config_path_base, S_IRWXU);
641 mkdirs(data_path_base, S_IRWXU);
642 mkdirs(cache_path_base, S_IRWXU);
645 int
646 fs_init(void)
648 xdg_init();
650 join_path(config_path, config_path_base, "/config",
651 sizeof(config_path));
652 join_path(lockfile_path, cache_path_base, "/lock",
653 sizeof(lockfile_path));
654 join_path(bookmark_file, data_path_base, "/bookmarks.gmi",
655 sizeof(bookmark_file));
656 join_path(known_hosts_file, data_path_base, "/known_hosts",
657 sizeof(known_hosts_file));
658 join_path(known_hosts_tmp, cache_path_base,
659 "/known_hosts.tmp.XXXXXXXXXX", sizeof(known_hosts_tmp));
660 join_path(session_file, cache_path_base, "/session",
661 sizeof(session_file));
662 join_path(crashed_file, cache_path_base, "/crashed",
663 sizeof(crashed_file));
665 return 1;
668 int
669 fs_main(void)
671 setproctitle("fs");
673 fs_init();
675 event_init();
677 /* Setup pipe and event handler to the main process */
678 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
679 die();
680 imsg_init(&iev_ui->ibuf, 3);
681 iev_ui->handler = handle_dispatch_imsg;
682 iev_ui->events = EV_READ;
683 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
684 iev_ui->handler, iev_ui);
685 event_add(&iev_ui->ev, NULL);
687 sandbox_fs_process();
689 event_dispatch();
690 return 0;
695 /*
696 * Check if the last time telescope crashed. The check is done by
697 * looking at `crashed_file': if it exists then last time we crashed.
698 * Then, while here, touch the file too. During IMSG_QUIT we'll
699 * remove it.
700 */
701 int
702 last_time_crashed(void)
704 int fd, crashed = 1;
706 if (safe_mode)
707 return 0;
709 if (unlink(crashed_file) == -1 && errno == ENOENT)
710 crashed = 0;
712 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
713 return crashed;
714 close(fd);
716 return crashed;
719 int
720 lock_session(void)
722 struct flock lock;
723 int fd;
725 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
726 return -1;
728 lock.l_start = 0;
729 lock.l_len = 0;
730 lock.l_type = F_WRLCK;
731 lock.l_whence = SEEK_SET;
733 if (fcntl(fd, F_SETLK, &lock) == -1) {
734 close(fd);
735 return -1;
738 return fd;
741 static int
742 parse_khost_line(char *line, char *tmp[3])
744 char **ap;
746 for (ap = tmp; ap < &tmp[3] &&
747 (*ap = strsep(&line, " \t\n")) != NULL;) {
748 if (**ap != '\0')
749 ap++;
752 return ap == &tmp[3] && *line == '\0';
755 int
756 load_certs(struct ohash *h)
758 char *tmp[3], *line = NULL;
759 const char *errstr;
760 size_t lineno = 0, linesize = 0;
761 ssize_t linelen;
762 FILE *f;
763 struct tofu_entry *e;
765 if ((f = fopen(known_hosts_file, "r")) == NULL)
766 return 0;
768 while ((linelen = getline(&line, &linesize, f)) != -1) {
769 if ((e = calloc(1, sizeof(*e))) == NULL)
770 abort();
772 lineno++;
774 if (parse_khost_line(line, tmp)) {
775 strlcpy(e->domain, tmp[0], sizeof(e->domain));
776 strlcpy(e->hash, tmp[1], sizeof(e->hash));
778 e->verified = strtonum(tmp[2], 0, 1, &errstr);
779 if (errstr != NULL)
780 errx(1, "%s:%zu verification for %s is %s: %s",
781 known_hosts_file, lineno,
782 e->domain, errstr, tmp[2]);
783 tofu_add(h, e);
784 } else {
785 warnx("%s:%zu invalid entry",
786 known_hosts_file, lineno);
787 free(e);
791 free(line);
792 return ferror(f);