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_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_end(struct imsg*, size_t);
54 static void handle_dispatch_imsg(int, short, void*);
55 static int fs_send_ui(int, uint32_t, int, const void *, uint16_t);
56 static size_t join_path(char*, const char*, const char*, size_t);
57 static void getenv_default(char*, const char*, const char*, size_t);
58 static void mkdirs(const char*, mode_t);
59 static void xdg_init(void);
61 static struct imsgev *iev_ui;
65 * Note: these are empty if ~/.telescope exists, use *_path_base
68 static char xdg_config_base[PATH_MAX];
69 static char xdg_data_base[PATH_MAX];
70 static char xdg_cache_base[PATH_MAX];
73 * Where to store user data. These are all equal to ~/.telescope if
76 char config_path_base[PATH_MAX];
77 char data_path_base[PATH_MAX];
78 char cache_path_base[PATH_MAX];
80 char config_path[PATH_MAX];
81 char lockfile_path[PATH_MAX];
82 char bookmark_file[PATH_MAX];
83 char known_hosts_file[PATH_MAX], known_hosts_tmp[PATH_MAX];
84 char crashed_file[PATH_MAX];
85 char session_file[PATH_MAX];
87 static imsg_handlerfn *handlers[] = {
88 [IMSG_GET] = handle_get,
89 [IMSG_GET_FILE] = handle_get_file,
90 [IMSG_QUIT] = handle_quit,
91 [IMSG_BOOKMARK_PAGE] = handle_bookmark_page,
92 [IMSG_SAVE_CERT] = handle_save_cert,
93 [IMSG_UPDATE_CERT] = handle_update_cert,
94 [IMSG_FILE_OPEN] = handle_file_open,
95 [IMSG_SESSION_START] = handle_session_start,
96 [IMSG_SESSION_TAB] = handle_session_tab,
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_quit(struct imsg *imsg, size_t datalen)
337 unlink(crashed_file);
343 handle_bookmark_page(struct imsg *imsg, size_t datalen)
350 if (data[datalen-1] != '\0')
353 if ((f = fopen(bookmark_file, "a")) == NULL) {
357 fprintf(f, "=> %s\n", data);
362 fs_send_ui(IMSG_BOOKMARK_OK, 0, -1, &res, sizeof(res));
366 handle_save_cert(struct imsg *imsg, size_t datalen)
372 /* TODO: traverse the file to avoid duplications? */
374 if (datalen != sizeof(e))
376 memcpy(&e, imsg->data, datalen);
378 if ((f = fopen(known_hosts_file, "a")) == NULL) {
382 fprintf(f, "%s %s %d\n", e.domain, e.hash, e.verified);
387 fs_send_ui(IMSG_SAVE_CERT_OK, imsg->hdr.peerid, -1,
392 handle_update_cert(struct imsg *imsg, size_t datalen)
395 struct tofu_entry entry;
396 char sfn[PATH_MAX], *line = NULL, *t;
397 size_t l, linesize = 0;
401 if (datalen != sizeof(entry))
403 memcpy(&entry, imsg->data, datalen);
405 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
406 if ((fd = mkstemp(sfn)) == -1 ||
407 (tmp = fdopen(fd, "w")) == NULL) {
416 if ((f = fopen(known_hosts_file, "r")) == NULL) {
423 l = strlen(entry.domain);
424 while ((linelen = getline(&line, &linesize, f)) != -1) {
425 if ((t = strstr(line, entry.domain)) != NULL &&
426 (line[l] == ' ' || line[l] == '\t'))
428 /* line has a trailing \n */
429 fprintf(tmp, "%s", line);
431 fprintf(tmp, "%s %s %d\n", entry.domain, entry.hash, entry.verified);
445 res = rename(sfn, known_hosts_file) != -1;
448 fs_send_ui(IMSG_UPDATE_CERT_OK, imsg->hdr.peerid, -1,
453 handle_file_open(struct imsg *imsg, size_t datalen)
459 if (path[datalen-1] != '\0')
462 if ((fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
464 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, -1,
467 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, fd,
472 handle_session_start(struct imsg *imsg, size_t datalen)
477 if ((session = fopen(session_file, "w")) == NULL)
482 handle_session_tab(struct imsg *imsg, size_t datalen)
484 struct session_tab tab;
489 if (datalen != sizeof(tab))
492 memcpy(&tab, imsg->data, sizeof(tab));
493 if (tab.uri[sizeof(tab.uri)-1] != '\0' ||
494 tab.title[sizeof(tab.title)-1] != '\0')
497 fprintf(session, "%s", tab.uri);
499 if (tab.flags & TAB_CURRENT)
500 fprintf(session, " current ");
502 fprintf(session, " - ");
504 fprintf(session, "%s\n", tab.title);
508 handle_session_end(struct imsg *imsg, size_t datalen)
517 handle_dispatch_imsg(int fd, short ev, void *d)
519 struct imsgev *iev = d;
522 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1) {
524 * This should leave a ~/.cache/telescope/crashed file to
525 * trigger about:crash on next run. Unfortunately, if
526 * the main process dies the fs sticks around and
527 * doesn't notice that the fd was closed. Why EV_READ
528 * is not triggered when a fd is closed on the other end?
531 if ((fd = open(crashed_file, O_CREAT|O_TRUNC|O_WRONLY, 0600))
535 errx(1, "connection closed: %s", strerror(e));
540 fs_send_ui(int type, uint32_t peerid, int fd, const void *data,
543 return imsg_compose_event(iev_ui, type, peerid, 0, fd,
548 join_path(char *buf, const char *lhs, const char *rhs, size_t buflen)
550 strlcpy(buf, lhs, buflen);
551 return strlcat(buf, rhs, buflen);
555 getenv_default(char *buf, const char *name, const char *def, size_t buflen)
560 if ((home = getenv("HOME")) == NULL)
561 errx(1, "HOME is not defined");
563 if ((env = getenv(name)) != NULL)
564 ret = strlcpy(buf, env, buflen);
566 ret = join_path(buf, home, def, buflen);
569 errx(1, "buffer too small for %s", name);
573 mkdirs(const char *path, mode_t mode)
575 char copy[PATH_MAX+1], orig[PATH_MAX+1], *parent;
577 strlcpy(copy, path, sizeof(copy));
578 strlcpy(orig, path, sizeof(orig));
579 parent = dirname(copy);
580 if (!strcmp(parent, "/"))
582 mkdirs(parent, mode);
584 if (mkdir(orig, mode) != 0) {
587 err(1, "can't mkdir %s", orig);
594 char *home, old_path[PATH_MAX];
598 if ((home = getenv("HOME")) == NULL)
599 errx(1, "HOME is not defined");
600 join_path(old_path, home, "/.telescope", sizeof(old_path));
602 /* if ~/.telescope exists, use that instead of xdg dirs */
603 if (stat(old_path, &info) == 0 && S_ISDIR(info.st_mode)) {
604 join_path(config_path_base, home, "/.telescope",
605 sizeof(config_path_base));
606 join_path(data_path_base, home, "/.telescope",
607 sizeof(data_path_base));
608 join_path(cache_path_base, home, "/.telescope",
609 sizeof(cache_path_base));
614 getenv_default(xdg_config_base, "XDG_CONFIG_HOME", "/.config",
615 sizeof(xdg_config_base));
616 getenv_default(xdg_data_base, "XDG_DATA_HOME", "/.local/share",
617 sizeof(xdg_data_base));
618 getenv_default(xdg_cache_base, "XDG_CACHE_HOME", "/.cache",
619 sizeof(xdg_cache_base));
621 join_path(config_path_base, xdg_config_base, "/telescope",
622 sizeof(config_path_base));
623 join_path(data_path_base, xdg_data_base, "/telescope",
624 sizeof(data_path_base));
625 join_path(cache_path_base, xdg_cache_base, "/telescope",
626 sizeof(cache_path_base));
628 mkdirs(xdg_config_base, S_IRWXU);
629 mkdirs(xdg_data_base, S_IRWXU);
630 mkdirs(xdg_cache_base, S_IRWXU);
632 mkdirs(config_path_base, S_IRWXU);
633 mkdirs(data_path_base, S_IRWXU);
634 mkdirs(cache_path_base, S_IRWXU);
642 join_path(config_path, config_path_base, "/config",
643 sizeof(config_path));
644 join_path(lockfile_path, cache_path_base, "/lock",
645 sizeof(lockfile_path));
646 join_path(bookmark_file, data_path_base, "/bookmarks.gmi",
647 sizeof(bookmark_file));
648 join_path(known_hosts_file, data_path_base, "/known_hosts",
649 sizeof(known_hosts_file));
650 join_path(known_hosts_tmp, cache_path_base,
651 "/known_hosts.tmp.XXXXXXXXXX", sizeof(known_hosts_tmp));
652 join_path(session_file, cache_path_base, "/session",
653 sizeof(session_file));
654 join_path(crashed_file, cache_path_base, "/crashed",
655 sizeof(crashed_file));
661 * Parse a line of the session file. The format is:
663 * URL [flags,...] [title]\n
666 parse_session_line(char *line, const char **title, uint32_t *flags)
672 if ((s = strchr(line, ' ')) == NULL)
677 if ((t = strchr(s, ' ')) != NULL) {
682 while ((ap = strsep(&s, ",")) != NULL) {
683 if (!strcmp(ap, "current"))
684 *flags |= TAB_CURRENT;
689 sendtab(uint32_t flags, const char *uri, const char *title)
691 struct session_tab tab;
693 memset(&tab, 0, sizeof(tab));
696 if (strlcpy(tab.uri, uri, sizeof(tab.uri)) >= sizeof(tab.uri))
699 /* don't worry about cached title truncation */
701 strlcpy(tab.title, title, sizeof(tab.title));
703 fs_send_ui(IMSG_SESSION_TAB, 0, -1, &tab, sizeof(tab));
707 load_last_session(int fd, short event, void *d)
715 char *nl, *line = NULL;
717 if ((session = fopen(session_file, "r")) == NULL) {
723 while ((linelen = getline(&line, &linesize, session)) != -1) {
724 if ((nl = strchr(line, '\n')) != NULL)
726 parse_session_line(line, &title, &flags);
727 sendtab(flags, line, title);
733 if (last_time_crashed())
734 sendtab(TAB_CURRENT, "about:crash", NULL);
737 fs_send_ui(IMSG_SESSION_END, 0, -1, &first_time, sizeof(first_time));
744 struct timeval t = {0, 0};
752 /* Setup pipe and event handler to the main process */
753 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
755 imsg_init(&iev_ui->ibuf, 3);
756 iev_ui->handler = handle_dispatch_imsg;
757 iev_ui->events = EV_READ;
758 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
759 iev_ui->handler, iev_ui);
760 event_add(&iev_ui->ev, NULL);
762 sandbox_fs_process();
765 * Run load_last_session during the event loop, as soon as
766 * possible; it uses fs_send_ui so it can't be ran outside
769 evtimer_set(&ev, load_last_session, NULL);
770 evtimer_add(&ev, &t);
779 * Check if the last time telescope crashed. The check is done by
780 * looking at `crashed_file': if it exists then last time we crashed.
781 * Then, while here, touch the file too. During IMSG_QUIT we'll
785 last_time_crashed(void)
792 if (unlink(crashed_file) == -1 && errno == ENOENT)
795 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
808 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
813 lock.l_type = F_WRLCK;
814 lock.l_whence = SEEK_SET;
816 if (fcntl(fd, F_SETLK, &lock) == -1) {
825 parse_khost_line(char *line, char *tmp[3])
829 for (ap = tmp; ap < &tmp[3] &&
830 (*ap = strsep(&line, " \t\n")) != NULL;) {
835 return ap == &tmp[3] && *line == '\0';
839 load_certs(struct ohash *h)
841 char *tmp[3], *line = NULL;
843 size_t lineno = 0, linesize = 0;
846 struct tofu_entry *e;
848 if ((f = fopen(known_hosts_file, "r")) == NULL)
851 while ((linelen = getline(&line, &linesize, f)) != -1) {
852 if ((e = calloc(1, sizeof(*e))) == NULL)
857 if (parse_khost_line(line, tmp)) {
858 strlcpy(e->domain, tmp[0], sizeof(e->domain));
859 strlcpy(e->hash, tmp[1], sizeof(e->hash));
861 e->verified = strtonum(tmp[2], 0, 1, &errstr);
863 errx(1, "%s:%zu verification for %s is %s: %s",
864 known_hosts_file, lineno,
865 e->domain, errstr, tmp[2]);
868 warnx("%s:%zu invalid entry",
869 known_hosts_file, lineno);