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 "pages.h"
37 #include "parser.h"
38 #include "session.h"
39 #include "telescope.h"
40 #include "utils.h"
42 #include "fs.h"
44 #ifndef nitems
45 #define nitems(x) (sizeof(x) / sizeof(x[0]))
46 #endif
48 static void die(void) __attribute__((__noreturn__));
49 static int select_non_dot(const struct dirent *);
50 static int select_non_dotdot(const struct dirent *);
51 static size_t join_path(char*, const char*, const char*, size_t);
52 static void getenv_default(char*, const char*, const char*, size_t);
53 static void mkdirs(const char*, mode_t);
54 static void init_paths(void);
55 static void load_last_session(void);
56 static void load_hist(void);
57 static int last_time_crashed(void);
58 static void load_certs(struct ohash *);
60 /*
61 * Where to store user data. These are all equal to ~/.telescope if
62 * it exists.
63 */
64 char config_path_base[PATH_MAX];
65 char data_path_base[PATH_MAX];
66 char cache_path_base[PATH_MAX];
68 char ctlsock_path[PATH_MAX];
69 char config_path[PATH_MAX];
70 char lockfile_path[PATH_MAX];
71 char bookmark_file[PATH_MAX];
72 char known_hosts_file[PATH_MAX], known_hosts_tmp[PATH_MAX];
73 char crashed_file[PATH_MAX];
74 char session_file[PATH_MAX], session_file_tmp[PATH_MAX];
75 char history_file[PATH_MAX], history_file_tmp[PATH_MAX];
77 static void __attribute__((__noreturn__))
78 die(void)
79 {
80 abort(); /* TODO */
81 }
83 static int
84 select_non_dot(const struct dirent *d)
85 {
86 return strcmp(d->d_name, ".");
87 }
89 static int
90 select_non_dotdot(const struct dirent *d)
91 {
92 return strcmp(d->d_name, ".") && strcmp(d->d_name, "..");
93 }
95 static void
96 send_dir(struct tab *tab, const char *path)
97 {
98 struct dirent **names;
99 int (*selector)(const struct dirent *) = select_non_dot;
100 int i, len;
102 #if notyet
103 /*
104 * need something to fake a redirect
105 */
107 if (!has_suffix(path, "/")) {
108 if (asprintf(&s, "%s/", path) == -1)
109 die();
110 send_hdr(peerid, 30, s);
111 free(s);
112 return;
114 #endif
116 if (!strcmp(path, "/"))
117 selector = select_non_dotdot;
119 if ((len = scandir(path, &names, selector, alphasort)) == -1) {
120 load_page_from_str(tab, "# failure reading the directory\n");
121 return;
124 parser_init(tab, gemtext_initparser);
125 parser_parsef(tab, "# Index of %s\n\n", path);
127 for (i = 0; i < len; ++i) {
128 const char *sufx = "";
130 if (names[i]->d_type == DT_DIR)
131 sufx = "/";
133 parser_parsef(tab, "=> %s%s\n", names[i]->d_name, sufx);
136 parser_free(tab);
137 free(names);
140 static int
141 is_dir(FILE *fp)
143 struct stat sb;
145 if (fstat(fileno(fp), &sb) == -1)
146 return 0;
148 return S_ISDIR(sb.st_mode);
151 static parserinit
152 file_type(const char *path)
154 struct mapping {
155 const char *ext;
156 parserinit fn;
157 } ms[] = {
158 {"diff", textpatch_initparser},
159 {"gemini", gemtext_initparser},
160 {"gmi", gemtext_initparser},
161 {"markdown", textplain_initparser},
162 {"md", textplain_initparser},
163 {"patch", gemtext_initparser},
164 {NULL, NULL},
165 }, *m;
166 char *dot;
168 if ((dot = strrchr(path, '.')) == NULL)
169 return textplain_initparser;
171 dot++;
173 for (m = ms; m->ext != NULL; ++m)
174 if (!strcmp(m->ext, dot))
175 return m->fn;
177 return textplain_initparser;
180 void
181 fs_load_url(struct tab *tab, const char *url)
183 const char *bpath = "bookmarks.gmi", *fallback = "# Not found\n";
184 parserinit initfn = gemtext_initparser;
185 char path[PATH_MAX];
186 FILE *fp = NULL;
187 size_t i;
188 char buf[BUFSIZ];
189 struct page {
190 const char *name;
191 const char *path;
192 const uint8_t *data;
193 size_t len;
194 } pages[] = {
195 {"about", NULL, about_about, about_about_len},
196 {"blank", NULL, about_blank, about_blank_len},
197 {"bookmarks", bpath, bookmarks, bookmarks_len},
198 {"crash", NULL, about_crash, about_crash_len},
199 {"help", NULL, about_help, about_help_len},
200 {"license", NULL, about_license, about_license_len},
201 {"new", NULL, about_new, about_new_len},
202 }, *page = NULL;
204 if (!strncmp(url, "about:", 6)) {
205 url += 6;
207 for (i = 0; page == NULL && i < nitems(pages); ++i) {
208 if (!strcmp(url, pages[i].name))
209 page = &pages[i];
212 if (page == NULL)
213 goto done;
215 strlcpy(path, data_path_base, sizeof(path));
216 strlcat(path, "/", sizeof(path));
217 if (page->path != NULL)
218 strlcat(path, page->path, sizeof(path));
219 else {
220 strlcat(path, "page/about_", sizeof(path));
221 strlcat(path, page->name, sizeof(path));
222 strlcat(path, ".gmi", sizeof(path));
225 fallback = page->data;
226 } else if (!strncmp(url, "file://", 7)) {
227 url += 7;
228 strlcpy(path, url, sizeof(path));
229 initfn = file_type(url);
230 } else
231 goto done;
233 if ((fp = fopen(path, "r")) == NULL)
234 goto done;
236 if (is_dir(fp)) {
237 fclose(fp);
238 send_dir(tab, path);
239 goto done;
242 parser_init(tab, initfn);
243 for (;;) {
244 size_t r;
246 r = fread(buf, 1, sizeof(buf), fp);
247 if (!parser_parse(tab, buf, r))
248 break;
249 if (r != sizeof(buf))
250 break;
252 parser_free(tab);
254 done:
255 if (fp != NULL)
256 fclose(fp);
257 else
258 load_page_from_str(tab, fallback);
261 int
262 save_cert(const struct tofu_entry *e)
264 FILE *f;
266 if ((f = fopen(known_hosts_file, "a")) == NULL)
267 return -1;
268 fprintf(f, "%s %s %d\n", e->domain, e->hash, e->verified);
269 fclose(f);
270 return 0;
273 int
274 update_cert(const struct tofu_entry *e)
276 FILE *tmp, *f;
277 char sfn[PATH_MAX], *line = NULL, *t;
278 size_t l, linesize = 0;
279 ssize_t linelen;
280 int fd, err;
282 strlcpy(sfn, known_hosts_tmp, sizeof(sfn));
283 if ((fd = mkstemp(sfn)) == -1 ||
284 (tmp = fdopen(fd, "w")) == NULL) {
285 if (fd != -1) {
286 unlink(sfn);
287 close(fd);
289 return -1;
292 if ((f = fopen(known_hosts_file, "r")) == NULL) {
293 unlink(sfn);
294 fclose(tmp);
295 return -1;
298 l = strlen(e->domain);
299 while ((linelen = getline(&line, &linesize, f)) != -1) {
300 if ((t = strstr(line, e->domain)) != NULL &&
301 (line[l] == ' ' || line[l] == '\t'))
302 continue;
303 /* line has a trailing \n */
304 fprintf(tmp, "%s", line);
306 fprintf(tmp, "%s %s %d\n", e->domain, e->hash, e->verified);
308 free(line);
309 err = ferror(tmp);
311 fclose(tmp);
312 fclose(f);
314 if (err) {
315 unlink(sfn);
316 return -1;
319 if (rename(sfn, known_hosts_file))
320 return -1;
321 return 0;
324 static size_t
325 join_path(char *buf, const char *lhs, const char *rhs, size_t buflen)
327 strlcpy(buf, lhs, buflen);
328 return strlcat(buf, rhs, buflen);
331 static void
332 getenv_default(char *buf, const char *name, const char *def, size_t buflen)
334 size_t ret;
335 char *home, *env;
337 if ((home = getenv("HOME")) == NULL)
338 errx(1, "HOME is not defined");
340 if ((env = getenv(name)) != NULL)
341 ret = strlcpy(buf, env, buflen);
342 else
343 ret = join_path(buf, home, def, buflen);
345 if (ret >= buflen)
346 errx(1, "buffer too small for %s", name);
349 static void
350 mkdirs(const char *path, mode_t mode)
352 char copy[PATH_MAX+1], orig[PATH_MAX+1], *parent;
354 strlcpy(copy, path, sizeof(copy));
355 strlcpy(orig, path, sizeof(orig));
356 parent = dirname(copy);
357 if (!strcmp(parent, "/"))
358 return;
359 mkdirs(parent, mode);
361 if (mkdir(orig, mode) != 0) {
362 if (errno == EEXIST)
363 return;
364 err(1, "can't mkdir %s", orig);
368 static void
369 init_paths(void)
371 char xdg_config_base[PATH_MAX];
372 char xdg_data_base[PATH_MAX];
373 char xdg_cache_base[PATH_MAX];
374 char old_path[PATH_MAX];
375 char *home;
376 struct stat info;
378 /* old path */
379 if ((home = getenv("HOME")) == NULL)
380 errx(1, "HOME is not defined");
381 join_path(old_path, home, "/.telescope", sizeof(old_path));
383 /* if ~/.telescope exists, use that instead of xdg dirs */
384 if (stat(old_path, &info) == 0 && S_ISDIR(info.st_mode)) {
385 join_path(config_path_base, home, "/.telescope",
386 sizeof(config_path_base));
387 join_path(data_path_base, home, "/.telescope",
388 sizeof(data_path_base));
389 join_path(cache_path_base, home, "/.telescope",
390 sizeof(cache_path_base));
391 return;
394 /* xdg paths */
395 getenv_default(xdg_config_base, "XDG_CONFIG_HOME", "/.config",
396 sizeof(xdg_config_base));
397 getenv_default(xdg_data_base, "XDG_DATA_HOME", "/.local/share",
398 sizeof(xdg_data_base));
399 getenv_default(xdg_cache_base, "XDG_CACHE_HOME", "/.cache",
400 sizeof(xdg_cache_base));
402 join_path(config_path_base, xdg_config_base, "/telescope",
403 sizeof(config_path_base));
404 join_path(data_path_base, xdg_data_base, "/telescope",
405 sizeof(data_path_base));
406 join_path(cache_path_base, xdg_cache_base, "/telescope",
407 sizeof(cache_path_base));
409 mkdirs(xdg_config_base, S_IRWXU);
410 mkdirs(xdg_data_base, S_IRWXU);
411 mkdirs(xdg_cache_base, S_IRWXU);
413 mkdirs(config_path_base, S_IRWXU);
414 mkdirs(data_path_base, S_IRWXU);
415 mkdirs(cache_path_base, S_IRWXU);
418 int
419 fs_init(void)
421 init_paths();
423 join_path(ctlsock_path, cache_path_base, "/ctl",
424 sizeof(ctlsock_path));
425 join_path(config_path, config_path_base, "/config",
426 sizeof(config_path));
427 join_path(lockfile_path, cache_path_base, "/lock",
428 sizeof(lockfile_path));
429 join_path(bookmark_file, data_path_base, "/bookmarks.gmi",
430 sizeof(bookmark_file));
431 join_path(known_hosts_file, data_path_base, "/known_hosts",
432 sizeof(known_hosts_file));
433 join_path(known_hosts_tmp, cache_path_base,
434 "/known_hosts.tmp.XXXXXXXXXX", sizeof(known_hosts_tmp));
435 join_path(session_file, cache_path_base, "/session",
436 sizeof(session_file));
437 join_path(session_file_tmp, cache_path_base, "/session.XXXXXXXXXX",
438 sizeof(session_file));
439 join_path(history_file, cache_path_base, "/history",
440 sizeof(history_file));
441 join_path(history_file_tmp, cache_path_base, "/history.XXXXXXXXXX",
442 sizeof(history_file));
443 join_path(crashed_file, cache_path_base, "/crashed",
444 sizeof(crashed_file));
446 return 1;
449 /*
450 * Parse a line of the session file and restores it. The format is:
452 * URL [flags,...] [title]\n
453 */
454 static inline struct tab *
455 parse_session_line(char *line, struct tab **ct)
457 struct tab *tab;
458 char *s, *t, *ap;
459 const char *uri, *title = "";
460 int current = 0, killed = 0;
461 size_t top_line = 0, current_line = 0;
463 uri = line;
464 if ((s = strchr(line, ' ')) == NULL)
465 return NULL;
467 *s++ = '\0';
469 if ((t = strchr(s, ' ')) != NULL) {
470 *t++ = '\0';
471 title = t;
474 while ((ap = strsep(&s, ",")) != NULL) {
475 if (!strcmp(ap, "current"))
476 current = 1;
477 else if (!strcmp(ap, "killed"))
478 killed = 1;
479 else if (has_prefix(ap, "top="))
480 top_line = strtonum(ap+4, 0, UINT32_MAX, NULL);
481 else if (has_prefix(ap, "cur="))
482 current_line = strtonum(ap+4, 0, UINT32_MAX, NULL);
485 if (top_line > current_line) {
486 top_line = 0;
487 current_line = 0;
490 if ((tab = new_tab(uri, NULL, NULL)) == NULL)
491 die();
492 tab->hist_cur->line_off = top_line;
493 tab->hist_cur->current_off = current_line;
494 strlcpy(tab->buffer.page.title, title, sizeof(tab->buffer.page.title));
496 if (current)
497 *ct = tab;
498 else if (killed)
499 kill_tab(tab, 1);
501 return tab;
504 static inline void
505 sendhist(struct tab *tab, const char *uri, int future)
507 struct hist *h;
509 if ((h = calloc(1, sizeof(*h))) == NULL)
510 die();
511 strlcpy(h->h, uri, sizeof(h->h));
513 if (future)
514 hist_push(&tab->hist, h);
515 else
516 hist_add_before(&tab->hist, tab->hist_cur, h);
519 static void
520 load_last_session(void)
522 struct tab *tab = NULL, *ct = NULL;
523 FILE *session;
524 size_t linesize = 0;
525 ssize_t linelen;
526 int future;
527 char *nl, *s, *line = NULL;
529 if ((session = fopen(session_file, "r")) == NULL) {
530 new_tab("about:new", NULL, NULL);
531 switch_to_tab(new_tab("about:help", NULL, NULL));
532 return;
535 while ((linelen = getline(&line, &linesize, session)) != -1) {
536 if ((nl = strchr(line, '\n')) != NULL)
537 *nl = '\0';
539 if (*line == '<' || *line == '>') {
540 future = *line == '>';
541 s = line+1;
542 if (*s != ' ' || tab == NULL)
543 continue;
544 sendhist(tab, ++s, future);
545 } else {
546 tab = parse_session_line(line, &ct);
550 fclose(session);
551 free(line);
553 if (ct != NULL)
554 switch_to_tab(ct);
556 if (last_time_crashed())
557 switch_to_tab(new_tab("about:crash", NULL, NULL));
560 static void
561 load_hist(void)
563 FILE *hist;
564 size_t linesize = 0;
565 ssize_t linelen;
566 char *nl, *spc, *line = NULL;
567 const char *errstr;
568 struct histitem hi;
570 if ((hist = fopen(history_file, "r")) == NULL)
571 return;
573 while ((linelen = getline(&line, &linesize, hist)) != -1) {
574 if ((nl = strchr(line, '\n')) != NULL)
575 *nl = '\0';
576 if ((spc = strchr(line, ' ')) == NULL)
577 continue;
578 *spc = '\0';
579 spc++;
581 memset(&hi, 0, sizeof(hi));
582 hi.ts = strtonum(line, INT64_MIN, INT64_MAX, &errstr);
583 if (errstr != NULL)
584 continue;
585 if (strlcpy(hi.uri, spc, sizeof(hi.uri)) >= sizeof(hi.uri))
586 continue;
588 history_push(&hi);
591 fclose(hist);
592 free(line);
594 history_sort();
597 int
598 fs_load_state(struct ohash *certs)
600 load_certs(certs);
601 load_hist();
602 load_last_session();
603 return 0;
606 /*
607 * Check if the last time telescope crashed. The check is done by
608 * looking at `crashed_file': if it exists then last time we crashed.
609 * Then, while here, touch the file too. During IMSG_QUIT we'll
610 * remove it.
611 */
612 static int
613 last_time_crashed(void)
615 int fd, crashed = 1;
617 if (safe_mode)
618 return 0;
620 if (unlink(crashed_file) == -1 && errno == ENOENT)
621 crashed = 0;
623 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
624 return crashed;
625 close(fd);
627 return crashed;
630 int
631 lock_session(void)
633 struct flock lock;
634 int fd;
636 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
637 return -1;
639 lock.l_start = 0;
640 lock.l_len = 0;
641 lock.l_type = F_WRLCK;
642 lock.l_whence = SEEK_SET;
644 if (fcntl(fd, F_SETLK, &lock) == -1) {
645 close(fd);
646 return -1;
649 return fd;
652 static inline int
653 parse_khost_line(char *line, char *tmp[3])
655 char **ap;
657 for (ap = tmp; ap < &tmp[3] &&
658 (*ap = strsep(&line, " \t\n")) != NULL;) {
659 if (**ap != '\0')
660 ap++;
663 return ap == &tmp[3] && *line == '\0';
666 static void
667 load_certs(struct ohash *certs)
669 char *tmp[3], *line = NULL;
670 const char *errstr;
671 size_t lineno = 0, linesize = 0;
672 ssize_t linelen;
673 FILE *f;
674 struct tofu_entry *e;
676 if ((f = fopen(known_hosts_file, "r")) == NULL)
677 return;
679 if ((e = calloc(1, sizeof(*e))) == NULL) {
680 fclose(f);
681 return;
684 while ((linelen = getline(&line, &linesize, f)) != -1) {
685 lineno++;
687 if (parse_khost_line(line, tmp)) {
688 strlcpy(e->domain, tmp[0], sizeof(e->domain));
689 strlcpy(e->hash, tmp[1], sizeof(e->hash));
691 e->verified = strtonum(tmp[2], 0, 1, &errstr);
692 if (errstr != NULL)
693 errx(1, "%s:%zu verification for %s is %s: %s",
694 known_hosts_file, lineno,
695 e->domain, errstr, tmp[2]);
697 tofu_add(certs, e);
698 } else {
699 warnx("%s:%zu invalid entry",
700 known_hosts_file, lineno);
704 free(line);
705 fclose(f);
706 return;