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 the data in ~/.telescope
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 <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
35 #include "pages.h"
36 #include "telescope.h"
38 static void die(void) __attribute__((__noreturn__));
39 static void send_file(uint32_t, FILE *);
40 static void handle_get(struct imsg*, size_t);
41 static int select_non_dot(const struct dirent *);
42 static int select_non_dotdot(const struct dirent *);
43 static void handle_get_file(struct imsg*, size_t);
44 static void handle_quit(struct imsg*, size_t);
45 static void handle_bookmark_page(struct imsg*, size_t);
46 static void handle_save_cert(struct imsg*, size_t);
47 static void handle_update_cert(struct imsg*, size_t);
48 static void handle_file_open(struct imsg*, size_t);
49 static void handle_session_start(struct imsg*, size_t);
50 static void handle_session_tab(struct imsg*, size_t);
51 static void handle_session_tab_title(struct imsg*, size_t);
52 static void handle_session_end(struct imsg*, size_t);
53 static void handle_dispatch_imsg(int, short, void*);
54 static int fs_send_ui(int, uint32_t, int, const void *, uint16_t);
56 static struct imsgev *iev_ui;
57 static FILE *session;
59 static char base_path[PATH_MAX];
60 static char lockfile_path[PATH_MAX];
61 static char bookmark_file[PATH_MAX];
62 static char known_hosts_file[PATH_MAX], known_hosts_tmp[PATH_MAX];
63 static char crashed_file[PATH_MAX];
65 char session_file[PATH_MAX];
67 static imsg_handlerfn *handlers[] = {
68 [IMSG_GET] = handle_get,
69 [IMSG_GET_FILE] = handle_get_file,
70 [IMSG_QUIT] = handle_quit,
71 [IMSG_BOOKMARK_PAGE] = handle_bookmark_page,
72 [IMSG_SAVE_CERT] = handle_save_cert,
73 [IMSG_UPDATE_CERT] = handle_update_cert,
74 [IMSG_FILE_OPEN] = handle_file_open,
75 [IMSG_SESSION_START] = handle_session_start,
76 [IMSG_SESSION_TAB] = handle_session_tab,
77 [IMSG_SESSION_TAB_TITLE] = handle_session_tab_title,
78 [IMSG_SESSION_END] = handle_session_end,
79 };
81 static void __attribute__((__noreturn__))
82 die(void)
83 {
84 abort(); /* TODO */
85 }
87 static void
88 send_file(uint32_t peerid, FILE *f)
89 {
90 ssize_t r;
91 char buf[BUFSIZ];
93 for (;;) {
94 r = fread(buf, 1, sizeof(buf), f);
95 if (r != 0)
96 fs_send_ui(IMSG_BUF, peerid, -1, buf, r);
97 if (r != sizeof(buf))
98 break;
99 }
100 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
101 fclose(f);
104 static void
105 handle_get(struct imsg *imsg, size_t datalen)
107 const char *bpath = "bookmarks.gmi";
108 char path[PATH_MAX];
109 FILE *f;
110 const char *data, *p;
111 size_t i;
112 struct page {
113 const char *name;
114 const char *path;
115 const uint8_t *data;
116 size_t len;
117 } pages[] = {
118 {"about", NULL, about_about, about_about_len},
119 {"blank", NULL, about_blank, about_blank_len},
120 {"bookmarks", bpath, bookmarks, bookmarks_len},
121 {"crash", NULL, about_crash, about_crash_len},
122 {"help", NULL, about_help, about_help_len},
123 {"license", NULL, about_license, about_license_len},
124 {"new", NULL, about_new, about_new_len},
125 }, *page = NULL;
127 data = imsg->data;
128 if (data[datalen-1] != '\0') /* make sure it's NUL-terminated */
129 die();
130 if ((data = strchr(data, ':')) == NULL)
131 goto notfound;
132 data++;
134 for (i = 0; i < sizeof(pages)/sizeof(pages[0]); ++i)
135 if (!strcmp(data, pages[i].name)) {
136 page = &pages[i];
137 break;
140 if (page == NULL)
141 goto notfound;
143 strlcpy(path, base_path, sizeof(path));
144 strlcat(path, "/", sizeof(path));
145 if (page->path != NULL)
146 strlcat(path, page->path, sizeof(path));
147 else {
148 strlcat(path, "pages/about_", sizeof(path));
149 strlcat(path, page->name, sizeof(path));
150 strlcat(path, ".gmi", sizeof(path));
153 if ((f = fopen(path, "r")) == NULL) {
154 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1,
155 page->data, page->len);
156 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1,
157 NULL, 0);
158 return;
161 send_file(imsg->hdr.peerid, f);
162 return;
164 notfound:
165 p = "# not found!\n";
166 fs_send_ui(IMSG_BUF, imsg->hdr.peerid, -1, p, strlen(p));
167 fs_send_ui(IMSG_EOF, imsg->hdr.peerid, -1, NULL, 0);
170 static inline void
171 send_hdr(uint32_t peerid, int code, const char *meta)
173 fs_send_ui(IMSG_GOT_CODE, peerid, -1, &code, sizeof(code));
174 fs_send_ui(IMSG_GOT_META, peerid, -1, meta, strlen(meta)+1);
177 static inline void
178 send_errno(uint32_t peerid, int code, const char *str, int no)
180 char *s;
182 if (asprintf(&s, "%s: %s", str, strerror(no)) == -1)
183 s = NULL;
185 send_hdr(peerid, code, s == NULL ? str : s);
186 free(s);
189 static inline const char *
190 file_type(const char *path)
192 struct mapping {
193 const char *ext;
194 const char *mime;
195 } ms[] = {
196 {"diff", "text/x-patch"},
197 {"gemini", "text/gemini"},
198 {"gmi", "text/gemini"},
199 {"markdown", "text/plain"},
200 {"md", "text/plain"},
201 {"patch", "text/x-patch"},
202 {"txt", "text/plain"},
203 {NULL, NULL},
204 }, *m;
205 char *dot;
207 if ((dot = strrchr(path, '.')) == NULL)
208 return NULL;
210 dot++;
212 for (m = ms; m->ext != NULL; ++m)
213 if (!strcmp(m->ext, dot))
214 return m->mime;
216 return NULL;
219 static int
220 select_non_dot(const struct dirent *d)
222 return strcmp(d->d_name, ".");
225 static int
226 select_non_dotdot(const struct dirent *d)
228 return strcmp(d->d_name, ".") && strcmp(d->d_name, "..");
231 static inline void
232 send_dir(uint32_t peerid, const char *path)
234 struct dirent **names;
235 struct evbuffer *ev;
236 char *s;
237 int (*selector)(const struct dirent *) = select_non_dot;
238 int i, len, no;
240 if (!has_suffix(path, "/")) {
241 if (asprintf(&s, "%s/", path) == -1)
242 die();
243 send_hdr(peerid, 30, s);
244 free(s);
245 return;
248 if (!strcmp(path, "/"))
249 selector = select_non_dotdot;
251 if ((ev = evbuffer_new()) == NULL ||
252 (len = scandir(path, &names, selector, alphasort)) == -1) {
253 no = errno;
254 evbuffer_free(ev);
255 send_errno(peerid, 40, "failure reading the directory", no);
256 return;
259 evbuffer_add_printf(ev, "# Index of %s\n\n", path);
260 for (i = 0; i < len; ++i) {
261 evbuffer_add_printf(ev, "=> %s", names[i]->d_name);
262 if (names[i]->d_type == DT_DIR)
263 evbuffer_add(ev, "/", 1);
264 evbuffer_add(ev, "\n", 1);
267 send_hdr(peerid, 20, "text/gemini");
268 fs_send_ui(IMSG_BUF, peerid, -1,
269 EVBUFFER_DATA(ev), EVBUFFER_LENGTH(ev));
270 fs_send_ui(IMSG_EOF, peerid, -1, NULL, 0);
272 evbuffer_free(ev);
273 free(names);
276 static void
277 handle_get_file(struct imsg *imsg, size_t datalen)
279 struct stat sb;
280 FILE *f;
281 char *data;
282 const char *meta = NULL;
284 data = imsg->data;
285 data[datalen-1] = '\0';
287 if ((f = fopen(data, "r")) == NULL) {
288 send_errno(imsg->hdr.peerid, 51, "can't open", errno);
289 return;
292 if (fstat(fileno(f), &sb) == -1) {
293 send_errno(imsg->hdr.peerid, 40, "fstat", errno);
294 return;
297 if (S_ISDIR(sb.st_mode)) {
298 fclose(f);
299 send_dir(imsg->hdr.peerid, data);
300 return;
303 if ((meta = file_type(data)) == NULL) {
304 fclose(f);
305 send_hdr(imsg->hdr.peerid, 51,
306 "don't know how to visualize this file");
307 return;
310 send_hdr(imsg->hdr.peerid, 20, meta);
311 send_file(imsg->hdr.peerid, f);
314 static void
315 handle_quit(struct imsg *imsg, size_t datalen)
317 if (!safe_mode)
318 unlink(crashed_file);
320 event_loopbreak();
323 static void
324 handle_bookmark_page(struct imsg *imsg, size_t datalen)
326 char *data;
327 int res;
328 FILE *f;
330 data = imsg->data;
331 if (data[datalen-1] != '\0')
332 die();
334 if ((f = fopen(bookmark_file, "a")) == NULL) {
335 res = errno;
336 goto end;
338 fprintf(f, "=> %s\n", data);
339 fclose(f);
341 res = 0;
342 end:
343 fs_send_ui(IMSG_BOOKMARK_OK, 0, -1, &res, sizeof(res));
346 static void
347 handle_save_cert(struct imsg *imsg, size_t datalen)
349 struct tofu_entry e;
350 FILE *f;
351 int res;
353 /* TODO: traverse the file to avoid duplications? */
355 if (datalen != sizeof(e))
356 die();
357 memcpy(&e, imsg->data, datalen);
359 if ((f = fopen(known_hosts_file, "a")) == NULL) {
360 res = errno;
361 goto end;
363 fprintf(f, "%s %s %d\n", e.domain, e.hash, e.verified);
364 fclose(f);
366 res = 0;
367 end:
368 fs_send_ui(IMSG_SAVE_CERT_OK, imsg->hdr.peerid, -1,
369 &res, sizeof(res));
372 static void
373 handle_update_cert(struct imsg *imsg, size_t datalen)
375 FILE *tmp, *f;
376 struct tofu_entry entry;
377 char sfn[PATH_MAX], *line = NULL, *t;
378 size_t l, linesize = 0;
379 ssize_t linelen;
380 int fd, e, res = 0;
382 if (datalen != sizeof(entry))
383 die();
384 memcpy(&entry, imsg->data, datalen);
386 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
387 if ((fd = mkstemp(sfn)) == -1 ||
388 (tmp = fdopen(fd, "w")) == NULL) {
389 if (fd != -1) {
390 unlink(sfn);
391 close(fd);
393 res = 0;
394 goto end;
397 if ((f = fopen(known_hosts_file, "r")) == NULL) {
398 unlink(sfn);
399 fclose(tmp);
400 res = 0;
401 goto end;
404 l = strlen(entry.domain);
405 while ((linelen = getline(&line, &linesize, f)) != -1) {
406 if ((t = strstr(line, entry.domain)) != NULL &&
407 (line[l] == ' ' || line[l] == '\t'))
408 continue;
409 /* line has a trailing \n */
410 fprintf(tmp, "%s", line);
412 fprintf(tmp, "%s %s %d\n", entry.domain, entry.hash, entry.verified);
414 free(line);
415 e = ferror(tmp);
417 fclose(tmp);
418 fclose(f);
420 if (e) {
421 unlink(sfn);
422 res = 0;
423 goto end;
426 res = rename(sfn, known_hosts_file) != -1;
428 end:
429 fs_send_ui(IMSG_UPDATE_CERT_OK, imsg->hdr.peerid, -1,
430 &res, sizeof(res));
433 static void
434 handle_file_open(struct imsg *imsg, size_t datalen)
436 char *path, *e;
437 int fd;
439 path = imsg->data;
440 if (path[datalen-1] != '\0')
441 die();
443 if ((fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0644)) == -1) {
444 e = strerror(errno);
445 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, -1,
446 e, strlen(e)+1);
447 } else
448 fs_send_ui(IMSG_FILE_OPENED, imsg->hdr.peerid, fd,
449 NULL, 0);
452 static void
453 handle_session_start(struct imsg *imsg, size_t datalen)
455 if (datalen != 0)
456 die();
458 if ((session = fopen(session_file, "w")) == NULL)
459 die();
462 static void
463 handle_session_tab(struct imsg *imsg, size_t datalen)
465 char *url;
466 uint32_t flags;
468 if (session == NULL)
469 die();
471 flags = imsg->hdr.peerid;
472 url = imsg->data;
473 if (datalen == 0 || url[datalen-1] != '\0')
474 die();
475 fprintf(session, "%s", url);
477 if (flags & TAB_CURRENT)
478 fprintf(session, " current ");
479 else
480 fprintf(session, " - ");
483 static void
484 handle_session_tab_title(struct imsg *imsg, size_t datalen)
486 const char *title;
488 title = imsg->data;
489 if (title == NULL) {
490 datalen = 1;
491 title = "";
494 if (title[datalen-1] != '\0')
495 die();
497 fprintf(session, "%s\n", title);
500 static void
501 handle_session_end(struct imsg *imsg, size_t datalen)
503 if (session == NULL)
504 die();
505 fclose(session);
506 session = NULL;
509 static void
510 handle_dispatch_imsg(int fd, short ev, void *d)
512 struct imsgev *iev = d;
513 int e;
515 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1) {
516 /*
517 * This should leave a ~/.telescope/crashed file to
518 * trigger about:crash on next run. Unfortunately, if
519 * the main process dies the fs sticks around and
520 * doesn't notice that the fd was closed. Why EV_READ
521 * is not triggered when a fd is closed on the other end?
522 */
523 e = errno;
524 if ((fd = open(crashed_file, O_CREAT|O_TRUNC|O_WRONLY, 0600))
525 == -1)
526 err(1, "open");
527 close(fd);
528 errx(1, "connection closed: %s", strerror(e));
532 static int
533 fs_send_ui(int type, uint32_t peerid, int fd, const void *data,
534 uint16_t datalen)
536 return imsg_compose_event(iev_ui, type, peerid, 0, fd,
537 data, datalen);
540 int
541 fs_init(void)
543 strlcpy(base_path, getenv("HOME"), sizeof(base_path));
544 strlcat(base_path, "/.telescope", sizeof(base_path));
545 mkdir(base_path, 0700);
547 strlcpy(lockfile_path, base_path, sizeof(lockfile_path));
548 strlcat(lockfile_path, "/lock", sizeof(lockfile_path));
550 strlcpy(bookmark_file, base_path, sizeof(bookmark_file));
551 strlcat(bookmark_file, "/bookmarks.gmi", sizeof(bookmark_file));
553 strlcpy(known_hosts_file, base_path, sizeof(known_hosts_file));
554 strlcat(known_hosts_file, "/known_hosts", sizeof(known_hosts_file));
556 strlcpy(known_hosts_tmp, base_path, sizeof(known_hosts_tmp));
557 strlcat(known_hosts_tmp, "/known_hosts.tmp.XXXXXXXXXX",
558 sizeof(known_hosts_file));
560 strlcpy(session_file, base_path, sizeof(session_file));
561 strlcat(session_file, "/session", sizeof(session_file));
563 strlcpy(crashed_file, base_path, sizeof(crashed_file));
564 strlcat(crashed_file, "/crashed", sizeof(crashed_file));
566 return 1;
569 int
570 fs_main(void)
572 setproctitle("fs");
574 fs_init();
576 event_init();
578 /* Setup pipe and event handler to the main process */
579 if ((iev_ui = malloc(sizeof(*iev_ui))) == NULL)
580 die();
581 imsg_init(&iev_ui->ibuf, 3);
582 iev_ui->handler = handle_dispatch_imsg;
583 iev_ui->events = EV_READ;
584 event_set(&iev_ui->ev, iev_ui->ibuf.fd, iev_ui->events,
585 iev_ui->handler, iev_ui);
586 event_add(&iev_ui->ev, NULL);
588 sandbox_fs_process();
590 event_dispatch();
591 return 0;
596 /*
597 * Check if the last time telescope crashed. The check is done by
598 * looking at `crashed_file': if it exists then last time we crashed.
599 * Then, while here, touch the file too. During IMSG_QUIT we'll
600 * remove it.
601 */
602 int
603 last_time_crashed(void)
605 int fd, crashed = 1;
607 if (safe_mode)
608 return 0;
610 if (unlink(crashed_file) == -1 && errno == ENOENT)
611 crashed = 0;
613 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
614 return crashed;
615 close(fd);
617 return crashed;
620 int
621 lock_session(void)
623 struct flock lock;
624 int fd;
626 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
627 return -1;
629 lock.l_start = 0;
630 lock.l_len = 0;
631 lock.l_type = F_WRLCK;
632 lock.l_whence = SEEK_SET;
634 if (fcntl(fd, F_SETLK, &lock) == -1) {
635 close(fd);
636 return -1;
639 return fd;
642 static int
643 parse_khost_line(char *line, char *tmp[3])
645 char **ap;
647 for (ap = tmp; ap < &tmp[3] &&
648 (*ap = strsep(&line, " \t\n")) != NULL;) {
649 if (**ap != '\0')
650 ap++;
653 return ap == &tmp[3] && *line == '\0';
656 int
657 load_certs(struct ohash *h)
659 char *tmp[3], *line = NULL;
660 const char *errstr;
661 size_t lineno = 0, linesize = 0;
662 ssize_t linelen;
663 FILE *f;
664 struct tofu_entry *e;
666 if ((f = fopen(known_hosts_file, "r")) == NULL)
667 return 0;
669 while ((linelen = getline(&line, &linesize, f)) != -1) {
670 if ((e = calloc(1, sizeof(*e))) == NULL)
671 abort();
673 lineno++;
675 if (parse_khost_line(line, tmp)) {
676 strlcpy(e->domain, tmp[0], sizeof(e->domain));
677 strlcpy(e->hash, tmp[1], sizeof(e->hash));
679 e->verified = strtonum(tmp[2], 0, 1, &errstr);
680 if (errstr != NULL)
681 errx(1, "%s:%zu verification for %s is %s: %s",
682 known_hosts_file, lineno,
683 e->domain, errstr, tmp[2]);
684 tofu_add(h, e);
685 } else {
686 warnx("%s:%zu invalid entry",
687 known_hosts_file, lineno);
688 free(e);
692 free(line);
693 return ferror(f);