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"
39 #include "session.h"
40 #include "utils.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_hist(struct imsg *, size_t);
58 static void handle_dispatch_imsg(int, short, void*);
59 static int fs_send_ui(int, uint32_t, int, const void *, uint16_t);
60 static size_t join_path(char*, const char*, const char*, size_t);
61 static void getenv_default(char*, const char*, const char*, size_t);
62 static void mkdirs(const char*, mode_t);
63 static void init_paths(void);
64 static void load_last_session(void);
65 static void load_hist(void);
66 static int last_time_crashed(void);
67 static void load_certs(void);
69 static struct imsgev *iev_ui;
70 static FILE *session;
72 /*
73 * Where to store user data. These are all equal to ~/.telescope if
74 * it exists.
75 */
76 char config_path_base[PATH_MAX];
77 char data_path_base[PATH_MAX];
78 char cache_path_base[PATH_MAX];
80 char ctlsock_path[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];
87 static char history_file[PATH_MAX];
89 static imsg_handlerfn *handlers[] = {
90 [IMSG_GET] = handle_get,
91 [IMSG_GET_FILE] = handle_get_file,
92 [IMSG_QUIT] = handle_misc,
93 [IMSG_INIT] = handle_misc,
94 [IMSG_BOOKMARK_PAGE] = handle_bookmark_page,
95 [IMSG_SAVE_CERT] = handle_save_cert,
96 [IMSG_UPDATE_CERT] = handle_update_cert,
97 [IMSG_FILE_OPEN] = handle_file_open,
98 [IMSG_SESSION_START] = handle_session_start,
99 [IMSG_SESSION_TAB] = handle_session_tab,
100 [IMSG_SESSION_TAB_HIST] = handle_session_tab_hist,
101 [IMSG_SESSION_END] = handle_session_end,
102 [IMSG_HIST_ITEM] = handle_hist,
103 [IMSG_HIST_END] = handle_hist,
104 };
106 static void __attribute__((__noreturn__))
107 die(void)
109 abort(); /* TODO */
112 static void
113 send_file(uint32_t peerid, FILE *f)
115 ssize_t r;
116 char buf[BUFSIZ];
118 for (;;) {
119 r = fread(buf, 1, sizeof(buf), f);
120 if (r != 0)
121 fs_send_ui(IMSG_BUF, peerid, -1, buf, r);
122 if (r != sizeof(buf))
123 break;
125 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
126 fclose(f);
129 static void
130 handle_get(struct imsg *imsg, size_t datalen)
132 const char *bpath = "bookmarks.gmi";
133 char path[PATH_MAX];
134 FILE *f;
135 const char *data, *p;
136 size_t i;
137 struct page {
138 const char *name;
139 const char *path;
140 const uint8_t *data;
141 size_t len;
142 } pages[] = {
143 {"about", NULL, about_about, about_about_len},
144 {"blank", NULL, about_blank, about_blank_len},
145 {"bookmarks", bpath, bookmarks, bookmarks_len},
146 {"crash", NULL, about_crash, about_crash_len},
147 {"help", NULL, about_help, about_help_len},
148 {"license", NULL, about_license, about_license_len},
149 {"new", NULL, about_new, about_new_len},
150 }, *page = NULL;
152 data = imsg->data;
153 if (data[datalen-1] != '\0') /* make sure it's NUL-terminated */
154 die();
155 if ((data = strchr(data, ':')) == NULL)
156 goto notfound;
157 data++;
159 for (i = 0; i < sizeof(pages)/sizeof(pages[0]); ++i)
160 if (!strcmp(data, pages[i].name)) {
161 page = &pages[i];
162 break;
165 if (page == NULL)
166 goto notfound;
168 strlcpy(path, data_path_base, sizeof(path));
169 strlcat(path, "/", sizeof(path));
170 if (page->path != NULL)
171 strlcat(path, page->path, sizeof(path));
172 else {
173 strlcat(path, "pages/about_", sizeof(path));
174 strlcat(path, page->name, sizeof(path));
175 strlcat(path, ".gmi", sizeof(path));
178 if ((f = fopen(path, "r")) == NULL) {
179 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1,
180 page->data, page->len);
181 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1,
182 NULL, 0);
183 return;
186 send_file(imsg->hdr.peerid, f);
187 return;
189 notfound:
190 p = "# not found!\n";
191 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1, p, strlen(p));
192 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1, NULL, 0);
195 static inline void
196 send_hdr(uint32_t peerid, int code, const char *meta)
198 fs_send_ui(IMSG_GOT_CODE, peerid, -1, &code, sizeof(code));
199 fs_send_ui(IMSG_GOT_META, peerid, -1, meta, strlen(meta)+1);
202 static inline void
203 send_errno(uint32_t peerid, int code, const char *str, int no)
205 char *s;
207 if (asprintf(&s, "%s: %s", str, strerror(no)) == -1)
208 s = NULL;
210 send_hdr(peerid, code, s == NULL ? str : s);
211 free(s);
214 static inline const char *
215 file_type(const char *path)
217 struct mapping {
218 const char *ext;
219 const char *mime;
220 } ms[] = {
221 {"diff", "text/x-patch"},
222 {"gemini", "text/gemini"},
223 {"gmi", "text/gemini"},
224 {"markdown", "text/plain"},
225 {"md", "text/plain"},
226 {"patch", "text/x-patch"},
227 {"txt", "text/plain"},
228 {NULL, NULL},
229 }, *m;
230 char *dot;
232 if ((dot = strrchr(path, '.')) == NULL)
233 return NULL;
235 dot++;
237 for (m = ms; m->ext != NULL; ++m)
238 if (!strcmp(m->ext, dot))
239 return m->mime;
241 return NULL;
244 static int
245 select_non_dot(const struct dirent *d)
247 return strcmp(d->d_name, ".");
250 static int
251 select_non_dotdot(const struct dirent *d)
253 return strcmp(d->d_name, ".") && strcmp(d->d_name, "..");
256 static inline void
257 send_dir(uint32_t peerid, const char *path)
259 struct dirent **names;
260 struct evbuffer *ev;
261 char *s;
262 int (*selector)(const struct dirent *) = select_non_dot;
263 int i, len, no;
265 if (!has_suffix(path, "/")) {
266 if (asprintf(&s, "%s/", path) == -1)
267 die();
268 send_hdr(peerid, 30, s);
269 free(s);
270 return;
273 if (!strcmp(path, "/"))
274 selector = select_non_dotdot;
276 if ((ev = evbuffer_new()) == NULL ||
277 (len = scandir(path, &names, selector, alphasort)) == -1) {
278 no = errno;
279 evbuffer_free(ev);
280 send_errno(peerid, 40, "failure reading the directory", no);
281 return;
284 evbuffer_add_printf(ev, "# Index of %s\n\n", path);
285 for (i = 0; i < len; ++i) {
286 evbuffer_add_printf(ev, "=> %s", names[i]->d_name);
287 if (names[i]->d_type == DT_DIR)
288 evbuffer_add(ev, "/", 1);
289 evbuffer_add(ev, "\n", 1);
292 send_hdr(peerid, 20, "text/gemini");
293 fs_send_ui(IMSG_BUF, peerid, -1,
294 EVBUFFER_DATA(ev), EVBUFFER_LENGTH(ev));
295 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
297 evbuffer_free(ev);
298 free(names);
301 static void
302 handle_get_file(struct imsg *imsg, size_t datalen)
304 struct stat sb;
305 FILE *f;
306 char *data;
307 const char *meta = NULL;
309 data = imsg->data;
310 data[datalen-1] = '\0';
312 if ((f = fopen(data, "r")) == NULL) {
313 send_errno(imsg->hdr.peerid, 51, "can't open", errno);
314 return;
317 if (fstat(fileno(f), &sb) == -1) {
318 send_errno(imsg->hdr.peerid, 40, "fstat", errno);
319 return;
322 if (S_ISDIR(sb.st_mode)) {
323 fclose(f);
324 send_dir(imsg->hdr.peerid, data);
325 return;
328 if ((meta = file_type(data)) == NULL) {
329 fclose(f);
330 send_hdr(imsg->hdr.peerid, 51,
331 "don't know how to visualize this file");
332 return;
335 send_hdr(imsg->hdr.peerid, 20, meta);
336 send_file(imsg->hdr.peerid, f);
339 static void
340 handle_misc(struct imsg *imsg, size_t datalen)
342 switch (imsg->hdr.type) {
343 case IMSG_INIT:
344 load_certs();
345 load_hist();
346 load_last_session();
347 break;
349 case IMSG_QUIT:
350 if (!safe_mode)
351 unlink(crashed_file);
352 event_loopbreak();
353 break;
355 default:
356 die();
360 static void
361 handle_bookmark_page(struct imsg *imsg, size_t datalen)
363 char *data;
364 int res;
365 FILE *f;
367 data = imsg->data;
368 if (data[datalen-1] != '\0')
369 die();
371 if ((f = fopen(bookmark_file, "a")) == NULL) {
372 res = errno;
373 goto end;
375 fprintf(f, "=> %s\n", data);
376 fclose(f);
378 res = 0;
379 end:
380 fs_send_ui(IMSG_BOOKMARK_OK, 0, -1, &res, sizeof(res));
383 static void
384 handle_save_cert(struct imsg *imsg, size_t datalen)
386 struct tofu_entry e;
387 FILE *f;
388 int res;
390 /* TODO: traverse the file to avoid duplications? */
392 if (datalen != sizeof(e))
393 die();
394 memcpy(&e, imsg->data, datalen);
396 if ((f = fopen(known_hosts_file, "a")) == NULL) {
397 res = errno;
398 goto end;
400 fprintf(f, "%s %s %d\n", e.domain, e.hash, e.verified);
401 fclose(f);
403 res = 0;
404 end:
405 fs_send_ui(IMSG_SAVE_CERT_OK, imsg->hdr.peerid, -1,
406 &res, sizeof(res));
409 static void
410 handle_update_cert(struct imsg *imsg, size_t datalen)
412 FILE *tmp, *f;
413 struct tofu_entry entry;
414 char sfn[PATH_MAX], *line = NULL, *t;
415 size_t l, linesize = 0;
416 ssize_t linelen;
417 int fd, e, res = 0;
419 if (datalen != sizeof(entry))
420 die();
421 memcpy(&entry, imsg->data, datalen);
423 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
424 if ((fd = mkstemp(sfn)) == -1 ||
425 (tmp = fdopen(fd, "w")) == NULL) {
426 if (fd != -1) {
427 unlink(sfn);
428 close(fd);
430 res = 0;
431 goto end;
434 if ((f = fopen(known_hosts_file, "r")) == NULL) {
435 unlink(sfn);
436 fclose(tmp);
437 res = 0;
438 goto end;
441 l = strlen(entry.domain);
442 while ((linelen = getline(&line, &linesize, f)) != -1) {
443 if ((t = strstr(line, entry.domain)) != NULL &&
444 (line[l] == ' ' || line[l] == '\t'))
445 continue;
446 /* line has a trailing \n */
447 fprintf(tmp, "%s", line);
449 fprintf(tmp, "%s %s %d\n", entry.domain, entry.hash, entry.verified);
451 free(line);
452 e = ferror(tmp);
454 fclose(tmp);
455 fclose(f);
457 if (e) {
458 unlink(sfn);
459 res = 0;
460 goto end;
463 res = rename(sfn, known_hosts_file) != -1;
465 end:
466 fs_send_ui(IMSG_UPDATE_CERT_OK, imsg->hdr.peerid, -1,
467 &res, sizeof(res));
470 static void
471 handle_file_open(struct imsg *imsg, size_t datalen)
473 char *path, *e;
474 int fd;
476 path = imsg->data;
477 if (path[datalen-1] != '\0')
478 die();
480 if ((fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
481 e = strerror(errno);
482 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, -1,
483 e, strlen(e)+1);
484 } else
485 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, fd,
486 NULL, 0);
489 static void
490 handle_session_start(struct imsg *imsg, size_t datalen)
492 if (datalen != 0)
493 die();
495 if ((session = fopen(session_file, "w")) == NULL)
496 die();
499 static void
500 handle_session_tab(struct imsg *imsg, size_t datalen)
502 struct session_tab tab;
504 if (session == NULL)
505 die();
507 if (datalen != sizeof(tab))
508 die();
510 memcpy(&tab, imsg->data, sizeof(tab));
511 if (tab.uri[sizeof(tab.uri)-1] != '\0' ||
512 tab.title[sizeof(tab.title)-1] != '\0')
513 die();
515 fprintf(session, "%s ", tab.uri);
517 if (tab.flags & TAB_CURRENT)
518 fprintf(session, "current,");
519 if (tab.flags & TAB_KILLED)
520 fprintf(session, "killed,");
522 fprintf(session, "top=%zu,cur=%zu %s\n", tab.top_line,
523 tab.current_line, tab.title);
526 static void
527 handle_session_tab_hist(struct imsg *imsg, size_t datalen)
529 struct session_tab_hist th;
531 if (session == NULL)
532 die();
534 if (datalen != sizeof(th))
535 die();
537 memcpy(&th, imsg->data, sizeof(th));
538 if (th.uri[sizeof(th.uri)-1] != '\0')
539 die();
541 fprintf(session, "%s %s\n", th.future ? ">" : "<", th.uri);
544 static void
545 handle_session_end(struct imsg *imsg, size_t datalen)
547 if (session == NULL)
548 die();
549 fclose(session);
550 session = NULL;
553 static void
554 handle_hist(struct imsg *imsg, size_t datalen)
556 static FILE *hist;
557 struct histitem hi;
559 switch (imsg->hdr.type) {
560 case IMSG_HIST_ITEM:
561 if (hist == NULL) {
562 if ((hist = fopen(history_file, "a")) == NULL)
563 return;
565 if (datalen != sizeof(hi))
566 abort();
567 memcpy(&hi, imsg->data, sizeof(hi));
568 fprintf(hist, "%lld %s\n", (long long)hi.ts, hi.uri);
569 break;
571 case IMSG_HIST_END:
572 if (hist == NULL)
573 return;
574 fclose(hist);
575 hist = NULL;
576 break;
578 default:
579 abort();
583 static void
584 handle_dispatch_imsg(int fd, short ev, void *d)
586 struct imsgev *iev = d;
587 int e;
589 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1) {
590 /*
591 * This should leave a ~/.cache/telescope/crashed file to
592 * trigger about:crash on next run. Unfortunately, if
593 * the main process dies the fs sticks around and
594 * doesn't notice that the fd was closed. Why EV_READ
595 * is not triggered when a fd is closed on the other end?
596 */
597 e = errno;
598 if ((fd = open(crashed_file, O_CREAT|O_TRUNC|O_WRONLY, 0600))
599 == -1)
600 err(1, "open");
601 close(fd);
602 errx(1, "connection closed: %s", strerror(e));
606 static int
607 fs_send_ui(int type, uint32_t peerid, int fd, const void *data,
608 uint16_t datalen)
610 return imsg_compose_event(iev_ui, type, peerid, 0, fd,
611 data, datalen);
614 static size_t
615 join_path(char *buf, const char *lhs, const char *rhs, size_t buflen)
617 strlcpy(buf, lhs, buflen);
618 return strlcat(buf, rhs, buflen);
621 static void
622 getenv_default(char *buf, const char *name, const char *def, size_t buflen)
624 size_t ret;
625 char *home, *env;
627 if ((home = getenv("HOME")) == NULL)
628 errx(1, "HOME is not defined");
630 if ((env = getenv(name)) != NULL)
631 ret = strlcpy(buf, env, buflen);
632 else
633 ret = join_path(buf, home, def, buflen);
635 if (ret >= buflen)
636 errx(1, "buffer too small for %s", name);
639 static void
640 mkdirs(const char *path, mode_t mode)
642 char copy[PATH_MAX+1], orig[PATH_MAX+1], *parent;
644 strlcpy(copy, path, sizeof(copy));
645 strlcpy(orig, path, sizeof(orig));
646 parent = dirname(copy);
647 if (!strcmp(parent, "/"))
648 return;
649 mkdirs(parent, mode);
651 if (mkdir(orig, mode) != 0) {
652 if (errno == EEXIST)
653 return;
654 err(1, "can't mkdir %s", orig);
658 static void
659 init_paths(void)
661 char xdg_config_base[PATH_MAX];
662 char xdg_data_base[PATH_MAX];
663 char xdg_cache_base[PATH_MAX];
664 char old_path[PATH_MAX];
665 char *home;
666 struct stat info;
668 /* old path */
669 if ((home = getenv("HOME")) == NULL)
670 errx(1, "HOME is not defined");
671 join_path(old_path, home, "/.telescope", sizeof(old_path));
673 /* if ~/.telescope exists, use that instead of xdg dirs */
674 if (stat(old_path, &info) == 0 && S_ISDIR(info.st_mode)) {
675 join_path(config_path_base, home, "/.telescope",
676 sizeof(config_path_base));
677 join_path(data_path_base, home, "/.telescope",
678 sizeof(data_path_base));
679 join_path(cache_path_base, home, "/.telescope",
680 sizeof(cache_path_base));
681 return;
684 /* xdg paths */
685 getenv_default(xdg_config_base, "XDG_CONFIG_HOME", "/.config",
686 sizeof(xdg_config_base));
687 getenv_default(xdg_data_base, "XDG_DATA_HOME", "/.local/share",
688 sizeof(xdg_data_base));
689 getenv_default(xdg_cache_base, "XDG_CACHE_HOME", "/.cache",
690 sizeof(xdg_cache_base));
692 join_path(config_path_base, xdg_config_base, "/telescope",
693 sizeof(config_path_base));
694 join_path(data_path_base, xdg_data_base, "/telescope",
695 sizeof(data_path_base));
696 join_path(cache_path_base, xdg_cache_base, "/telescope",
697 sizeof(cache_path_base));
699 mkdirs(xdg_config_base, S_IRWXU);
700 mkdirs(xdg_data_base, S_IRWXU);
701 mkdirs(xdg_cache_base, S_IRWXU);
703 mkdirs(config_path_base, S_IRWXU);
704 mkdirs(data_path_base, S_IRWXU);
705 mkdirs(cache_path_base, S_IRWXU);
708 int
709 fs_init(void)
711 init_paths();
713 join_path(ctlsock_path, cache_path_base, "/ctl",
714 sizeof(ctlsock_path));
715 join_path(config_path, config_path_base, "/config",
716 sizeof(config_path));
717 join_path(lockfile_path, cache_path_base, "/lock",
718 sizeof(lockfile_path));
719 join_path(bookmark_file, data_path_base, "/bookmarks.gmi",
720 sizeof(bookmark_file));
721 join_path(known_hosts_file, data_path_base, "/known_hosts",
722 sizeof(known_hosts_file));
723 join_path(known_hosts_tmp, cache_path_base,
724 "/known_hosts.tmp.XXXXXXXXXX", sizeof(known_hosts_tmp));
725 join_path(session_file, cache_path_base, "/session",
726 sizeof(session_file));
727 join_path(history_file, cache_path_base, "/history",
728 sizeof(history_file));
729 join_path(crashed_file, cache_path_base, "/crashed",
730 sizeof(crashed_file));
732 return 1;
735 /*
736 * Parse a line of the session file. The format is:
738 * URL [flags,...] [title]\n
739 */
740 static void
741 parse_session_line(char *line)
743 struct session_tab tab;
744 char *s, *t, *ap;
746 memset(&tab, 0, sizeof(tab));
748 if ((s = strchr(line, ' ')) == NULL)
749 return;
751 *s++ = '\0';
753 if (strlcpy(tab.uri, line, sizeof(tab.uri)) >= sizeof(tab.uri))
754 return;
756 if ((t = strchr(s, ' ')) != NULL) {
757 *t++ = '\0';
759 /* don't worry about cached title truncation */
760 strlcpy(tab.title, t, sizeof(tab.title));
763 while ((ap = strsep(&s, ",")) != NULL) {
764 if (!strcmp(ap, "current"))
765 tab.flags |= TAB_CURRENT;
766 else if (!strcmp(ap, "killed"))
767 tab.flags |= TAB_KILLED;
768 else if (has_prefix(ap, "top="))
769 tab.top_line = strtonum(ap+4, 0, UINT32_MAX, NULL);
770 else if (has_prefix(ap, "cur="))
771 tab.current_line = strtonum(ap+4, 0, UINT32_MAX, NULL);
774 if (tab.top_line > tab.current_line) {
775 tab.top_line = 0;
776 tab.current_line = 0;
779 fs_send_ui(IMSG_SESSION_TAB, 0, -1, &tab, sizeof(tab));
782 static inline void
783 sendhist(const char *uri, int future)
785 struct session_tab_hist sth;
787 memset(&sth, 0, sizeof(sth));
788 sth.future = future;
790 if (strlcpy(sth.uri, uri, sizeof(sth.uri)) >= sizeof(sth.uri))
791 return;
793 fs_send_ui(IMSG_SESSION_TAB_HIST, 0, -1, &sth, sizeof(sth));
796 static void
797 load_last_session(void)
799 FILE *session;
800 size_t linesize = 0;
801 ssize_t linelen;
802 int first_time = 0;
803 int future;
804 char *nl, *s, *line = NULL;
806 if ((session = fopen(session_file, "r")) == NULL) {
807 /* first time? */
808 first_time = 1;
809 goto end;
812 while ((linelen = getline(&line, &linesize, session)) != -1) {
813 if ((nl = strchr(line, '\n')) != NULL)
814 *nl = '\0';
816 if (*line == '<' || *line == '>') {
817 future = *line == '>';
818 s = line+1;
819 if (*s != ' ')
820 continue;
821 sendhist(++s, future);
822 } else {
823 parse_session_line(line);
827 fclose(session);
828 free(line);
830 if (last_time_crashed()) {
831 struct session_tab tab;
832 memset(&tab, 0, sizeof(tab));
833 tab.flags = TAB_CURRENT;
834 strlcpy(tab.uri, "about:crash", sizeof(tab.uri));
835 fs_send_ui(IMSG_SESSION_TAB, 0, -1, &tab, sizeof(tab));
838 end:
839 fs_send_ui(IMSG_SESSION_END, 0, -1, &first_time, sizeof(first_time));
842 static void
843 load_hist(void)
845 FILE *hist;
846 size_t linesize = 0;
847 ssize_t linelen;
848 char *nl, *spc, *line = NULL;
849 const char *errstr;
850 struct histitem hi;
852 if ((hist = fopen(history_file, "r")) == NULL)
853 goto end;
855 while ((linelen = getline(&line, &linesize, hist)) != -1) {
856 if ((nl = strchr(line, '\n')) != NULL)
857 *nl = '\0';
858 if ((spc = strchr(line, ' ')) == NULL)
859 continue;
860 *spc = '\0';
861 spc++;
863 memset(&hi, 0, sizeof(hi));
864 hi.ts = strtonum(line, INT64_MIN, INT64_MAX, &errstr);
865 if (errstr != NULL)
866 continue;
867 if (strlcpy(hi.uri, spc, sizeof(hi.uri)) >= sizeof(hi.uri))
868 continue;
870 fs_send_ui(IMSG_HIST_ITEM, 0, -1, &hi, sizeof(hi));
873 fclose(hist);
874 free(line);
875 end:
876 fs_send_ui(IMSG_HIST_END, 0, -1, NULL, 0);
879 int
880 fs_main(void)
882 setproctitle("fs");
884 fs_init();
886 event_init();
888 /* Setup pipe and event handler to the main process */
889 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
890 die();
891 imsg_init(&iev_ui->ibuf, 3);
892 iev_ui->handler = handle_dispatch_imsg;
893 iev_ui->events = EV_READ;
894 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
895 iev_ui->handler, iev_ui);
896 event_add(&iev_ui->ev, NULL);
898 sandbox_fs_process();
900 event_dispatch();
901 return 0;
904 /*
905 * Check if the last time telescope crashed. The check is done by
906 * looking at `crashed_file': if it exists then last time we crashed.
907 * Then, while here, touch the file too. During IMSG_QUIT we'll
908 * remove it.
909 */
910 static int
911 last_time_crashed(void)
913 int fd, crashed = 1;
915 if (safe_mode)
916 return 0;
918 if (unlink(crashed_file) == -1 && errno == ENOENT)
919 crashed = 0;
921 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
922 return crashed;
923 close(fd);
925 return crashed;
928 int
929 lock_session(void)
931 struct flock lock;
932 int fd;
934 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
935 return -1;
937 lock.l_start = 0;
938 lock.l_len = 0;
939 lock.l_type = F_WRLCK;
940 lock.l_whence = SEEK_SET;
942 if (fcntl(fd, F_SETLK, &lock) == -1) {
943 close(fd);
944 return -1;
947 return fd;
950 static inline int
951 parse_khost_line(char *line, char *tmp[3])
953 char **ap;
955 for (ap = tmp; ap < &tmp[3] &&
956 (*ap = strsep(&line, " \t\n")) != NULL;) {
957 if (**ap != '\0')
958 ap++;
961 return ap == &tmp[3] && *line == '\0';
964 static void
965 load_certs(void)
967 char *tmp[3], *line = NULL;
968 const char *errstr;
969 size_t lineno = 0, linesize = 0;
970 ssize_t linelen;
971 FILE *f;
972 struct tofu_entry e;
974 if ((f = fopen(known_hosts_file, "r")) == NULL)
975 return;
977 while ((linelen = getline(&line, &linesize, f)) != -1) {
978 lineno++;
980 memset(&e, 0, sizeof(e));
981 if (parse_khost_line(line, tmp)) {
982 strlcpy(e.domain, tmp[0], sizeof(e.domain));
983 strlcpy(e.hash, tmp[1], sizeof(e.hash));
985 e.verified = strtonum(tmp[2], 0, 1, &errstr);
986 if (errstr != NULL)
987 errx(1, "%s:%zu verification for %s is %s: %s",
988 known_hosts_file, lineno,
989 e.domain, errstr, tmp[2]);
991 fs_send_ui(IMSG_TOFU, 0, -1, &e, sizeof(e));
992 } else {
993 warnx("%s:%zu invalid entry",
994 known_hosts_file, lineno);
998 free(line);
999 fclose(f);
1000 return;