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 char config_path_base[PATH_MAX];
72 char data_path_base[PATH_MAX];
73 char cache_path_base[PATH_MAX];
75 char config_path[PATH_MAX];
76 char lockfile_path[PATH_MAX];
77 char bookmark_file[PATH_MAX];
78 char known_hosts_file[PATH_MAX], known_hosts_tmp[PATH_MAX];
79 char crashed_file[PATH_MAX];
80 char session_file[PATH_MAX];
82 static imsg_handlerfn *handlers[] = {
83 [IMSG_GET] = handle_get,
84 [IMSG_GET_FILE] = handle_get_file,
85 [IMSG_QUIT] = handle_quit,
86 [IMSG_BOOKMARK_PAGE] = handle_bookmark_page,
87 [IMSG_SAVE_CERT] = handle_save_cert,
88 [IMSG_UPDATE_CERT] = handle_update_cert,
89 [IMSG_FILE_OPEN] = handle_file_open,
90 [IMSG_SESSION_START] = handle_session_start,
91 [IMSG_SESSION_TAB] = handle_session_tab,
92 [IMSG_SESSION_TAB_TITLE] = handle_session_tab_title,
93 [IMSG_SESSION_END] = handle_session_end,
94 };
96 static void __attribute__((__noreturn__))
97 die(void)
98 {
99 abort(); /* TODO */
102 static void
103 send_file(uint32_t peerid, FILE *f)
105 ssize_t r;
106 char buf[BUFSIZ];
108 for (;;) {
109 r = fread(buf, 1, sizeof(buf), f);
110 if (r != 0)
111 fs_send_ui(IMSG_BUF, peerid, -1, buf, r);
112 if (r != sizeof(buf))
113 break;
115 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
116 fclose(f);
119 static void
120 handle_get(struct imsg *imsg, size_t datalen)
122 const char *bpath = "bookmarks.gmi";
123 char path[PATH_MAX];
124 FILE *f;
125 const char *data, *p;
126 size_t i;
127 struct page {
128 const char *name;
129 const char *path;
130 const uint8_t *data;
131 size_t len;
132 } pages[] = {
133 {"about", NULL, about_about, about_about_len},
134 {"blank", NULL, about_blank, about_blank_len},
135 {"bookmarks", bpath, bookmarks, bookmarks_len},
136 {"crash", NULL, about_crash, about_crash_len},
137 {"help", NULL, about_help, about_help_len},
138 {"license", NULL, about_license, about_license_len},
139 {"new", NULL, about_new, about_new_len},
140 }, *page = NULL;
142 data = imsg->data;
143 if (data[datalen-1] != '\0') /* make sure it's NUL-terminated */
144 die();
145 if ((data = strchr(data, ':')) == NULL)
146 goto notfound;
147 data++;
149 for (i = 0; i < sizeof(pages)/sizeof(pages[0]); ++i)
150 if (!strcmp(data, pages[i].name)) {
151 page = &pages[i];
152 break;
155 if (page == NULL)
156 goto notfound;
158 strlcpy(path, config_path_base, sizeof(path));
159 strlcat(path, "/", sizeof(path));
160 if (page->path != NULL)
161 strlcat(path, page->path, sizeof(path));
162 else {
163 strlcat(path, "pages/about_", sizeof(path));
164 strlcat(path, page->name, sizeof(path));
165 strlcat(path, ".gmi", sizeof(path));
168 if ((f = fopen(path, "r")) == NULL) {
169 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1,
170 page->data, page->len);
171 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1,
172 NULL, 0);
173 return;
176 send_file(imsg->hdr.peerid, f);
177 return;
179 notfound:
180 p = "# not found!\n";
181 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1, p, strlen(p));
182 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1, NULL, 0);
185 static inline void
186 send_hdr(uint32_t peerid, int code, const char *meta)
188 fs_send_ui(IMSG_GOT_CODE, peerid, -1, &code, sizeof(code));
189 fs_send_ui(IMSG_GOT_META, peerid, -1, meta, strlen(meta)+1);
192 static inline void
193 send_errno(uint32_t peerid, int code, const char *str, int no)
195 char *s;
197 if (asprintf(&s, "%s: %s", str, strerror(no)) == -1)
198 s = NULL;
200 send_hdr(peerid, code, s == NULL ? str : s);
201 free(s);
204 static inline const char *
205 file_type(const char *path)
207 struct mapping {
208 const char *ext;
209 const char *mime;
210 } ms[] = {
211 {"diff", "text/x-patch"},
212 {"gemini", "text/gemini"},
213 {"gmi", "text/gemini"},
214 {"markdown", "text/plain"},
215 {"md", "text/plain"},
216 {"patch", "text/x-patch"},
217 {"txt", "text/plain"},
218 {NULL, NULL},
219 }, *m;
220 char *dot;
222 if ((dot = strrchr(path, '.')) == NULL)
223 return NULL;
225 dot++;
227 for (m = ms; m->ext != NULL; ++m)
228 if (!strcmp(m->ext, dot))
229 return m->mime;
231 return NULL;
234 static int
235 select_non_dot(const struct dirent *d)
237 return strcmp(d->d_name, ".");
240 static int
241 select_non_dotdot(const struct dirent *d)
243 return strcmp(d->d_name, ".") && strcmp(d->d_name, "..");
246 static inline void
247 send_dir(uint32_t peerid, const char *path)
249 struct dirent **names;
250 struct evbuffer *ev;
251 char *s;
252 int (*selector)(const struct dirent *) = select_non_dot;
253 int i, len, no;
255 if (!has_suffix(path, "/")) {
256 if (asprintf(&s, "%s/", path) == -1)
257 die();
258 send_hdr(peerid, 30, s);
259 free(s);
260 return;
263 if (!strcmp(path, "/"))
264 selector = select_non_dotdot;
266 if ((ev = evbuffer_new()) == NULL ||
267 (len = scandir(path, &names, selector, alphasort)) == -1) {
268 no = errno;
269 evbuffer_free(ev);
270 send_errno(peerid, 40, "failure reading the directory", no);
271 return;
274 evbuffer_add_printf(ev, "# Index of %s\n\n", path);
275 for (i = 0; i < len; ++i) {
276 evbuffer_add_printf(ev, "=> %s", names[i]->d_name);
277 if (names[i]->d_type == DT_DIR)
278 evbuffer_add(ev, "/", 1);
279 evbuffer_add(ev, "\n", 1);
282 send_hdr(peerid, 20, "text/gemini");
283 fs_send_ui(IMSG_BUF, peerid, -1,
284 EVBUFFER_DATA(ev), EVBUFFER_LENGTH(ev));
285 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
287 evbuffer_free(ev);
288 free(names);
291 static void
292 handle_get_file(struct imsg *imsg, size_t datalen)
294 struct stat sb;
295 FILE *f;
296 char *data;
297 const char *meta = NULL;
299 data = imsg->data;
300 data[datalen-1] = '\0';
302 if ((f = fopen(data, "r")) == NULL) {
303 send_errno(imsg->hdr.peerid, 51, "can't open", errno);
304 return;
307 if (fstat(fileno(f), &sb) == -1) {
308 send_errno(imsg->hdr.peerid, 40, "fstat", errno);
309 return;
312 if (S_ISDIR(sb.st_mode)) {
313 fclose(f);
314 send_dir(imsg->hdr.peerid, data);
315 return;
318 if ((meta = file_type(data)) == NULL) {
319 fclose(f);
320 send_hdr(imsg->hdr.peerid, 51,
321 "don't know how to visualize this file");
322 return;
325 send_hdr(imsg->hdr.peerid, 20, meta);
326 send_file(imsg->hdr.peerid, f);
329 static void
330 handle_quit(struct imsg *imsg, size_t datalen)
332 if (!safe_mode)
333 unlink(crashed_file);
335 event_loopbreak();
338 static void
339 handle_bookmark_page(struct imsg *imsg, size_t datalen)
341 char *data;
342 int res;
343 FILE *f;
345 data = imsg->data;
346 if (data[datalen-1] != '\0')
347 die();
349 if ((f = fopen(bookmark_file, "a")) == NULL) {
350 res = errno;
351 goto end;
353 fprintf(f, "=> %s\n", data);
354 fclose(f);
356 res = 0;
357 end:
358 fs_send_ui(IMSG_BOOKMARK_OK, 0, -1, &res, sizeof(res));
361 static void
362 handle_save_cert(struct imsg *imsg, size_t datalen)
364 struct tofu_entry e;
365 FILE *f;
366 int res;
368 /* TODO: traverse the file to avoid duplications? */
370 if (datalen != sizeof(e))
371 die();
372 memcpy(&e, imsg->data, datalen);
374 if ((f = fopen(known_hosts_file, "a")) == NULL) {
375 res = errno;
376 goto end;
378 fprintf(f, "%s %s %d\n", e.domain, e.hash, e.verified);
379 fclose(f);
381 res = 0;
382 end:
383 fs_send_ui(IMSG_SAVE_CERT_OK, imsg->hdr.peerid, -1,
384 &res, sizeof(res));
387 static void
388 handle_update_cert(struct imsg *imsg, size_t datalen)
390 FILE *tmp, *f;
391 struct tofu_entry entry;
392 char sfn[PATH_MAX], *line = NULL, *t;
393 size_t l, linesize = 0;
394 ssize_t linelen;
395 int fd, e, res = 0;
397 if (datalen != sizeof(entry))
398 die();
399 memcpy(&entry, imsg->data, datalen);
401 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
402 if ((fd = mkstemp(sfn)) == -1 ||
403 (tmp = fdopen(fd, "w")) == NULL) {
404 if (fd != -1) {
405 unlink(sfn);
406 close(fd);
408 res = 0;
409 goto end;
412 if ((f = fopen(known_hosts_file, "r")) == NULL) {
413 unlink(sfn);
414 fclose(tmp);
415 res = 0;
416 goto end;
419 l = strlen(entry.domain);
420 while ((linelen = getline(&line, &linesize, f)) != -1) {
421 if ((t = strstr(line, entry.domain)) != NULL &&
422 (line[l] == ' ' || line[l] == '\t'))
423 continue;
424 /* line has a trailing \n */
425 fprintf(tmp, "%s", line);
427 fprintf(tmp, "%s %s %d\n", entry.domain, entry.hash, entry.verified);
429 free(line);
430 e = ferror(tmp);
432 fclose(tmp);
433 fclose(f);
435 if (e) {
436 unlink(sfn);
437 res = 0;
438 goto end;
441 res = rename(sfn, known_hosts_file) != -1;
443 end:
444 fs_send_ui(IMSG_UPDATE_CERT_OK, imsg->hdr.peerid, -1,
445 &res, sizeof(res));
448 static void
449 handle_file_open(struct imsg *imsg, size_t datalen)
451 char *path, *e;
452 int fd;
454 path = imsg->data;
455 if (path[datalen-1] != '\0')
456 die();
458 if ((fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
459 e = strerror(errno);
460 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, -1,
461 e, strlen(e)+1);
462 } else
463 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, fd,
464 NULL, 0);
467 static void
468 handle_session_start(struct imsg *imsg, size_t datalen)
470 if (datalen != 0)
471 die();
473 if ((session = fopen(session_file, "w")) == NULL)
474 die();
477 static void
478 handle_session_tab(struct imsg *imsg, size_t datalen)
480 char *url;
481 uint32_t flags;
483 if (session == NULL)
484 die();
486 flags = imsg->hdr.peerid;
487 url = imsg->data;
488 if (datalen == 0 || url[datalen-1] != '\0')
489 die();
490 fprintf(session, "%s", url);
492 if (flags & TAB_CURRENT)
493 fprintf(session, " current ");
494 else
495 fprintf(session, " - ");
498 static void
499 handle_session_tab_title(struct imsg *imsg, size_t datalen)
501 const char *title;
503 title = imsg->data;
504 if (title == NULL) {
505 datalen = 1;
506 title = "";
509 if (title[datalen-1] != '\0')
510 die();
512 fprintf(session, "%s\n", title);
515 static void
516 handle_session_end(struct imsg *imsg, size_t datalen)
518 if (session == NULL)
519 die();
520 fclose(session);
521 session = NULL;
524 static void
525 handle_dispatch_imsg(int fd, short ev, void *d)
527 struct imsgev *iev = d;
528 int e;
530 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1) {
531 /*
532 * This should leave a ~/.cache/telescope/crashed file to
533 * trigger about:crash on next run. Unfortunately, if
534 * the main process dies the fs sticks around and
535 * doesn't notice that the fd was closed. Why EV_READ
536 * is not triggered when a fd is closed on the other end?
537 */
538 e = errno;
539 if ((fd = open(crashed_file, O_CREAT|O_TRUNC|O_WRONLY, 0600))
540 == -1)
541 err(1, "open");
542 close(fd);
543 errx(1, "connection closed: %s", strerror(e));
547 static int
548 fs_send_ui(int type, uint32_t peerid, int fd, const void *data,
549 uint16_t datalen)
551 return imsg_compose_event(iev_ui, type, peerid, 0, fd,
552 data, datalen);
555 static size_t
556 join_path(char *buf, const char *lhs, const char *rhs, size_t buflen)
558 strlcpy(buf, lhs, buflen);
559 return strlcat(buf, rhs, buflen);
562 static void
563 getenv_default(char *buf, const char *name, const char *def, size_t buflen)
565 size_t ret;
566 char *home, *env;
568 if ((home = getenv("HOME")) == NULL)
569 errx(1, "HOME is not defined");
571 if ((env = getenv(name)) != NULL)
572 ret = strlcpy(buf, env, buflen);
573 else
574 ret = join_path(buf, home, def, buflen);
576 if (ret >= buflen)
577 errx(1, "buffer too small for %s", name);
580 static void
581 mkdirs(const char *path, mode_t mode)
583 char copy[PATH_MAX+1], orig[PATH_MAX+1], *parent;
585 strlcpy(copy, path, sizeof(copy));
586 strlcpy(orig, path, sizeof(orig));
587 parent = dirname(copy);
588 if (!strcmp(parent, "/"))
589 return;
590 mkdirs(parent, mode);
592 if (mkdir(orig, mode) != 0) {
593 if (errno == EEXIST)
594 return;
595 err(1, "can't mkdir %s", orig);
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);