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"
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_misc(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_hist(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);
61 static void load_last_session(void);
62 static void load_certs(void);
64 static struct imsgev *iev_ui;
68 * Note: these are empty if ~/.telescope exists, use *_path_base
71 static char xdg_config_base[PATH_MAX];
72 static char xdg_data_base[PATH_MAX];
73 static char xdg_cache_base[PATH_MAX];
76 * Where to store user data. These are all equal to ~/.telescope if
79 char config_path_base[PATH_MAX];
80 char data_path_base[PATH_MAX];
81 char cache_path_base[PATH_MAX];
83 char config_path[PATH_MAX];
84 char lockfile_path[PATH_MAX];
85 char bookmark_file[PATH_MAX];
86 char known_hosts_file[PATH_MAX], known_hosts_tmp[PATH_MAX];
87 char crashed_file[PATH_MAX];
88 char session_file[PATH_MAX];
90 static imsg_handlerfn *handlers[] = {
91 [IMSG_GET] = handle_get,
92 [IMSG_GET_FILE] = handle_get_file,
93 [IMSG_QUIT] = handle_misc,
94 [IMSG_INIT] = handle_misc,
95 [IMSG_BOOKMARK_PAGE] = handle_bookmark_page,
96 [IMSG_SAVE_CERT] = handle_save_cert,
97 [IMSG_UPDATE_CERT] = handle_update_cert,
98 [IMSG_FILE_OPEN] = handle_file_open,
99 [IMSG_SESSION_START] = handle_session_start,
100 [IMSG_SESSION_TAB] = handle_session_tab,
101 [IMSG_SESSION_TAB_HIST] = handle_session_tab_hist,
102 [IMSG_SESSION_END] = handle_session_end,
105 static void __attribute__((__noreturn__))
112 send_file(uint32_t peerid, FILE *f)
118 r = fread(buf, 1, sizeof(buf), f);
120 fs_send_ui(IMSG_BUF, peerid, -1, buf, r);
121 if (r != sizeof(buf))
124 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
129 handle_get(struct imsg *imsg, size_t datalen)
131 const char *bpath = "bookmarks.gmi";
134 const char *data, *p;
142 {"about", NULL, about_about, about_about_len},
143 {"blank", NULL, about_blank, about_blank_len},
144 {"bookmarks", bpath, bookmarks, bookmarks_len},
145 {"crash", NULL, about_crash, about_crash_len},
146 {"help", NULL, about_help, about_help_len},
147 {"license", NULL, about_license, about_license_len},
148 {"new", NULL, about_new, about_new_len},
152 if (data[datalen-1] != '\0') /* make sure it's NUL-terminated */
154 if ((data = strchr(data, ':')) == NULL)
158 for (i = 0; i < sizeof(pages)/sizeof(pages[0]); ++i)
159 if (!strcmp(data, pages[i].name)) {
167 strlcpy(path, data_path_base, sizeof(path));
168 strlcat(path, "/", sizeof(path));
169 if (page->path != NULL)
170 strlcat(path, page->path, sizeof(path));
172 strlcat(path, "pages/about_", sizeof(path));
173 strlcat(path, page->name, sizeof(path));
174 strlcat(path, ".gmi", sizeof(path));
177 if ((f = fopen(path, "r")) == NULL) {
178 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1,
179 page->data, page->len);
180 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1,
185 send_file(imsg->hdr.peerid, f);
189 p = "# not found!\n";
190 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1, p, strlen(p));
191 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1, NULL, 0);
195 send_hdr(uint32_t peerid, int code, const char *meta)
197 fs_send_ui(IMSG_GOT_CODE, peerid, -1, &code, sizeof(code));
198 fs_send_ui(IMSG_GOT_META, peerid, -1, meta, strlen(meta)+1);
202 send_errno(uint32_t peerid, int code, const char *str, int no)
206 if (asprintf(&s, "%s: %s", str, strerror(no)) == -1)
209 send_hdr(peerid, code, s == NULL ? str : s);
213 static inline const char *
214 file_type(const char *path)
220 {"diff", "text/x-patch"},
221 {"gemini", "text/gemini"},
222 {"gmi", "text/gemini"},
223 {"markdown", "text/plain"},
224 {"md", "text/plain"},
225 {"patch", "text/x-patch"},
226 {"txt", "text/plain"},
231 if ((dot = strrchr(path, '.')) == NULL)
236 for (m = ms; m->ext != NULL; ++m)
237 if (!strcmp(m->ext, dot))
244 select_non_dot(const struct dirent *d)
246 return strcmp(d->d_name, ".");
250 select_non_dotdot(const struct dirent *d)
252 return strcmp(d->d_name, ".") && strcmp(d->d_name, "..");
256 send_dir(uint32_t peerid, const char *path)
258 struct dirent **names;
261 int (*selector)(const struct dirent *) = select_non_dot;
264 if (!has_suffix(path, "/")) {
265 if (asprintf(&s, "%s/", path) == -1)
267 send_hdr(peerid, 30, s);
272 if (!strcmp(path, "/"))
273 selector = select_non_dotdot;
275 if ((ev = evbuffer_new()) == NULL ||
276 (len = scandir(path, &names, selector, alphasort)) == -1) {
279 send_errno(peerid, 40, "failure reading the directory", no);
283 evbuffer_add_printf(ev, "# Index of %s\n\n", path);
284 for (i = 0; i < len; ++i) {
285 evbuffer_add_printf(ev, "=> %s", names[i]->d_name);
286 if (names[i]->d_type == DT_DIR)
287 evbuffer_add(ev, "/", 1);
288 evbuffer_add(ev, "\n", 1);
291 send_hdr(peerid, 20, "text/gemini");
292 fs_send_ui(IMSG_BUF, peerid, -1,
293 EVBUFFER_DATA(ev), EVBUFFER_LENGTH(ev));
294 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
301 handle_get_file(struct imsg *imsg, size_t datalen)
306 const char *meta = NULL;
309 data[datalen-1] = '\0';
311 if ((f = fopen(data, "r")) == NULL) {
312 send_errno(imsg->hdr.peerid, 51, "can't open", errno);
316 if (fstat(fileno(f), &sb) == -1) {
317 send_errno(imsg->hdr.peerid, 40, "fstat", errno);
321 if (S_ISDIR(sb.st_mode)) {
323 send_dir(imsg->hdr.peerid, data);
327 if ((meta = file_type(data)) == NULL) {
329 send_hdr(imsg->hdr.peerid, 51,
330 "don't know how to visualize this file");
334 send_hdr(imsg->hdr.peerid, 20, meta);
335 send_file(imsg->hdr.peerid, f);
339 handle_misc(struct imsg *imsg, size_t datalen)
341 switch (imsg->hdr.type) {
349 unlink(crashed_file);
359 handle_bookmark_page(struct imsg *imsg, size_t datalen)
366 if (data[datalen-1] != '\0')
369 if ((f = fopen(bookmark_file, "a")) == NULL) {
373 fprintf(f, "=> %s\n", data);
378 fs_send_ui(IMSG_BOOKMARK_OK, 0, -1, &res, sizeof(res));
382 handle_save_cert(struct imsg *imsg, size_t datalen)
388 /* TODO: traverse the file to avoid duplications? */
390 if (datalen != sizeof(e))
392 memcpy(&e, imsg->data, datalen);
394 if ((f = fopen(known_hosts_file, "a")) == NULL) {
398 fprintf(f, "%s %s %d\n", e.domain, e.hash, e.verified);
403 fs_send_ui(IMSG_SAVE_CERT_OK, imsg->hdr.peerid, -1,
408 handle_update_cert(struct imsg *imsg, size_t datalen)
411 struct tofu_entry entry;
412 char sfn[PATH_MAX], *line = NULL, *t;
413 size_t l, linesize = 0;
417 if (datalen != sizeof(entry))
419 memcpy(&entry, imsg->data, datalen);
421 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
422 if ((fd = mkstemp(sfn)) == -1 ||
423 (tmp = fdopen(fd, "w")) == NULL) {
432 if ((f = fopen(known_hosts_file, "r")) == NULL) {
439 l = strlen(entry.domain);
440 while ((linelen = getline(&line, &linesize, f)) != -1) {
441 if ((t = strstr(line, entry.domain)) != NULL &&
442 (line[l] == ' ' || line[l] == '\t'))
444 /* line has a trailing \n */
445 fprintf(tmp, "%s", line);
447 fprintf(tmp, "%s %s %d\n", entry.domain, entry.hash, entry.verified);
461 res = rename(sfn, known_hosts_file) != -1;
464 fs_send_ui(IMSG_UPDATE_CERT_OK, imsg->hdr.peerid, -1,
469 handle_file_open(struct imsg *imsg, size_t datalen)
475 if (path[datalen-1] != '\0')
478 if ((fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
480 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, -1,
483 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, fd,
488 handle_session_start(struct imsg *imsg, size_t datalen)
493 if ((session = fopen(session_file, "w")) == NULL)
498 handle_session_tab(struct imsg *imsg, size_t datalen)
500 struct session_tab tab;
505 if (datalen != sizeof(tab))
508 memcpy(&tab, imsg->data, sizeof(tab));
509 if (tab.uri[sizeof(tab.uri)-1] != '\0' ||
510 tab.title[sizeof(tab.title)-1] != '\0')
513 fprintf(session, "%s", tab.uri);
515 if (tab.flags & TAB_CURRENT)
516 fprintf(session, " current ");
518 fprintf(session, " - ");
520 fprintf(session, "%s\n", tab.title);
524 handle_session_tab_hist(struct imsg *imsg, size_t datalen)
526 struct session_tab_hist th;
531 if (datalen != sizeof(th))
534 memcpy(&th, imsg->data, sizeof(th));
535 if (th.uri[sizeof(th.uri)-1] != '\0')
538 fprintf(session, "%s %s\n", th.future ? ">" : "<", th.uri);
542 handle_session_end(struct imsg *imsg, size_t datalen)
551 handle_dispatch_imsg(int fd, short ev, void *d)
553 struct imsgev *iev = d;
556 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1) {
558 * This should leave a ~/.cache/telescope/crashed file to
559 * trigger about:crash on next run. Unfortunately, if
560 * the main process dies the fs sticks around and
561 * doesn't notice that the fd was closed. Why EV_READ
562 * is not triggered when a fd is closed on the other end?
565 if ((fd = open(crashed_file, O_CREAT|O_TRUNC|O_WRONLY, 0600))
569 errx(1, "connection closed: %s", strerror(e));
574 fs_send_ui(int type, uint32_t peerid, int fd, const void *data,
577 return imsg_compose_event(iev_ui, type, peerid, 0, fd,
582 join_path(char *buf, const char *lhs, const char *rhs, size_t buflen)
584 strlcpy(buf, lhs, buflen);
585 return strlcat(buf, rhs, buflen);
589 getenv_default(char *buf, const char *name, const char *def, size_t buflen)
594 if ((home = getenv("HOME")) == NULL)
595 errx(1, "HOME is not defined");
597 if ((env = getenv(name)) != NULL)
598 ret = strlcpy(buf, env, buflen);
600 ret = join_path(buf, home, def, buflen);
603 errx(1, "buffer too small for %s", name);
607 mkdirs(const char *path, mode_t mode)
609 char copy[PATH_MAX+1], orig[PATH_MAX+1], *parent;
611 strlcpy(copy, path, sizeof(copy));
612 strlcpy(orig, path, sizeof(orig));
613 parent = dirname(copy);
614 if (!strcmp(parent, "/"))
616 mkdirs(parent, mode);
618 if (mkdir(orig, mode) != 0) {
621 err(1, "can't mkdir %s", orig);
628 char *home, 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, const char **title, uint32_t *flags)
706 if ((s = strchr(line, ' ')) == NULL)
711 if ((t = strchr(s, ' ')) != NULL) {
716 while ((ap = strsep(&s, ",")) != NULL) {
717 if (!strcmp(ap, "current"))
718 *flags |= TAB_CURRENT;
723 sendtab(uint32_t flags, const char *uri, const char *title)
725 struct session_tab tab;
727 memset(&tab, 0, sizeof(tab));
730 if (strlcpy(tab.uri, uri, sizeof(tab.uri)) >= sizeof(tab.uri))
733 /* don't worry about cached title truncation */
735 strlcpy(tab.title, title, sizeof(tab.title));
737 fs_send_ui(IMSG_SESSION_TAB, 0, -1, &tab, sizeof(tab));
741 sendhist(const char *uri, int future)
743 struct session_tab_hist sth;
745 memset(&sth, 0, sizeof(sth));
748 if (strlcpy(sth.uri, uri, sizeof(sth.uri)) >= sizeof(sth.uri))
751 fs_send_ui(IMSG_SESSION_TAB_HIST, 0, -1, &sth, sizeof(sth));
755 load_last_session(void)
764 char *nl, *s, *line = NULL;
766 if ((session = fopen(session_file, "r")) == NULL) {
772 while ((linelen = getline(&line, &linesize, session)) != -1) {
773 if ((nl = strchr(line, '\n')) != NULL)
776 if (*line == '<' || *line == '>') {
777 future = *line == '>';
781 sendhist(++s, future);
783 parse_session_line(line, &title, &flags);
784 sendtab(flags, line, title);
791 if (last_time_crashed())
792 sendtab(TAB_CURRENT, "about:crash", NULL);
795 fs_send_ui(IMSG_SESSION_END, 0, -1, &first_time, sizeof(first_time));
807 /* Setup pipe and event handler to the main process */
808 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
810 imsg_init(&iev_ui->ibuf, 3);
811 iev_ui->handler = handle_dispatch_imsg;
812 iev_ui->events = EV_READ;
813 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
814 iev_ui->handler, iev_ui);
815 event_add(&iev_ui->ev, NULL);
817 sandbox_fs_process();
826 * Check if the last time telescope crashed. The check is done by
827 * looking at `crashed_file': if it exists then last time we crashed.
828 * Then, while here, touch the file too. During IMSG_QUIT we'll
832 last_time_crashed(void)
839 if (unlink(crashed_file) == -1 && errno == ENOENT)
842 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
855 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
860 lock.l_type = F_WRLCK;
861 lock.l_whence = SEEK_SET;
863 if (fcntl(fd, F_SETLK, &lock) == -1) {
872 parse_khost_line(char *line, char *tmp[3])
876 for (ap = tmp; ap < &tmp[3] &&
877 (*ap = strsep(&line, " \t\n")) != NULL;) {
882 return ap == &tmp[3] && *line == '\0';
888 char *tmp[3], *line = NULL;
890 size_t lineno = 0, linesize = 0;
895 if ((f = fopen(known_hosts_file, "r")) == NULL)
898 while ((linelen = getline(&line, &linesize, f)) != -1) {
901 memset(&e, 0, sizeof(e));
902 if (parse_khost_line(line, tmp)) {
903 strlcpy(e.domain, tmp[0], sizeof(e.domain));
904 strlcpy(e.hash, tmp[1], sizeof(e.hash));
906 e.verified = strtonum(tmp[2], 0, 1, &errstr);
908 errx(1, "%s:%zu verification for %s is %s: %s",
909 known_hosts_file, lineno,
910 e.domain, errstr, tmp[2]);
912 fs_send_ui(IMSG_TOFU, 0, -1, &e, sizeof(e));
914 warnx("%s:%zu invalid entry",
915 known_hosts_file, lineno);