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 #include "compat.h"
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <limits.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <time.h>
26 #include <unistd.h>
28 #include "defaults.h"
29 #include "fs.h"
30 #include "minibuffer.h"
31 #include "session.h"
32 #include "ui.h"
34 struct history history;
36 static struct event autosaveev;
38 void
39 switch_to_tab(struct tab *tab)
40 {
41 current_tab = tab;
42 tab->flags &= ~TAB_URGENT;
44 if (operating && tab->flags & TAB_LAZY)
45 load_url_in_tab(tab, tab->hist_cur->h, NULL, LU_MODE_NOHIST);
46 }
48 unsigned int
49 tab_new_id(void)
50 {
51 static uint32_t tab_counter;
53 return tab_counter++;
54 }
56 struct tab *
57 new_tab(const char *url, const char *base, struct tab *after)
58 {
59 struct tab *tab;
61 ui_schedule_redraw();
62 autosave_hook();
64 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
65 event_loopbreak();
66 return NULL;
67 }
69 TAILQ_INIT(&tab->hist.head);
70 TAILQ_INIT(&tab->buffer.head);
71 TAILQ_INIT(&tab->buffer.page.head);
72 evtimer_set(&tab->loadingev, NULL, NULL);
74 tab->id = tab_new_id();
76 if (after != NULL)
77 TAILQ_INSERT_AFTER(&tabshead, after, tab, tabs);
78 else
79 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
81 if (!operating)
82 tab->flags |= TAB_LAZY;
83 load_url_in_tab(tab, url, base, 0);
84 switch_to_tab(tab);
85 return tab;
86 }
88 /*
89 * Move a tab from the tablist to the killed tab list and erase its
90 * contents. Append should always be 0 to prepend tabs so unkill_tab
91 * can work correctly; appending is only useful during startup when
92 * receiving the list of killed tabs to keep the correct order.
93 * NB: doesn't update the current_tab.
94 */
95 void
96 kill_tab(struct tab *tab, int append)
97 {
98 int count;
100 stop_tab(tab);
101 erase_buffer(&tab->buffer);
102 TAILQ_REMOVE(&tabshead, tab, tabs);
103 ui_schedule_redraw();
104 autosave_hook();
106 if (evtimer_pending(&tab->loadingev, NULL))
107 evtimer_del(&tab->loadingev);
109 if (append)
110 TAILQ_INSERT_TAIL(&ktabshead, tab, tabs);
111 else
112 TAILQ_INSERT_HEAD(&ktabshead, tab, tabs);
114 /* gc closed tabs */
115 count = 0;
116 TAILQ_FOREACH(tab, &ktabshead, tabs)
117 count++;
118 while (count > max_killed_tabs) {
119 count--;
120 free_tab(TAILQ_LAST(&ktabshead, tabshead));
124 /*
125 * Resurrects the lastest killed tab and returns it. The tab is already
126 * added to the tab list with the TAB_LAZY flag set. NB: this doesn't
127 * update current_tab.
128 */
129 struct tab *
130 unkill_tab(void)
132 struct tab *t;
134 if (TAILQ_EMPTY(&ktabshead))
135 return NULL;
137 ui_schedule_redraw();
138 autosave_hook();
140 t = TAILQ_FIRST(&ktabshead);
141 TAILQ_REMOVE(&ktabshead, t, tabs);
142 TAILQ_INSERT_TAIL(&tabshead, t, tabs);
143 t->flags |= TAB_LAZY;
144 return t;
147 /*
148 * Free every resource linked to the tab, including the tab itself, and
149 * removes it from the *killed* tablist.
150 */
151 void
152 free_tab(struct tab *tab)
154 TAILQ_REMOVE(&ktabshead, tab, tabs);
155 hist_clear(&tab->hist);
156 free(tab);
159 void
160 stop_tab(struct tab *tab)
162 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
165 static inline void
166 savetab(FILE *fp, struct tab *tab, int killed)
168 struct hist *h;
169 size_t top_line, current_line;
170 int future;
172 get_scroll_position(tab, &top_line, &current_line);
174 fprintf(fp, "%s ", tab->hist_cur->h);
175 if (tab == current_tab)
176 fprintf(fp, "current,");
177 if (killed)
178 fprintf(fp, "killed,");
180 fprintf(fp, "top=%zu,cur=%zu %s\n", top_line, current_line,
181 tab->buffer.page.title);
183 future = 0;
184 TAILQ_FOREACH(h, &tab->hist.head, entries) {
185 if (h == tab->hist_cur) {
186 future = 1;
187 continue;
190 fprintf(fp, "%s %s\n", future ? ">" : "<", h->h);
194 static void
195 save_tabs(void)
197 FILE *fp;
198 struct tab *tab;
199 int fd, err;
200 char sfn[PATH_MAX];
202 strlcpy(sfn, session_file_tmp, sizeof(sfn));
203 if ((fd = mkstemp(sfn)) == -1 ||
204 (fp = fdopen(fd, "w")) == NULL) {
205 if (fd != -1) {
206 unlink(sfn);
207 close(fd);
209 return;
212 TAILQ_FOREACH(tab, &tabshead, tabs)
213 savetab(fp, tab, 0);
214 TAILQ_FOREACH(tab, &ktabshead, tabs)
215 savetab(fp, tab, 1);
217 err = fflush(fp) == EOF;
218 fclose(fp);
220 if (err || rename(sfn, session_file) == -1)
221 unlink(sfn);
224 static void
225 save_all_history(void)
227 FILE *fp;
228 size_t i;
229 int fd, err;
230 char sfn[PATH_MAX];
232 strlcpy(sfn, history_file_tmp, sizeof(sfn));
233 if ((fd = mkstemp(sfn)) == -1 ||
234 (fp = fdopen(fd, "w")) == NULL) {
235 if (fd != -1) {
236 unlink(sfn);
237 close(fd);
239 return;
242 for (i = 0; i < history.len; ++i) {
243 history.items[i].dirty = 0;
244 fprintf(fp, "%lld %s\n", (long long)history.items[i].ts,
245 history.items[i].uri);
248 err = fflush(fp) == EOF;
249 fclose(fp);
251 if (err || rename(sfn, history_file) == -1) {
252 unlink(sfn);
253 return;
256 history.dirty = 0;
257 history.extra = 0;
260 static void
261 save_dirty_history(void)
263 FILE *fp;
264 size_t i;
266 if ((fp = fopen(history_file, "a")) == NULL)
267 return;
269 for (i = 0; i < history.len && history.dirty > 0; ++i) {
270 if (!history.items[i].dirty)
271 continue;
272 history.dirty--;
273 history.items[i].dirty = 0;
274 fprintf(fp, "%lld %s\n", (long long)history.items[i].ts,
275 history.items[i].uri);
277 history.dirty = 0;
279 fclose(fp);
282 void
283 save_session(void)
285 if (safe_mode)
286 return;
288 save_tabs();
290 if (history.extra > HISTORY_CAP/2)
291 save_all_history();
292 else if (history.dirty)
293 save_dirty_history();
296 void
297 history_push(struct histitem *hi)
299 size_t i, oldest = 0;
300 char *uri;
302 for (i = 0; i < history.len; ++i) {
303 if (history.items[i].ts < history.items[oldest].ts)
304 oldest = i;
306 /* remove duplicates */
307 if (!strcmp(history.items[i].uri, hi->uri))
308 return;
311 if ((uri = strdup(hi->uri)) == NULL)
312 abort();
314 /* don't grow too much; replace the oldest */
315 if (history.len == HISTORY_CAP) {
316 history.items[oldest].ts = hi->ts;
317 free(history.items[oldest].uri);
318 history.items[oldest].uri = uri;
320 /* Growed past the max value, signal to regen the file. */
321 history.extra++;
322 return;
325 history.items[history.len].ts = hi->ts;
326 history.items[history.len].uri = uri;
327 history.len++;
330 static int
331 history_cmp(const void *a, const void *b)
333 const struct history_item *i = a, *j = b;
334 return strcmp(i->uri, j->uri);
337 void
338 history_sort(void)
340 qsort(history.items, history.len, sizeof(history.items[0]),
341 history_cmp);
344 void
345 history_add(const char *uri)
347 size_t i, j, insert = 0, oldest = 0;
348 char *u;
349 int c;
351 for (i = 0; i < history.len; ++i) {
352 if (history.items[i].ts < history.items[oldest].ts)
353 oldest = i;
355 if (insert != 0 && insert < i)
356 continue;
358 c = strcmp(uri, history.items[i].uri);
359 if (c == 0) {
360 history.items[i].ts = time(NULL);
361 history.items[i].dirty = 1;
362 history.dirty++;
363 autosave_hook();
364 return;
367 if (c > 0)
368 insert = i;
371 if ((u = strdup(uri)) == NULL)
372 return;
374 /* if history is full, replace the oldest one */
375 if (history.len == HISTORY_CAP) {
376 free(history.items[oldest].uri);
377 history.items[oldest].uri = u;
378 history.items[oldest].ts = time(NULL);
379 history.items[oldest].dirty = 1;
380 history.dirty++;
381 history_sort();
382 autosave_hook();
383 return;
386 /* otherwise just insert in the right spot */
388 for (j = history.len; j > insert; --j)
389 memcpy(&history.items[j], &history.items[j-1],
390 sizeof(history.items[j]));
392 history.items[insert].ts = time(NULL);
393 history.items[insert].uri = u;
394 history.items[insert].dirty = 1;
395 history.dirty++;
396 history.len++;
397 autosave_hook();
400 void
401 autosave_init(void)
403 evtimer_set(&autosaveev, autosave_timer, NULL);
406 void
407 autosave_timer(int fd, short event, void *data)
409 save_session();
412 /*
413 * Function to be called in "interesting" places where we may want to
414 * schedule an autosave (like on new tab or before loading an url.)
415 */
416 void
417 autosave_hook(void)
419 struct timeval tv;
421 if (autosave <= 0)
422 return;
424 if (!evtimer_pending(&autosaveev, NULL)) {
425 tv.tv_sec = autosave;
426 tv.tv_usec = 0;
428 evtimer_add(&autosaveev, &tv);
432 static inline int
433 parse_khost_line(char *line, char *tmp[3])
435 char **ap;
437 for (ap = tmp; ap < &tmp[3] &&
438 (*ap = strsep(&line, " \t\n")) != NULL;) {
439 if (**ap != '\0')
440 ap++;
443 return ap == &tmp[3] && *line == '\0';
446 static void
447 load_certs(struct ohash *certs)
449 char *tmp[3], *line = NULL;
450 const char *errstr;
451 size_t lineno = 0, linesize = 0;
452 ssize_t linelen;
453 FILE *f;
454 struct tofu_entry *e;
456 if ((f = fopen(known_hosts_file, "r")) == NULL)
457 return;
459 if ((e = calloc(1, sizeof(*e))) == NULL) {
460 fclose(f);
461 return;
464 while ((linelen = getline(&line, &linesize, f)) != -1) {
465 lineno++;
467 if (parse_khost_line(line, tmp)) {
468 strlcpy(e->domain, tmp[0], sizeof(e->domain));
469 strlcpy(e->hash, tmp[1], sizeof(e->hash));
471 e->verified = strtonum(tmp[2], 0, 1, &errstr);
472 if (errstr != NULL)
473 errx(1, "%s:%zu verification for %s is %s: %s",
474 known_hosts_file, lineno,
475 e->domain, errstr, tmp[2]);
477 tofu_add(certs, e);
478 } else
479 warnx("%s:%zu invalid entry",
480 known_hosts_file, lineno);
483 free(line);
484 fclose(f);
485 return;
489 static void
490 load_hist(void)
492 FILE *hist;
493 size_t linesize = 0;
494 ssize_t linelen;
495 char *nl, *spc, *line = NULL;
496 const char *errstr;
497 struct histitem hi;
499 if ((hist = fopen(history_file, "r")) == NULL)
500 return;
502 while ((linelen = getline(&line, &linesize, hist)) != -1) {
503 if ((nl = strchr(line, '\n')) != NULL)
504 *nl = '\0';
505 if ((spc = strchr(line, ' ')) == NULL)
506 continue;
507 *spc = '\0';
508 spc++;
510 memset(&hi, 0, sizeof(hi));
511 hi.ts = strtonum(line, INT64_MIN, INT64_MAX, &errstr);
512 if (errstr != NULL)
513 continue;
514 if (strlcpy(hi.uri, spc, sizeof(hi.uri)) >= sizeof(hi.uri))
515 continue;
517 history_push(&hi);
520 fclose(hist);
521 free(line);
523 history_sort();
526 /*
527 * Check if the last time telescope crashed. The check is done by
528 * looking at `crashed_file': if it exists then last time we crashed.
529 * Then, while here, touch the file too, it's removed during the
530 * teardown.
531 */
532 static int
533 last_time_crashed(void)
535 int fd, crashed = 1;
537 if (safe_mode)
538 return 0;
540 if (unlink(crashed_file) == -1 && errno == ENOENT)
541 crashed = 0;
543 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
544 return crashed;
545 close(fd);
547 return crashed;
550 /*
551 * Parse and restore a tab from the session file. The format is:
553 * URL [flags,...] [title]\n
554 */
555 static inline struct tab *
556 parse_tab_line(char *line, struct tab **ct)
558 struct tab *tab;
559 char *s, *t, *ap;
560 const char *uri, *title = "";
561 int current = 0, killed = 0;
562 size_t tline = 0, cline = 0;
564 uri = line;
565 if ((s = strchr(line, ' ')) == NULL)
566 return NULL;
567 *s++ = '\0';
569 if ((t = strchr(s, ' ')) != NULL) {
570 *t++ = '\0';
571 title = t;
574 while ((ap = strsep(&s, ",")) != NULL) {
575 if (!strcmp(ap, "current"))
576 current = 1;
577 else if (!strcmp(ap, "killed"))
578 killed = 1;
579 else if (!strncmp(ap, "top=", 4))
580 tline = strtonum(ap+4, 0, UINT32_MAX, NULL);
581 else if (!strncmp(ap, "cur=", 4))
582 cline = strtonum(ap + 4, 0, UINT32_MAX, NULL);
585 if (tline > cline) {
586 tline = 0;
587 cline = 0;
590 if ((tab = new_tab(uri, NULL, NULL)) == NULL)
591 err(1, "new_tab");
592 tab->hist_cur->line_off = tline;
593 tab->hist_cur->current_off = cline;
594 strlcpy(tab->buffer.page.title, title, sizeof(tab->buffer.page.title));
596 if (current)
597 *ct = tab;
598 else if (killed)
599 kill_tab(tab, 1);
601 return tab;
604 static void
605 load_tabs(void)
607 struct tab *tab = NULL, *ct = NULL;
608 struct hist *h;
609 FILE *session;
610 size_t lineno = 0, linesize = 0;
611 ssize_t linelen;
612 char *uri, *line = NULL;
614 if ((session = fopen(session_file, "r")) == NULL) {
615 new_tab("about:new", NULL, NULL);
616 new_tab("about:help", NULL, NULL);
617 return;
620 while ((linelen = getline(&line, &linesize, session)) != -1) {
621 lineno++;
623 if (linelen > 0 && line[linelen-1] == '\n')
624 line[linelen-1] = '\0';
626 if (*line == '<' || *line == '>') {
627 uri = line + 1;
628 if (*uri != ' ' || tab == NULL) {
629 fprintf(stderr, "%s:%zu invalid line\n",
630 session_file, lineno);
631 continue;
633 uri++;
635 if ((h = calloc(1, sizeof(*h))) == NULL)
636 err(1, "calloc");
637 strlcpy(h->h, uri, sizeof(h->h));
639 if (*line == '>') /* future hist */
640 hist_push(&tab->hist, h);
641 else
642 hist_add_before(&tab->hist, tab->hist_cur, h);
643 } else
644 tab = parse_tab_line(line, &ct);
647 fclose(session);
648 free(line);
650 if (ct == NULL || TAILQ_EMPTY(&tabshead))
651 ct = new_tab("about:new", NULL, NULL);
653 switch_to_tab(ct);
655 if (last_time_crashed())
656 new_tab("about:crash", NULL, NULL);
659 int
660 load_session(struct ohash *certs)
662 load_certs(certs);
663 load_hist();
664 load_tabs();
665 return 0;
668 int
669 lock_session(void)
671 struct flock lock;
672 int fd;
674 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
675 return -1;
677 lock.l_start = 0;
678 lock.l_len = 0;
679 lock.l_type = F_WRLCK;
680 lock.l_whence = SEEK_SET;
682 if (fcntl(fd, F_SETLK, &lock) == -1) {
683 close(fd);
684 return -1;
687 return fd;