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 /*
66 * Note: these are empty if ~/.telescope exists, use *_path_base
67 * below.
68 */
69 static char xdg_config_base[PATH_MAX];
70 static char xdg_data_base[PATH_MAX];
71 static char xdg_cache_base[PATH_MAX];
73 /*
74 * Where to store user data. These are all equal to ~/.telescope if
75 * it exists.
76 */
77 char config_path_base[PATH_MAX];
78 char data_path_base[PATH_MAX];
79 char cache_path_base[PATH_MAX];
81 char config_path[PATH_MAX];
82 char lockfile_path[PATH_MAX];
83 char bookmark_file[PATH_MAX];
84 char known_hosts_file[PATH_MAX], known_hosts_tmp[PATH_MAX];
85 char crashed_file[PATH_MAX];
86 char session_file[PATH_MAX];
88 static imsg_handlerfn *handlers[] = {
89 [IMSG_GET] = handle_get,
90 [IMSG_GET_FILE] = handle_get_file,
91 [IMSG_QUIT] = handle_quit,
92 [IMSG_BOOKMARK_PAGE] = handle_bookmark_page,
93 [IMSG_SAVE_CERT] = handle_save_cert,
94 [IMSG_UPDATE_CERT] = handle_update_cert,
95 [IMSG_FILE_OPEN] = handle_file_open,
96 [IMSG_SESSION_START] = handle_session_start,
97 [IMSG_SESSION_TAB] = handle_session_tab,
98 [IMSG_SESSION_TAB_TITLE] = handle_session_tab_title,
99 [IMSG_SESSION_END] = handle_session_end,
100 };
102 static void __attribute__((__noreturn__))
103 die(void)
105 abort(); /* TODO */
108 static void
109 send_file(uint32_t peerid, FILE *f)
111 ssize_t r;
112 char buf[BUFSIZ];
114 for (;;) {
115 r = fread(buf, 1, sizeof(buf), f);
116 if (r != 0)
117 fs_send_ui(IMSG_BUF, peerid, -1, buf, r);
118 if (r != sizeof(buf))
119 break;
121 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
122 fclose(f);
125 static void
126 handle_get(struct imsg *imsg, size_t datalen)
128 const char *bpath = "bookmarks.gmi";
129 char path[PATH_MAX];
130 FILE *f;
131 const char *data, *p;
132 size_t i;
133 struct page {
134 const char *name;
135 const char *path;
136 const uint8_t *data;
137 size_t len;
138 } pages[] = {
139 {"about", NULL, about_about, about_about_len},
140 {"blank", NULL, about_blank, about_blank_len},
141 {"bookmarks", bpath, bookmarks, bookmarks_len},
142 {"crash", NULL, about_crash, about_crash_len},
143 {"help", NULL, about_help, about_help_len},
144 {"license", NULL, about_license, about_license_len},
145 {"new", NULL, about_new, about_new_len},
146 }, *page = NULL;
148 data = imsg->data;
149 if (data[datalen-1] != '\0') /* make sure it's NUL-terminated */
150 die();
151 if ((data = strchr(data, ':')) == NULL)
152 goto notfound;
153 data++;
155 for (i = 0; i < sizeof(pages)/sizeof(pages[0]); ++i)
156 if (!strcmp(data, pages[i].name)) {
157 page = &pages[i];
158 break;
161 if (page == NULL)
162 goto notfound;
164 strlcpy(path, data_path_base, sizeof(path));
165 strlcat(path, "/", sizeof(path));
166 if (page->path != NULL)
167 strlcat(path, page->path, sizeof(path));
168 else {
169 strlcat(path, "pages/about_", sizeof(path));
170 strlcat(path, page->name, sizeof(path));
171 strlcat(path, ".gmi", sizeof(path));
174 if ((f = fopen(path, "r")) == NULL) {
175 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1,
176 page->data, page->len);
177 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1,
178 NULL, 0);
179 return;
182 send_file(imsg->hdr.peerid, f);
183 return;
185 notfound:
186 p = "# not found!\n";
187 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1, p, strlen(p));
188 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1, NULL, 0);
191 static inline void
192 send_hdr(uint32_t peerid, int code, const char *meta)
194 fs_send_ui(IMSG_GOT_CODE, peerid, -1, &code, sizeof(code));
195 fs_send_ui(IMSG_GOT_META, peerid, -1, meta, strlen(meta)+1);
198 static inline void
199 send_errno(uint32_t peerid, int code, const char *str, int no)
201 char *s;
203 if (asprintf(&s, "%s: %s", str, strerror(no)) == -1)
204 s = NULL;
206 send_hdr(peerid, code, s == NULL ? str : s);
207 free(s);
210 static inline const char *
211 file_type(const char *path)
213 struct mapping {
214 const char *ext;
215 const char *mime;
216 } ms[] = {
217 {"diff", "text/x-patch"},
218 {"gemini", "text/gemini"},
219 {"gmi", "text/gemini"},
220 {"markdown", "text/plain"},
221 {"md", "text/plain"},
222 {"patch", "text/x-patch"},
223 {"txt", "text/plain"},
224 {NULL, NULL},
225 }, *m;
226 char *dot;
228 if ((dot = strrchr(path, '.')) == NULL)
229 return NULL;
231 dot++;
233 for (m = ms; m->ext != NULL; ++m)
234 if (!strcmp(m->ext, dot))
235 return m->mime;
237 return NULL;
240 static int
241 select_non_dot(const struct dirent *d)
243 return strcmp(d->d_name, ".");
246 static int
247 select_non_dotdot(const struct dirent *d)
249 return strcmp(d->d_name, ".") && strcmp(d->d_name, "..");
252 static inline void
253 send_dir(uint32_t peerid, const char *path)
255 struct dirent **names;
256 struct evbuffer *ev;
257 char *s;
258 int (*selector)(const struct dirent *) = select_non_dot;
259 int i, len, no;
261 if (!has_suffix(path, "/")) {
262 if (asprintf(&s, "%s/", path) == -1)
263 die();
264 send_hdr(peerid, 30, s);
265 free(s);
266 return;
269 if (!strcmp(path, "/"))
270 selector = select_non_dotdot;
272 if ((ev = evbuffer_new()) == NULL ||
273 (len = scandir(path, &names, selector, alphasort)) == -1) {
274 no = errno;
275 evbuffer_free(ev);
276 send_errno(peerid, 40, "failure reading the directory", no);
277 return;
280 evbuffer_add_printf(ev, "# Index of %s\n\n", path);
281 for (i = 0; i < len; ++i) {
282 evbuffer_add_printf(ev, "=> %s", names[i]->d_name);
283 if (names[i]->d_type == DT_DIR)
284 evbuffer_add(ev, "/", 1);
285 evbuffer_add(ev, "\n", 1);
288 send_hdr(peerid, 20, "text/gemini");
289 fs_send_ui(IMSG_BUF, peerid, -1,
290 EVBUFFER_DATA(ev), EVBUFFER_LENGTH(ev));
291 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
293 evbuffer_free(ev);
294 free(names);
297 static void
298 handle_get_file(struct imsg *imsg, size_t datalen)
300 struct stat sb;
301 FILE *f;
302 char *data;
303 const char *meta = NULL;
305 data = imsg->data;
306 data[datalen-1] = '\0';
308 if ((f = fopen(data, "r")) == NULL) {
309 send_errno(imsg->hdr.peerid, 51, "can't open", errno);
310 return;
313 if (fstat(fileno(f), &sb) == -1) {
314 send_errno(imsg->hdr.peerid, 40, "fstat", errno);
315 return;
318 if (S_ISDIR(sb.st_mode)) {
319 fclose(f);
320 send_dir(imsg->hdr.peerid, data);
321 return;
324 if ((meta = file_type(data)) == NULL) {
325 fclose(f);
326 send_hdr(imsg->hdr.peerid, 51,
327 "don't know how to visualize this file");
328 return;
331 send_hdr(imsg->hdr.peerid, 20, meta);
332 send_file(imsg->hdr.peerid, f);
335 static void
336 handle_quit(struct imsg *imsg, size_t datalen)
338 if (!safe_mode)
339 unlink(crashed_file);
341 event_loopbreak();
344 static void
345 handle_bookmark_page(struct imsg *imsg, size_t datalen)
347 char *data;
348 int res;
349 FILE *f;
351 data = imsg->data;
352 if (data[datalen-1] != '\0')
353 die();
355 if ((f = fopen(bookmark_file, "a")) == NULL) {
356 res = errno;
357 goto end;
359 fprintf(f, "=> %s\n", data);
360 fclose(f);
362 res = 0;
363 end:
364 fs_send_ui(IMSG_BOOKMARK_OK, 0, -1, &res, sizeof(res));
367 static void
368 handle_save_cert(struct imsg *imsg, size_t datalen)
370 struct tofu_entry e;
371 FILE *f;
372 int res;
374 /* TODO: traverse the file to avoid duplications? */
376 if (datalen != sizeof(e))
377 die();
378 memcpy(&e, imsg->data, datalen);
380 if ((f = fopen(known_hosts_file, "a")) == NULL) {
381 res = errno;
382 goto end;
384 fprintf(f, "%s %s %d\n", e.domain, e.hash, e.verified);
385 fclose(f);
387 res = 0;
388 end:
389 fs_send_ui(IMSG_SAVE_CERT_OK, imsg->hdr.peerid, -1,
390 &res, sizeof(res));
393 static void
394 handle_update_cert(struct imsg *imsg, size_t datalen)
396 FILE *tmp, *f;
397 struct tofu_entry entry;
398 char sfn[PATH_MAX], *line = NULL, *t;
399 size_t l, linesize = 0;
400 ssize_t linelen;
401 int fd, e, res = 0;
403 if (datalen != sizeof(entry))
404 die();
405 memcpy(&entry, imsg->data, datalen);
407 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
408 if ((fd = mkstemp(sfn)) == -1 ||
409 (tmp = fdopen(fd, "w")) == NULL) {
410 if (fd != -1) {
411 unlink(sfn);
412 close(fd);
414 res = 0;
415 goto end;
418 if ((f = fopen(known_hosts_file, "r")) == NULL) {
419 unlink(sfn);
420 fclose(tmp);
421 res = 0;
422 goto end;
425 l = strlen(entry.domain);
426 while ((linelen = getline(&line, &linesize, f)) != -1) {
427 if ((t = strstr(line, entry.domain)) != NULL &&
428 (line[l] == ' ' || line[l] == '\t'))
429 continue;
430 /* line has a trailing \n */
431 fprintf(tmp, "%s", line);
433 fprintf(tmp, "%s %s %d\n", entry.domain, entry.hash, entry.verified);
435 free(line);
436 e = ferror(tmp);
438 fclose(tmp);
439 fclose(f);
441 if (e) {
442 unlink(sfn);
443 res = 0;
444 goto end;
447 res = rename(sfn, known_hosts_file) != -1;
449 end:
450 fs_send_ui(IMSG_UPDATE_CERT_OK, imsg->hdr.peerid, -1,
451 &res, sizeof(res));
454 static void
455 handle_file_open(struct imsg *imsg, size_t datalen)
457 char *path, *e;
458 int fd;
460 path = imsg->data;
461 if (path[datalen-1] != '\0')
462 die();
464 if ((fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
465 e = strerror(errno);
466 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, -1,
467 e, strlen(e)+1);
468 } else
469 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, fd,
470 NULL, 0);
473 static void
474 handle_session_start(struct imsg *imsg, size_t datalen)
476 if (datalen != 0)
477 die();
479 if ((session = fopen(session_file, "w")) == NULL)
480 die();
483 static void
484 handle_session_tab(struct imsg *imsg, size_t datalen)
486 char *url;
487 uint32_t flags;
489 if (session == NULL)
490 die();
492 flags = imsg->hdr.peerid;
493 url = imsg->data;
494 if (datalen == 0 || url[datalen-1] != '\0')
495 die();
496 fprintf(session, "%s", url);
498 if (flags & TAB_CURRENT)
499 fprintf(session, " current ");
500 else
501 fprintf(session, " - ");
504 static void
505 handle_session_tab_title(struct imsg *imsg, size_t datalen)
507 const char *title;
509 title = imsg->data;
510 if (title == NULL) {
511 datalen = 1;
512 title = "";
515 if (title[datalen-1] != '\0')
516 die();
518 fprintf(session, "%s\n", title);
521 static void
522 handle_session_end(struct imsg *imsg, size_t datalen)
524 if (session == NULL)
525 die();
526 fclose(session);
527 session = NULL;
530 static void
531 handle_dispatch_imsg(int fd, short ev, void *d)
533 struct imsgev *iev = d;
534 int e;
536 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1) {
537 /*
538 * This should leave a ~/.cache/telescope/crashed file to
539 * trigger about:crash on next run. Unfortunately, if
540 * the main process dies the fs sticks around and
541 * doesn't notice that the fd was closed. Why EV_READ
542 * is not triggered when a fd is closed on the other end?
543 */
544 e = errno;
545 if ((fd = open(crashed_file, O_CREAT|O_TRUNC|O_WRONLY, 0600))
546 == -1)
547 err(1, "open");
548 close(fd);
549 errx(1, "connection closed: %s", strerror(e));
553 static int
554 fs_send_ui(int type, uint32_t peerid, int fd, const void *data,
555 uint16_t datalen)
557 return imsg_compose_event(iev_ui, type, peerid, 0, fd,
558 data, datalen);
561 static size_t
562 join_path(char *buf, const char *lhs, const char *rhs, size_t buflen)
564 strlcpy(buf, lhs, buflen);
565 return strlcat(buf, rhs, buflen);
568 static void
569 getenv_default(char *buf, const char *name, const char *def, size_t buflen)
571 size_t ret;
572 char *home, *env;
574 if ((home = getenv("HOME")) == NULL)
575 errx(1, "HOME is not defined");
577 if ((env = getenv(name)) != NULL)
578 ret = strlcpy(buf, env, buflen);
579 else
580 ret = join_path(buf, home, def, buflen);
582 if (ret >= buflen)
583 errx(1, "buffer too small for %s", name);
586 static void
587 mkdirs(const char *path, mode_t mode)
589 char copy[PATH_MAX+1], orig[PATH_MAX+1], *parent;
591 strlcpy(copy, path, sizeof(copy));
592 strlcpy(orig, path, sizeof(orig));
593 parent = dirname(copy);
594 if (!strcmp(parent, "/"))
595 return;
596 mkdirs(parent, mode);
598 if (mkdir(orig, mode) != 0) {
599 if (errno == EEXIST)
600 return;
601 err(1, "can't mkdir %s", orig);
605 static void
606 xdg_init(void)
608 char *home, old_path[PATH_MAX];
609 struct stat info;
611 /* old path */
612 if ((home = getenv("HOME")) == NULL)
613 errx(1, "HOME is not defined");
614 join_path(old_path, home, "/.telescope", sizeof(old_path));
616 /* if ~/.telescope exists, use that instead of xdg dirs */
617 if (stat(old_path, &info) == 0 && S_ISDIR(info.st_mode)) {
618 join_path(config_path_base, home, "/.telescope",
619 sizeof(config_path_base));
620 join_path(data_path_base, home, "/.telescope",
621 sizeof(data_path_base));
622 join_path(cache_path_base, home, "/.telescope",
623 sizeof(cache_path_base));
624 return;
627 /* xdg paths */
628 getenv_default(xdg_config_base, "XDG_CONFIG_HOME", "/.config",
629 sizeof(xdg_config_base));
630 getenv_default(xdg_data_base, "XDG_DATA_HOME", "/.local/share",
631 sizeof(xdg_data_base));
632 getenv_default(xdg_cache_base, "XDG_CACHE_HOME", "/.cache",
633 sizeof(xdg_cache_base));
635 join_path(config_path_base, xdg_config_base, "/telescope",
636 sizeof(config_path_base));
637 join_path(data_path_base, xdg_data_base, "/telescope",
638 sizeof(data_path_base));
639 join_path(cache_path_base, xdg_cache_base, "/telescope",
640 sizeof(cache_path_base));
642 mkdirs(xdg_config_base, S_IRWXU);
643 mkdirs(xdg_data_base, S_IRWXU);
644 mkdirs(xdg_cache_base, S_IRWXU);
646 mkdirs(config_path_base, S_IRWXU);
647 mkdirs(data_path_base, S_IRWXU);
648 mkdirs(cache_path_base, S_IRWXU);
651 int
652 fs_init(void)
654 xdg_init();
656 join_path(config_path, config_path_base, "/config",
657 sizeof(config_path));
658 join_path(lockfile_path, cache_path_base, "/lock",
659 sizeof(lockfile_path));
660 join_path(bookmark_file, data_path_base, "/bookmarks.gmi",
661 sizeof(bookmark_file));
662 join_path(known_hosts_file, data_path_base, "/known_hosts",
663 sizeof(known_hosts_file));
664 join_path(known_hosts_tmp, cache_path_base,
665 "/known_hosts.tmp.XXXXXXXXXX", sizeof(known_hosts_tmp));
666 join_path(session_file, cache_path_base, "/session",
667 sizeof(session_file));
668 join_path(crashed_file, cache_path_base, "/crashed",
669 sizeof(crashed_file));
671 return 1;
674 int
675 fs_main(void)
677 setproctitle("fs");
679 fs_init();
681 event_init();
683 /* Setup pipe and event handler to the main process */
684 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
685 die();
686 imsg_init(&iev_ui->ibuf, 3);
687 iev_ui->handler = handle_dispatch_imsg;
688 iev_ui->events = EV_READ;
689 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
690 iev_ui->handler, iev_ui);
691 event_add(&iev_ui->ev, NULL);
693 sandbox_fs_process();
695 event_dispatch();
696 return 0;
701 /*
702 * Check if the last time telescope crashed. The check is done by
703 * looking at `crashed_file': if it exists then last time we crashed.
704 * Then, while here, touch the file too. During IMSG_QUIT we'll
705 * remove it.
706 */
707 int
708 last_time_crashed(void)
710 int fd, crashed = 1;
712 if (safe_mode)
713 return 0;
715 if (unlink(crashed_file) == -1 && errno == ENOENT)
716 crashed = 0;
718 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
719 return crashed;
720 close(fd);
722 return crashed;
725 int
726 lock_session(void)
728 struct flock lock;
729 int fd;
731 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
732 return -1;
734 lock.l_start = 0;
735 lock.l_len = 0;
736 lock.l_type = F_WRLCK;
737 lock.l_whence = SEEK_SET;
739 if (fcntl(fd, F_SETLK, &lock) == -1) {
740 close(fd);
741 return -1;
744 return fd;
747 static int
748 parse_khost_line(char *line, char *tmp[3])
750 char **ap;
752 for (ap = tmp; ap < &tmp[3] &&
753 (*ap = strsep(&line, " \t\n")) != NULL;) {
754 if (**ap != '\0')
755 ap++;
758 return ap == &tmp[3] && *line == '\0';
761 int
762 load_certs(struct ohash *h)
764 char *tmp[3], *line = NULL;
765 const char *errstr;
766 size_t lineno = 0, linesize = 0;
767 ssize_t linelen;
768 FILE *f;
769 struct tofu_entry *e;
771 if ((f = fopen(known_hosts_file, "r")) == NULL)
772 return 0;
774 while ((linelen = getline(&line, &linesize, f)) != -1) {
775 if ((e = calloc(1, sizeof(*e))) == NULL)
776 abort();
778 lineno++;
780 if (parse_khost_line(line, tmp)) {
781 strlcpy(e->domain, tmp[0], sizeof(e->domain));
782 strlcpy(e->hash, tmp[1], sizeof(e->hash));
784 e->verified = strtonum(tmp[2], 0, 1, &errstr);
785 if (errstr != NULL)
786 errx(1, "%s:%zu verification for %s is %s: %s",
787 known_hosts_file, lineno,
788 e->domain, errstr, tmp[2]);
789 tofu_add(h, e);
790 } else {
791 warnx("%s:%zu invalid entry",
792 known_hosts_file, lineno);
793 free(e);
797 free(line);
798 return ferror(f);