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.
18 * Handles config and runtime files
24 #include <sys/types.h>
38 #include "telescope.h"
42 static void die(void) __attribute__((__noreturn__));
43 static void send_file(uint32_t, FILE *);
44 static void handle_get(struct imsg*, size_t);
45 static int select_non_dot(const struct dirent *);
46 static int select_non_dotdot(const struct dirent *);
47 static void handle_get_file(struct imsg*, size_t);
48 static void handle_misc(struct imsg *, size_t);
49 static void handle_bookmark_page(struct imsg*, size_t);
50 static void handle_save_cert(struct imsg*, size_t);
51 static void handle_update_cert(struct imsg*, size_t);
52 static void handle_file_open(struct imsg*, size_t);
53 static void handle_session_start(struct imsg*, size_t);
54 static void handle_session_tab(struct imsg*, size_t);
55 static void handle_session_tab_hist(struct imsg*, size_t);
56 static void handle_session_end(struct imsg*, size_t);
57 static void handle_dispatch_imsg(int, short, void*);
58 static int fs_send_ui(int, uint32_t, int, const void *, uint16_t);
59 static size_t join_path(char*, const char*, const char*, size_t);
60 static void getenv_default(char*, const char*, const char*, size_t);
61 static void mkdirs(const char*, mode_t);
62 static void init_paths(void);
63 static void load_last_session(void);
64 static int last_time_crashed(void);
65 static void load_certs(void);
67 static struct imsgev *iev_ui;
71 * Where to store user data. These are all equal to ~/.telescope if
74 char config_path_base[PATH_MAX];
75 char data_path_base[PATH_MAX];
76 char cache_path_base[PATH_MAX];
78 char config_path[PATH_MAX];
79 char lockfile_path[PATH_MAX];
80 char bookmark_file[PATH_MAX];
81 char known_hosts_file[PATH_MAX], known_hosts_tmp[PATH_MAX];
82 char crashed_file[PATH_MAX];
83 char session_file[PATH_MAX];
85 static imsg_handlerfn *handlers[] = {
86 [IMSG_GET] = handle_get,
87 [IMSG_GET_FILE] = handle_get_file,
88 [IMSG_QUIT] = handle_misc,
89 [IMSG_INIT] = handle_misc,
90 [IMSG_BOOKMARK_PAGE] = handle_bookmark_page,
91 [IMSG_SAVE_CERT] = handle_save_cert,
92 [IMSG_UPDATE_CERT] = handle_update_cert,
93 [IMSG_FILE_OPEN] = handle_file_open,
94 [IMSG_SESSION_START] = handle_session_start,
95 [IMSG_SESSION_TAB] = handle_session_tab,
96 [IMSG_SESSION_TAB_HIST] = handle_session_tab_hist,
97 [IMSG_SESSION_END] = handle_session_end,
100 static void __attribute__((__noreturn__))
107 send_file(uint32_t peerid, FILE *f)
113 r = fread(buf, 1, sizeof(buf), f);
115 fs_send_ui(IMSG_BUF, peerid, -1, buf, r);
116 if (r != sizeof(buf))
119 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
124 handle_get(struct imsg *imsg, size_t datalen)
126 const char *bpath = "bookmarks.gmi";
129 const char *data, *p;
137 {"about", NULL, about_about, about_about_len},
138 {"blank", NULL, about_blank, about_blank_len},
139 {"bookmarks", bpath, bookmarks, bookmarks_len},
140 {"crash", NULL, about_crash, about_crash_len},
141 {"help", NULL, about_help, about_help_len},
142 {"license", NULL, about_license, about_license_len},
143 {"new", NULL, about_new, about_new_len},
147 if (data[datalen-1] != '\0') /* make sure it's NUL-terminated */
149 if ((data = strchr(data, ':')) == NULL)
153 for (i = 0; i < sizeof(pages)/sizeof(pages[0]); ++i)
154 if (!strcmp(data, pages[i].name)) {
162 strlcpy(path, data_path_base, sizeof(path));
163 strlcat(path, "/", sizeof(path));
164 if (page->path != NULL)
165 strlcat(path, page->path, sizeof(path));
167 strlcat(path, "pages/about_", sizeof(path));
168 strlcat(path, page->name, sizeof(path));
169 strlcat(path, ".gmi", sizeof(path));
172 if ((f = fopen(path, "r")) == NULL) {
173 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1,
174 page->data, page->len);
175 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1,
180 send_file(imsg->hdr.peerid, f);
184 p = "# not found!\n";
185 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1, p, strlen(p));
186 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1, NULL, 0);
190 send_hdr(uint32_t peerid, int code, const char *meta)
192 fs_send_ui(IMSG_GOT_CODE, peerid, -1, &code, sizeof(code));
193 fs_send_ui(IMSG_GOT_META, peerid, -1, meta, strlen(meta)+1);
197 send_errno(uint32_t peerid, int code, const char *str, int no)
201 if (asprintf(&s, "%s: %s", str, strerror(no)) == -1)
204 send_hdr(peerid, code, s == NULL ? str : s);
208 static inline const char *
209 file_type(const char *path)
215 {"diff", "text/x-patch"},
216 {"gemini", "text/gemini"},
217 {"gmi", "text/gemini"},
218 {"markdown", "text/plain"},
219 {"md", "text/plain"},
220 {"patch", "text/x-patch"},
221 {"txt", "text/plain"},
226 if ((dot = strrchr(path, '.')) == NULL)
231 for (m = ms; m->ext != NULL; ++m)
232 if (!strcmp(m->ext, dot))
239 select_non_dot(const struct dirent *d)
241 return strcmp(d->d_name, ".");
245 select_non_dotdot(const struct dirent *d)
247 return strcmp(d->d_name, ".") && strcmp(d->d_name, "..");
251 send_dir(uint32_t peerid, const char *path)
253 struct dirent **names;
256 int (*selector)(const struct dirent *) = select_non_dot;
259 if (!has_suffix(path, "/")) {
260 if (asprintf(&s, "%s/", path) == -1)
262 send_hdr(peerid, 30, s);
267 if (!strcmp(path, "/"))
268 selector = select_non_dotdot;
270 if ((ev = evbuffer_new()) == NULL ||
271 (len = scandir(path, &names, selector, alphasort)) == -1) {
274 send_errno(peerid, 40, "failure reading the directory", no);
278 evbuffer_add_printf(ev, "# Index of %s\n\n", path);
279 for (i = 0; i < len; ++i) {
280 evbuffer_add_printf(ev, "=> %s", names[i]->d_name);
281 if (names[i]->d_type == DT_DIR)
282 evbuffer_add(ev, "/", 1);
283 evbuffer_add(ev, "\n", 1);
286 send_hdr(peerid, 20, "text/gemini");
287 fs_send_ui(IMSG_BUF, peerid, -1,
288 EVBUFFER_DATA(ev), EVBUFFER_LENGTH(ev));
289 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
296 handle_get_file(struct imsg *imsg, size_t datalen)
301 const char *meta = NULL;
304 data[datalen-1] = '\0';
306 if ((f = fopen(data, "r")) == NULL) {
307 send_errno(imsg->hdr.peerid, 51, "can't open", errno);
311 if (fstat(fileno(f), &sb) == -1) {
312 send_errno(imsg->hdr.peerid, 40, "fstat", errno);
316 if (S_ISDIR(sb.st_mode)) {
318 send_dir(imsg->hdr.peerid, data);
322 if ((meta = file_type(data)) == NULL) {
324 send_hdr(imsg->hdr.peerid, 51,
325 "don't know how to visualize this file");
329 send_hdr(imsg->hdr.peerid, 20, meta);
330 send_file(imsg->hdr.peerid, f);
334 handle_misc(struct imsg *imsg, size_t datalen)
336 switch (imsg->hdr.type) {
344 unlink(crashed_file);
354 handle_bookmark_page(struct imsg *imsg, size_t datalen)
361 if (data[datalen-1] != '\0')
364 if ((f = fopen(bookmark_file, "a")) == NULL) {
368 fprintf(f, "=> %s\n", data);
373 fs_send_ui(IMSG_BOOKMARK_OK, 0, -1, &res, sizeof(res));
377 handle_save_cert(struct imsg *imsg, size_t datalen)
383 /* TODO: traverse the file to avoid duplications? */
385 if (datalen != sizeof(e))
387 memcpy(&e, imsg->data, datalen);
389 if ((f = fopen(known_hosts_file, "a")) == NULL) {
393 fprintf(f, "%s %s %d\n", e.domain, e.hash, e.verified);
398 fs_send_ui(IMSG_SAVE_CERT_OK, imsg->hdr.peerid, -1,
403 handle_update_cert(struct imsg *imsg, size_t datalen)
406 struct tofu_entry entry;
407 char sfn[PATH_MAX], *line = NULL, *t;
408 size_t l, linesize = 0;
412 if (datalen != sizeof(entry))
414 memcpy(&entry, imsg->data, datalen);
416 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
417 if ((fd = mkstemp(sfn)) == -1 ||
418 (tmp = fdopen(fd, "w")) == NULL) {
427 if ((f = fopen(known_hosts_file, "r")) == NULL) {
434 l = strlen(entry.domain);
435 while ((linelen = getline(&line, &linesize, f)) != -1) {
436 if ((t = strstr(line, entry.domain)) != NULL &&
437 (line[l] == ' ' || line[l] == '\t'))
439 /* line has a trailing \n */
440 fprintf(tmp, "%s", line);
442 fprintf(tmp, "%s %s %d\n", entry.domain, entry.hash, entry.verified);
456 res = rename(sfn, known_hosts_file) != -1;
459 fs_send_ui(IMSG_UPDATE_CERT_OK, imsg->hdr.peerid, -1,
464 handle_file_open(struct imsg *imsg, size_t datalen)
470 if (path[datalen-1] != '\0')
473 if ((fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
475 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, -1,
478 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, fd,
483 handle_session_start(struct imsg *imsg, size_t datalen)
488 if ((session = fopen(session_file, "w")) == NULL)
493 handle_session_tab(struct imsg *imsg, size_t datalen)
495 struct session_tab tab;
500 if (datalen != sizeof(tab))
503 memcpy(&tab, imsg->data, sizeof(tab));
504 if (tab.uri[sizeof(tab.uri)-1] != '\0' ||
505 tab.title[sizeof(tab.title)-1] != '\0')
508 fprintf(session, "%s ", tab.uri);
510 if (tab.flags & TAB_CURRENT)
511 fprintf(session, "current,");
512 if (tab.flags & TAB_KILLED)
513 fprintf(session, "killed,");
515 fprintf(session, "top=%zu,cur=%zu %s\n", tab.top_line,
516 tab.current_line, tab.title);
520 handle_session_tab_hist(struct imsg *imsg, size_t datalen)
522 struct session_tab_hist th;
527 if (datalen != sizeof(th))
530 memcpy(&th, imsg->data, sizeof(th));
531 if (th.uri[sizeof(th.uri)-1] != '\0')
534 fprintf(session, "%s %s\n", th.future ? ">" : "<", th.uri);
538 handle_session_end(struct imsg *imsg, size_t datalen)
547 handle_dispatch_imsg(int fd, short ev, void *d)
549 struct imsgev *iev = d;
552 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1) {
554 * This should leave a ~/.cache/telescope/crashed file to
555 * trigger about:crash on next run. Unfortunately, if
556 * the main process dies the fs sticks around and
557 * doesn't notice that the fd was closed. Why EV_READ
558 * is not triggered when a fd is closed on the other end?
561 if ((fd = open(crashed_file, O_CREAT|O_TRUNC|O_WRONLY, 0600))
565 errx(1, "connection closed: %s", strerror(e));
570 fs_send_ui(int type, uint32_t peerid, int fd, const void *data,
573 return imsg_compose_event(iev_ui, type, peerid, 0, fd,
578 join_path(char *buf, const char *lhs, const char *rhs, size_t buflen)
580 strlcpy(buf, lhs, buflen);
581 return strlcat(buf, rhs, buflen);
585 getenv_default(char *buf, const char *name, const char *def, size_t buflen)
590 if ((home = getenv("HOME")) == NULL)
591 errx(1, "HOME is not defined");
593 if ((env = getenv(name)) != NULL)
594 ret = strlcpy(buf, env, buflen);
596 ret = join_path(buf, home, def, buflen);
599 errx(1, "buffer too small for %s", name);
603 mkdirs(const char *path, mode_t mode)
605 char copy[PATH_MAX+1], orig[PATH_MAX+1], *parent;
607 strlcpy(copy, path, sizeof(copy));
608 strlcpy(orig, path, sizeof(orig));
609 parent = dirname(copy);
610 if (!strcmp(parent, "/"))
612 mkdirs(parent, mode);
614 if (mkdir(orig, mode) != 0) {
617 err(1, "can't mkdir %s", orig);
624 char xdg_config_base[PATH_MAX];
625 char xdg_data_base[PATH_MAX];
626 char xdg_cache_base[PATH_MAX];
627 char old_path[PATH_MAX];
632 if ((home = getenv("HOME")) == NULL)
633 errx(1, "HOME is not defined");
634 join_path(old_path, home, "/.telescope", sizeof(old_path));
636 /* if ~/.telescope exists, use that instead of xdg dirs */
637 if (stat(old_path, &info) == 0 && S_ISDIR(info.st_mode)) {
638 join_path(config_path_base, home, "/.telescope",
639 sizeof(config_path_base));
640 join_path(data_path_base, home, "/.telescope",
641 sizeof(data_path_base));
642 join_path(cache_path_base, home, "/.telescope",
643 sizeof(cache_path_base));
648 getenv_default(xdg_config_base, "XDG_CONFIG_HOME", "/.config",
649 sizeof(xdg_config_base));
650 getenv_default(xdg_data_base, "XDG_DATA_HOME", "/.local/share",
651 sizeof(xdg_data_base));
652 getenv_default(xdg_cache_base, "XDG_CACHE_HOME", "/.cache",
653 sizeof(xdg_cache_base));
655 join_path(config_path_base, xdg_config_base, "/telescope",
656 sizeof(config_path_base));
657 join_path(data_path_base, xdg_data_base, "/telescope",
658 sizeof(data_path_base));
659 join_path(cache_path_base, xdg_cache_base, "/telescope",
660 sizeof(cache_path_base));
662 mkdirs(xdg_config_base, S_IRWXU);
663 mkdirs(xdg_data_base, S_IRWXU);
664 mkdirs(xdg_cache_base, S_IRWXU);
666 mkdirs(config_path_base, S_IRWXU);
667 mkdirs(data_path_base, S_IRWXU);
668 mkdirs(cache_path_base, S_IRWXU);
676 join_path(config_path, config_path_base, "/config",
677 sizeof(config_path));
678 join_path(lockfile_path, cache_path_base, "/lock",
679 sizeof(lockfile_path));
680 join_path(bookmark_file, data_path_base, "/bookmarks.gmi",
681 sizeof(bookmark_file));
682 join_path(known_hosts_file, data_path_base, "/known_hosts",
683 sizeof(known_hosts_file));
684 join_path(known_hosts_tmp, cache_path_base,
685 "/known_hosts.tmp.XXXXXXXXXX", sizeof(known_hosts_tmp));
686 join_path(session_file, cache_path_base, "/session",
687 sizeof(session_file));
688 join_path(crashed_file, cache_path_base, "/crashed",
689 sizeof(crashed_file));
695 * Parse a line of the session file. The format is:
697 * URL [flags,...] [title]\n
700 parse_session_line(char *line)
702 struct session_tab tab;
705 memset(&tab, 0, sizeof(tab));
707 if ((s = strchr(line, ' ')) == NULL)
712 if (strlcpy(tab.uri, line, sizeof(tab.uri)) >= sizeof(tab.uri))
715 if ((t = strchr(s, ' ')) != NULL) {
718 /* don't worry about cached title truncation */
719 strlcpy(tab.title, t, sizeof(tab.title));
722 while ((ap = strsep(&s, ",")) != NULL) {
723 if (!strcmp(ap, "current"))
724 tab.flags |= TAB_CURRENT;
725 else if (!strcmp(ap, "killed"))
726 tab.flags |= TAB_KILLED;
727 else if (has_prefix(ap, "top="))
728 tab.top_line = strtonum(ap+4, 0, UINT32_MAX, NULL);
729 else if (has_prefix(ap, "cur="))
730 tab.current_line = strtonum(ap+4, 0, UINT32_MAX, NULL);
733 if (tab.top_line > tab.current_line) {
735 tab.current_line = 0;
738 fs_send_ui(IMSG_SESSION_TAB, 0, -1, &tab, sizeof(tab));
742 sendhist(const char *uri, int future)
744 struct session_tab_hist sth;
746 memset(&sth, 0, sizeof(sth));
749 if (strlcpy(sth.uri, uri, sizeof(sth.uri)) >= sizeof(sth.uri))
752 fs_send_ui(IMSG_SESSION_TAB_HIST, 0, -1, &sth, sizeof(sth));
756 load_last_session(void)
763 char *nl, *s, *line = NULL;
765 if ((session = fopen(session_file, "r")) == NULL) {
771 while ((linelen = getline(&line, &linesize, session)) != -1) {
772 if ((nl = strchr(line, '\n')) != NULL)
775 if (*line == '<' || *line == '>') {
776 future = *line == '>';
780 sendhist(++s, future);
782 parse_session_line(line);
789 if (last_time_crashed()) {
790 struct session_tab tab;
791 memset(&tab, 0, sizeof(tab));
792 tab.flags = TAB_CURRENT;
793 strlcpy(tab.uri, "about:crash", sizeof(tab.uri));
794 fs_send_ui(IMSG_SESSION_TAB, 0, -1, &tab, sizeof(tab));
798 fs_send_ui(IMSG_SESSION_END, 0, -1, &first_time, sizeof(first_time));
810 /* Setup pipe and event handler to the main process */
811 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
813 imsg_init(&iev_ui->ibuf, 3);
814 iev_ui->handler = handle_dispatch_imsg;
815 iev_ui->events = EV_READ;
816 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
817 iev_ui->handler, iev_ui);
818 event_add(&iev_ui->ev, NULL);
820 sandbox_fs_process();
827 * Check if the last time telescope crashed. The check is done by
828 * looking at `crashed_file': if it exists then last time we crashed.
829 * Then, while here, touch the file too. During IMSG_QUIT we'll
833 last_time_crashed(void)
840 if (unlink(crashed_file) == -1 && errno == ENOENT)
843 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
856 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
861 lock.l_type = F_WRLCK;
862 lock.l_whence = SEEK_SET;
864 if (fcntl(fd, F_SETLK, &lock) == -1) {
873 parse_khost_line(char *line, char *tmp[3])
877 for (ap = tmp; ap < &tmp[3] &&
878 (*ap = strsep(&line, " \t\n")) != NULL;) {
883 return ap == &tmp[3] && *line == '\0';
889 char *tmp[3], *line = NULL;
891 size_t lineno = 0, linesize = 0;
896 if ((f = fopen(known_hosts_file, "r")) == NULL)
899 while ((linelen = getline(&line, &linesize, f)) != -1) {
902 memset(&e, 0, sizeof(e));
903 if (parse_khost_line(line, tmp)) {
904 strlcpy(e.domain, tmp[0], sizeof(e.domain));
905 strlcpy(e.hash, tmp[1], sizeof(e.hash));
907 e.verified = strtonum(tmp[2], 0, 1, &errstr);
909 errx(1, "%s:%zu verification for %s is %s: %s",
910 known_hosts_file, lineno,
911 e.domain, errstr, tmp[2]);
913 fs_send_ui(IMSG_TOFU, 0, -1, &e, sizeof(e));
915 warnx("%s:%zu invalid entry",
916 known_hosts_file, lineno);