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_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);
63 static struct imsgev *iev_ui;
64 static FILE *session;
66 /*
67 * Note: these are empty if ~/.telescope exists, use *_path_base
68 * below.
69 */
70 static char xdg_config_base[PATH_MAX];
71 static char xdg_data_base[PATH_MAX];
72 static char xdg_cache_base[PATH_MAX];
74 /*
75 * Where to store user data. These are all equal to ~/.telescope if
76 * it exists.
77 */
78 char config_path_base[PATH_MAX];
79 char data_path_base[PATH_MAX];
80 char cache_path_base[PATH_MAX];
82 char config_path[PATH_MAX];
83 char lockfile_path[PATH_MAX];
84 char bookmark_file[PATH_MAX];
85 char known_hosts_file[PATH_MAX], known_hosts_tmp[PATH_MAX];
86 char crashed_file[PATH_MAX];
87 char session_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 };
104 static void __attribute__((__noreturn__))
105 die(void)
107 abort(); /* TODO */
110 static void
111 send_file(uint32_t peerid, FILE *f)
113 ssize_t r;
114 char buf[BUFSIZ];
116 for (;;) {
117 r = fread(buf, 1, sizeof(buf), f);
118 if (r != 0)
119 fs_send_ui(IMSG_BUF, peerid, -1, buf, r);
120 if (r != sizeof(buf))
121 break;
123 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
124 fclose(f);
127 static void
128 handle_get(struct imsg *imsg, size_t datalen)
130 const char *bpath = "bookmarks.gmi";
131 char path[PATH_MAX];
132 FILE *f;
133 const char *data, *p;
134 size_t i;
135 struct page {
136 const char *name;
137 const char *path;
138 const uint8_t *data;
139 size_t len;
140 } pages[] = {
141 {"about", NULL, about_about, about_about_len},
142 {"blank", NULL, about_blank, about_blank_len},
143 {"bookmarks", bpath, bookmarks, bookmarks_len},
144 {"crash", NULL, about_crash, about_crash_len},
145 {"help", NULL, about_help, about_help_len},
146 {"license", NULL, about_license, about_license_len},
147 {"new", NULL, about_new, about_new_len},
148 }, *page = NULL;
150 data = imsg->data;
151 if (data[datalen-1] != '\0') /* make sure it's NUL-terminated */
152 die();
153 if ((data = strchr(data, ':')) == NULL)
154 goto notfound;
155 data++;
157 for (i = 0; i < sizeof(pages)/sizeof(pages[0]); ++i)
158 if (!strcmp(data, pages[i].name)) {
159 page = &pages[i];
160 break;
163 if (page == NULL)
164 goto notfound;
166 strlcpy(path, data_path_base, sizeof(path));
167 strlcat(path, "/", sizeof(path));
168 if (page->path != NULL)
169 strlcat(path, page->path, sizeof(path));
170 else {
171 strlcat(path, "pages/about_", sizeof(path));
172 strlcat(path, page->name, sizeof(path));
173 strlcat(path, ".gmi", sizeof(path));
176 if ((f = fopen(path, "r")) == NULL) {
177 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1,
178 page->data, page->len);
179 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1,
180 NULL, 0);
181 return;
184 send_file(imsg->hdr.peerid, f);
185 return;
187 notfound:
188 p = "# not found!\n";
189 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1, p, strlen(p));
190 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1, NULL, 0);
193 static inline void
194 send_hdr(uint32_t peerid, int code, const char *meta)
196 fs_send_ui(IMSG_GOT_CODE, peerid, -1, &code, sizeof(code));
197 fs_send_ui(IMSG_GOT_META, peerid, -1, meta, strlen(meta)+1);
200 static inline void
201 send_errno(uint32_t peerid, int code, const char *str, int no)
203 char *s;
205 if (asprintf(&s, "%s: %s", str, strerror(no)) == -1)
206 s = NULL;
208 send_hdr(peerid, code, s == NULL ? str : s);
209 free(s);
212 static inline const char *
213 file_type(const char *path)
215 struct mapping {
216 const char *ext;
217 const char *mime;
218 } ms[] = {
219 {"diff", "text/x-patch"},
220 {"gemini", "text/gemini"},
221 {"gmi", "text/gemini"},
222 {"markdown", "text/plain"},
223 {"md", "text/plain"},
224 {"patch", "text/x-patch"},
225 {"txt", "text/plain"},
226 {NULL, NULL},
227 }, *m;
228 char *dot;
230 if ((dot = strrchr(path, '.')) == NULL)
231 return NULL;
233 dot++;
235 for (m = ms; m->ext != NULL; ++m)
236 if (!strcmp(m->ext, dot))
237 return m->mime;
239 return NULL;
242 static int
243 select_non_dot(const struct dirent *d)
245 return strcmp(d->d_name, ".");
248 static int
249 select_non_dotdot(const struct dirent *d)
251 return strcmp(d->d_name, ".") && strcmp(d->d_name, "..");
254 static inline void
255 send_dir(uint32_t peerid, const char *path)
257 struct dirent **names;
258 struct evbuffer *ev;
259 char *s;
260 int (*selector)(const struct dirent *) = select_non_dot;
261 int i, len, no;
263 if (!has_suffix(path, "/")) {
264 if (asprintf(&s, "%s/", path) == -1)
265 die();
266 send_hdr(peerid, 30, s);
267 free(s);
268 return;
271 if (!strcmp(path, "/"))
272 selector = select_non_dotdot;
274 if ((ev = evbuffer_new()) == NULL ||
275 (len = scandir(path, &names, selector, alphasort)) == -1) {
276 no = errno;
277 evbuffer_free(ev);
278 send_errno(peerid, 40, "failure reading the directory", no);
279 return;
282 evbuffer_add_printf(ev, "# Index of %s\n\n", path);
283 for (i = 0; i < len; ++i) {
284 evbuffer_add_printf(ev, "=> %s", names[i]->d_name);
285 if (names[i]->d_type == DT_DIR)
286 evbuffer_add(ev, "/", 1);
287 evbuffer_add(ev, "\n", 1);
290 send_hdr(peerid, 20, "text/gemini");
291 fs_send_ui(IMSG_BUF, peerid, -1,
292 EVBUFFER_DATA(ev), EVBUFFER_LENGTH(ev));
293 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
295 evbuffer_free(ev);
296 free(names);
299 static void
300 handle_get_file(struct imsg *imsg, size_t datalen)
302 struct stat sb;
303 FILE *f;
304 char *data;
305 const char *meta = NULL;
307 data = imsg->data;
308 data[datalen-1] = '\0';
310 if ((f = fopen(data, "r")) == NULL) {
311 send_errno(imsg->hdr.peerid, 51, "can't open", errno);
312 return;
315 if (fstat(fileno(f), &sb) == -1) {
316 send_errno(imsg->hdr.peerid, 40, "fstat", errno);
317 return;
320 if (S_ISDIR(sb.st_mode)) {
321 fclose(f);
322 send_dir(imsg->hdr.peerid, data);
323 return;
326 if ((meta = file_type(data)) == NULL) {
327 fclose(f);
328 send_hdr(imsg->hdr.peerid, 51,
329 "don't know how to visualize this file");
330 return;
333 send_hdr(imsg->hdr.peerid, 20, meta);
334 send_file(imsg->hdr.peerid, f);
337 static void
338 handle_misc(struct imsg *imsg, size_t datalen)
340 switch (imsg->hdr.type) {
341 case IMSG_INIT:
342 load_last_session();
343 break;
345 case IMSG_QUIT:
346 if (!safe_mode)
347 unlink(crashed_file);
348 event_loopbreak();
349 break;
351 default:
352 die();
356 static void
357 handle_bookmark_page(struct imsg *imsg, size_t datalen)
359 char *data;
360 int res;
361 FILE *f;
363 data = imsg->data;
364 if (data[datalen-1] != '\0')
365 die();
367 if ((f = fopen(bookmark_file, "a")) == NULL) {
368 res = errno;
369 goto end;
371 fprintf(f, "=> %s\n", data);
372 fclose(f);
374 res = 0;
375 end:
376 fs_send_ui(IMSG_BOOKMARK_OK, 0, -1, &res, sizeof(res));
379 static void
380 handle_save_cert(struct imsg *imsg, size_t datalen)
382 struct tofu_entry e;
383 FILE *f;
384 int res;
386 /* TODO: traverse the file to avoid duplications? */
388 if (datalen != sizeof(e))
389 die();
390 memcpy(&e, imsg->data, datalen);
392 if ((f = fopen(known_hosts_file, "a")) == NULL) {
393 res = errno;
394 goto end;
396 fprintf(f, "%s %s %d\n", e.domain, e.hash, e.verified);
397 fclose(f);
399 res = 0;
400 end:
401 fs_send_ui(IMSG_SAVE_CERT_OK, imsg->hdr.peerid, -1,
402 &res, sizeof(res));
405 static void
406 handle_update_cert(struct imsg *imsg, size_t datalen)
408 FILE *tmp, *f;
409 struct tofu_entry entry;
410 char sfn[PATH_MAX], *line = NULL, *t;
411 size_t l, linesize = 0;
412 ssize_t linelen;
413 int fd, e, res = 0;
415 if (datalen != sizeof(entry))
416 die();
417 memcpy(&entry, imsg->data, datalen);
419 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
420 if ((fd = mkstemp(sfn)) == -1 ||
421 (tmp = fdopen(fd, "w")) == NULL) {
422 if (fd != -1) {
423 unlink(sfn);
424 close(fd);
426 res = 0;
427 goto end;
430 if ((f = fopen(known_hosts_file, "r")) == NULL) {
431 unlink(sfn);
432 fclose(tmp);
433 res = 0;
434 goto end;
437 l = strlen(entry.domain);
438 while ((linelen = getline(&line, &linesize, f)) != -1) {
439 if ((t = strstr(line, entry.domain)) != NULL &&
440 (line[l] == ' ' || line[l] == '\t'))
441 continue;
442 /* line has a trailing \n */
443 fprintf(tmp, "%s", line);
445 fprintf(tmp, "%s %s %d\n", entry.domain, entry.hash, entry.verified);
447 free(line);
448 e = ferror(tmp);
450 fclose(tmp);
451 fclose(f);
453 if (e) {
454 unlink(sfn);
455 res = 0;
456 goto end;
459 res = rename(sfn, known_hosts_file) != -1;
461 end:
462 fs_send_ui(IMSG_UPDATE_CERT_OK, imsg->hdr.peerid, -1,
463 &res, sizeof(res));
466 static void
467 handle_file_open(struct imsg *imsg, size_t datalen)
469 char *path, *e;
470 int fd;
472 path = imsg->data;
473 if (path[datalen-1] != '\0')
474 die();
476 if ((fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
477 e = strerror(errno);
478 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, -1,
479 e, strlen(e)+1);
480 } else
481 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, fd,
482 NULL, 0);
485 static void
486 handle_session_start(struct imsg *imsg, size_t datalen)
488 if (datalen != 0)
489 die();
491 if ((session = fopen(session_file, "w")) == NULL)
492 die();
495 static void
496 handle_session_tab(struct imsg *imsg, size_t datalen)
498 struct session_tab tab;
500 if (session == NULL)
501 die();
503 if (datalen != sizeof(tab))
504 die();
506 memcpy(&tab, imsg->data, sizeof(tab));
507 if (tab.uri[sizeof(tab.uri)-1] != '\0' ||
508 tab.title[sizeof(tab.title)-1] != '\0')
509 die();
511 fprintf(session, "%s", tab.uri);
513 if (tab.flags & TAB_CURRENT)
514 fprintf(session, " current ");
515 else
516 fprintf(session, " - ");
518 fprintf(session, "%s\n", tab.title);
521 static void
522 handle_session_tab_hist(struct imsg *imsg, size_t datalen)
524 struct session_tab_hist th;
526 if (session == NULL)
527 die();
529 if (datalen != sizeof(th))
530 die();
532 memcpy(&th, imsg->data, sizeof(th));
533 if (th.uri[sizeof(th.uri)-1] != '\0')
534 die();
536 fprintf(session, "%s %s\n", th.future ? ">" : "<", th.uri);
539 static void
540 handle_session_end(struct imsg *imsg, size_t datalen)
542 if (session == NULL)
543 die();
544 fclose(session);
545 session = NULL;
548 static void
549 handle_dispatch_imsg(int fd, short ev, void *d)
551 struct imsgev *iev = d;
552 int e;
554 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1) {
555 /*
556 * This should leave a ~/.cache/telescope/crashed file to
557 * trigger about:crash on next run. Unfortunately, if
558 * the main process dies the fs sticks around and
559 * doesn't notice that the fd was closed. Why EV_READ
560 * is not triggered when a fd is closed on the other end?
561 */
562 e = errno;
563 if ((fd = open(crashed_file, O_CREAT|O_TRUNC|O_WRONLY, 0600))
564 == -1)
565 err(1, "open");
566 close(fd);
567 errx(1, "connection closed: %s", strerror(e));
571 static int
572 fs_send_ui(int type, uint32_t peerid, int fd, const void *data,
573 uint16_t datalen)
575 return imsg_compose_event(iev_ui, type, peerid, 0, fd,
576 data, datalen);
579 static size_t
580 join_path(char *buf, const char *lhs, const char *rhs, size_t buflen)
582 strlcpy(buf, lhs, buflen);
583 return strlcat(buf, rhs, buflen);
586 static void
587 getenv_default(char *buf, const char *name, const char *def, size_t buflen)
589 size_t ret;
590 char *home, *env;
592 if ((home = getenv("HOME")) == NULL)
593 errx(1, "HOME is not defined");
595 if ((env = getenv(name)) != NULL)
596 ret = strlcpy(buf, env, buflen);
597 else
598 ret = join_path(buf, home, def, buflen);
600 if (ret >= buflen)
601 errx(1, "buffer too small for %s", name);
604 static void
605 mkdirs(const char *path, mode_t mode)
607 char copy[PATH_MAX+1], orig[PATH_MAX+1], *parent;
609 strlcpy(copy, path, sizeof(copy));
610 strlcpy(orig, path, sizeof(orig));
611 parent = dirname(copy);
612 if (!strcmp(parent, "/"))
613 return;
614 mkdirs(parent, mode);
616 if (mkdir(orig, mode) != 0) {
617 if (errno == EEXIST)
618 return;
619 err(1, "can't mkdir %s", orig);
623 static void
624 xdg_init(void)
626 char *home, old_path[PATH_MAX];
627 struct stat info;
629 /* old path */
630 if ((home = getenv("HOME")) == NULL)
631 errx(1, "HOME is not defined");
632 join_path(old_path, home, "/.telescope", sizeof(old_path));
634 /* if ~/.telescope exists, use that instead of xdg dirs */
635 if (stat(old_path, &info) == 0 && S_ISDIR(info.st_mode)) {
636 join_path(config_path_base, home, "/.telescope",
637 sizeof(config_path_base));
638 join_path(data_path_base, home, "/.telescope",
639 sizeof(data_path_base));
640 join_path(cache_path_base, home, "/.telescope",
641 sizeof(cache_path_base));
642 return;
645 /* xdg paths */
646 getenv_default(xdg_config_base, "XDG_CONFIG_HOME", "/.config",
647 sizeof(xdg_config_base));
648 getenv_default(xdg_data_base, "XDG_DATA_HOME", "/.local/share",
649 sizeof(xdg_data_base));
650 getenv_default(xdg_cache_base, "XDG_CACHE_HOME", "/.cache",
651 sizeof(xdg_cache_base));
653 join_path(config_path_base, xdg_config_base, "/telescope",
654 sizeof(config_path_base));
655 join_path(data_path_base, xdg_data_base, "/telescope",
656 sizeof(data_path_base));
657 join_path(cache_path_base, xdg_cache_base, "/telescope",
658 sizeof(cache_path_base));
660 mkdirs(xdg_config_base, S_IRWXU);
661 mkdirs(xdg_data_base, S_IRWXU);
662 mkdirs(xdg_cache_base, S_IRWXU);
664 mkdirs(config_path_base, S_IRWXU);
665 mkdirs(data_path_base, S_IRWXU);
666 mkdirs(cache_path_base, S_IRWXU);
669 int
670 fs_init(void)
672 xdg_init();
674 join_path(config_path, config_path_base, "/config",
675 sizeof(config_path));
676 join_path(lockfile_path, cache_path_base, "/lock",
677 sizeof(lockfile_path));
678 join_path(bookmark_file, data_path_base, "/bookmarks.gmi",
679 sizeof(bookmark_file));
680 join_path(known_hosts_file, data_path_base, "/known_hosts",
681 sizeof(known_hosts_file));
682 join_path(known_hosts_tmp, cache_path_base,
683 "/known_hosts.tmp.XXXXXXXXXX", sizeof(known_hosts_tmp));
684 join_path(session_file, cache_path_base, "/session",
685 sizeof(session_file));
686 join_path(crashed_file, cache_path_base, "/crashed",
687 sizeof(crashed_file));
689 return 1;
692 /*
693 * Parse a line of the session file. The format is:
695 * URL [flags,...] [title]\n
696 */
697 static void
698 parse_session_line(char *line, const char **title, uint32_t *flags)
700 char *s, *t, *ap;
702 *title = "";
703 *flags = 0;
704 if ((s = strchr(line, ' ')) == NULL)
705 return;
707 *s++ = '\0';
709 if ((t = strchr(s, ' ')) != NULL) {
710 *t++ = '\0';
711 *title = t;
714 while ((ap = strsep(&s, ",")) != NULL) {
715 if (!strcmp(ap, "current"))
716 *flags |= TAB_CURRENT;
720 static inline void
721 sendtab(uint32_t flags, const char *uri, const char *title)
723 struct session_tab tab;
725 memset(&tab, 0, sizeof(tab));
726 tab.flags = flags;
728 if (strlcpy(tab.uri, uri, sizeof(tab.uri)) >= sizeof(tab.uri))
729 return;
731 /* don't worry about cached title truncation */
732 if (title != NULL)
733 strlcpy(tab.title, title, sizeof(tab.title));
735 fs_send_ui(IMSG_SESSION_TAB, 0, -1, &tab, sizeof(tab));
738 static inline void
739 sendhist(const char *uri, int future)
741 struct session_tab_hist sth;
743 memset(&sth, 0, sizeof(sth));
744 sth.future = future;
746 if (strlcpy(sth.uri, uri, sizeof(sth.uri)) >= sizeof(sth.uri))
747 return;
749 fs_send_ui(IMSG_SESSION_TAB_HIST, 0, -1, &sth, sizeof(sth));
752 static void
753 load_last_session(void)
755 FILE *session;
756 uint32_t flags;
757 size_t linesize = 0;
758 ssize_t linelen;
759 int first_time = 0;
760 int future;
761 const char *title;
762 char *nl, *s, *line = NULL;
764 if ((session = fopen(session_file, "r")) == NULL) {
765 /* first time? */
766 first_time = 1;
767 goto end;
770 while ((linelen = getline(&line, &linesize, session)) != -1) {
771 if ((nl = strchr(line, '\n')) != NULL)
772 *nl = '\0';
774 if (*line == '<' || *line == '>') {
775 future = *line == '>';
776 s = line+1;
777 if (*s != ' ')
778 continue;
779 sendhist(++s, future);
780 } else {
781 parse_session_line(line, &title, &flags);
782 sendtab(flags, line, title);
786 fclose(session);
787 free(line);
789 if (last_time_crashed())
790 sendtab(TAB_CURRENT, "about:crash", NULL);
792 end:
793 fs_send_ui(IMSG_SESSION_END, 0, -1, &first_time, sizeof(first_time));
796 int
797 fs_main(void)
799 setproctitle("fs");
801 fs_init();
803 event_init();
805 /* Setup pipe and event handler to the main process */
806 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
807 die();
808 imsg_init(&iev_ui->ibuf, 3);
809 iev_ui->handler = handle_dispatch_imsg;
810 iev_ui->events = EV_READ;
811 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
812 iev_ui->handler, iev_ui);
813 event_add(&iev_ui->ev, NULL);
815 sandbox_fs_process();
817 event_dispatch();
818 return 0;
823 /*
824 * Check if the last time telescope crashed. The check is done by
825 * looking at `crashed_file': if it exists then last time we crashed.
826 * Then, while here, touch the file too. During IMSG_QUIT we'll
827 * remove it.
828 */
829 int
830 last_time_crashed(void)
832 int fd, crashed = 1;
834 if (safe_mode)
835 return 0;
837 if (unlink(crashed_file) == -1 && errno == ENOENT)
838 crashed = 0;
840 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
841 return crashed;
842 close(fd);
844 return crashed;
847 int
848 lock_session(void)
850 struct flock lock;
851 int fd;
853 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
854 return -1;
856 lock.l_start = 0;
857 lock.l_len = 0;
858 lock.l_type = F_WRLCK;
859 lock.l_whence = SEEK_SET;
861 if (fcntl(fd, F_SETLK, &lock) == -1) {
862 close(fd);
863 return -1;
866 return fd;
869 static int
870 parse_khost_line(char *line, char *tmp[3])
872 char **ap;
874 for (ap = tmp; ap < &tmp[3] &&
875 (*ap = strsep(&line, " \t\n")) != NULL;) {
876 if (**ap != '\0')
877 ap++;
880 return ap == &tmp[3] && *line == '\0';
883 int
884 load_certs(struct ohash *h)
886 char *tmp[3], *line = NULL;
887 const char *errstr;
888 size_t lineno = 0, linesize = 0;
889 ssize_t linelen;
890 FILE *f;
891 struct tofu_entry *e;
893 if ((f = fopen(known_hosts_file, "r")) == NULL)
894 return 0;
896 while ((linelen = getline(&line, &linesize, f)) != -1) {
897 if ((e = calloc(1, sizeof(*e))) == NULL)
898 abort();
900 lineno++;
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);
907 if (errstr != NULL)
908 errx(1, "%s:%zu verification for %s is %s: %s",
909 known_hosts_file, lineno,
910 e->domain, errstr, tmp[2]);
911 tofu_add(h, e);
912 } else {
913 warnx("%s:%zu invalid entry",
914 known_hosts_file, lineno);
915 free(e);
919 free(line);
920 return ferror(f);