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 <sys/time.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <time.h>
28 #include <unistd.h>
30 #include "defaults.h"
31 #include "ev.h"
32 #include "fs.h"
33 #include "hist.h"
34 #include "imsgev.h"
35 #include "minibuffer.h"
36 #include "session.h"
37 #include "tofu.h"
38 #include "ui.h"
39 #include "xwrapper.h"
41 struct history history;
43 static unsigned int autosavetimer;
45 void
46 switch_to_tab(struct tab *tab)
47 {
48 current_tab = tab;
49 tab->flags &= ~TAB_URGENT;
51 if (operating && tab->flags & TAB_LAZY)
52 load_url_in_tab(tab, hist_cur(tab->hist), NULL,
53 LU_MODE_NOHIST);
54 }
56 unsigned int
57 tab_new_id(void)
58 {
59 static uint32_t tab_counter;
61 return tab_counter++;
62 }
64 struct tab *
65 new_tab(const char *url, const char *base, struct tab *after)
66 {
67 struct tab *tab;
69 ui_schedule_redraw();
70 autosave_hook();
72 tab = xcalloc(1, sizeof(*tab));
74 if ((tab->hist = hist_new(HIST_LINEAR)) == NULL) {
75 free(tab);
76 ev_break();
77 return NULL;
78 }
80 TAILQ_INIT(&tab->buffer.head);
81 TAILQ_INIT(&tab->buffer.vhead);
83 tab->id = tab_new_id();
85 if (after != NULL)
86 TAILQ_INSERT_AFTER(&tabshead, after, tab, tabs);
87 else
88 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
90 if (!operating)
91 tab->flags |= TAB_LAZY;
92 load_url_in_tab(tab, url, base, 0);
93 switch_to_tab(tab);
94 return tab;
95 }
97 /*
98 * Move a tab from the tablist to the killed tab list and erase its
99 * contents. Append should always be 0 to prepend tabs so unkill_tab
100 * can work correctly; appending is only useful during startup when
101 * receiving the list of killed tabs to keep the correct order.
102 * NB: doesn't update the current_tab.
103 */
104 void
105 kill_tab(struct tab *tab, int append)
107 int count;
109 stop_tab(tab);
110 erase_buffer(&tab->buffer);
111 TAILQ_REMOVE(&tabshead, tab, tabs);
112 ui_schedule_redraw();
113 autosave_hook();
115 ev_timer_cancel(tab->loading_timer);
117 if (append)
118 TAILQ_INSERT_TAIL(&ktabshead, tab, tabs);
119 else
120 TAILQ_INSERT_HEAD(&ktabshead, tab, tabs);
122 /* gc closed tabs */
123 count = 0;
124 TAILQ_FOREACH(tab, &ktabshead, tabs)
125 count++;
126 while (count > max_killed_tabs) {
127 count--;
128 free_tab(TAILQ_LAST(&ktabshead, tabshead));
132 /*
133 * Resurrects the lastest killed tab and returns it. The tab is already
134 * added to the tab list with the TAB_LAZY flag set. NB: this doesn't
135 * update current_tab.
136 */
137 struct tab *
138 unkill_tab(void)
140 struct tab *t;
142 if (TAILQ_EMPTY(&ktabshead))
143 return NULL;
145 ui_schedule_redraw();
146 autosave_hook();
148 t = TAILQ_FIRST(&ktabshead);
149 TAILQ_REMOVE(&ktabshead, t, tabs);
150 TAILQ_INSERT_TAIL(&tabshead, t, tabs);
151 t->flags |= TAB_LAZY;
152 return t;
155 /*
156 * Free every resource linked to the tab, including the tab itself, and
157 * removes it from the *killed* tablist.
158 */
159 void
160 free_tab(struct tab *tab)
162 TAILQ_REMOVE(&ktabshead, tab, tabs);
163 hist_free(tab->hist);
164 free(tab);
167 void
168 stop_tab(struct tab *tab)
170 ui_send_net(IMSG_STOP, tab->id, -1, NULL, 0);
173 static inline void
174 savetab(FILE *fp, struct tab *tab, int killed)
176 size_t i, size, cur;
177 size_t top_line, current_line;
179 get_scroll_position(tab, &top_line, &current_line);
181 fprintf(fp, "%s ", hist_cur(tab->hist));
182 if (tab == current_tab)
183 fprintf(fp, "current,");
184 if (killed)
185 fprintf(fp, "killed,");
187 fprintf(fp, "top=%zu,cur=%zu %s\n", top_line, current_line,
188 tab->buffer.title);
190 cur = hist_off(tab->hist);
191 size = hist_size(tab->hist);
192 for (i = 0; i < size; ++i) {
193 if (i == cur)
194 continue;
195 fprintf(fp, "%s %s\n", i > cur ? ">" : "<",
196 hist_nth(tab->hist, i));
200 static void
201 save_tabs(void)
203 FILE *fp;
204 struct tab *tab;
205 int fd, err;
206 char sfn[PATH_MAX];
208 strlcpy(sfn, session_file_tmp, sizeof(sfn));
209 if ((fd = mkstemp(sfn)) == -1 ||
210 (fp = fdopen(fd, "w")) == NULL) {
211 if (fd != -1) {
212 unlink(sfn);
213 close(fd);
215 return;
218 TAILQ_FOREACH(tab, &tabshead, tabs)
219 savetab(fp, tab, 0);
220 TAILQ_FOREACH(tab, &ktabshead, tabs)
221 savetab(fp, tab, 1);
223 err = fflush(fp) == EOF;
224 fclose(fp);
226 if (err || rename(sfn, session_file) == -1)
227 unlink(sfn);
230 static void
231 save_all_history(void)
233 FILE *fp;
234 size_t i;
235 int fd, err;
236 char sfn[PATH_MAX];
238 strlcpy(sfn, history_file_tmp, sizeof(sfn));
239 if ((fd = mkstemp(sfn)) == -1 ||
240 (fp = fdopen(fd, "w")) == NULL) {
241 if (fd != -1) {
242 unlink(sfn);
243 close(fd);
245 return;
248 for (i = 0; i < history.len; ++i) {
249 history.items[i].dirty = 0;
250 fprintf(fp, "%lld %s\n", (long long)history.items[i].ts,
251 history.items[i].uri);
254 err = fflush(fp) == EOF;
255 fclose(fp);
257 if (err || rename(sfn, history_file) == -1) {
258 unlink(sfn);
259 return;
262 history.dirty = 0;
263 history.extra = 0;
266 static void
267 save_dirty_history(void)
269 FILE *fp;
270 size_t i;
272 if ((fp = fopen(history_file, "a")) == NULL)
273 return;
275 for (i = 0; i < history.len && history.dirty > 0; ++i) {
276 if (!history.items[i].dirty)
277 continue;
278 history.dirty--;
279 history.items[i].dirty = 0;
280 fprintf(fp, "%lld %s\n", (long long)history.items[i].ts,
281 history.items[i].uri);
283 history.dirty = 0;
285 fclose(fp);
288 void
289 save_session(void)
291 if (safe_mode)
292 return;
294 save_tabs();
296 if (history.extra > HISTORY_CAP/2)
297 save_all_history();
298 else if (history.dirty)
299 save_dirty_history();
302 void
303 history_push(struct histitem *hi)
305 size_t i, oldest = 0;
306 char *uri;
308 for (i = 0; i < history.len; ++i) {
309 if (history.items[i].ts < history.items[oldest].ts)
310 oldest = i;
312 /* remove duplicates */
313 if (!strcmp(history.items[i].uri, hi->uri))
314 return;
317 uri = xstrdup(hi->uri);
319 /* don't grow too much; replace the oldest */
320 if (history.len == HISTORY_CAP) {
321 history.items[oldest].ts = hi->ts;
322 free(history.items[oldest].uri);
323 history.items[oldest].uri = uri;
325 /* Growed past the max value, signal to regen the file. */
326 history.extra++;
327 return;
330 history.items[history.len].ts = hi->ts;
331 history.items[history.len].uri = uri;
332 history.len++;
335 static int
336 history_cmp(const void *a, const void *b)
338 const struct history_item *i = a, *j = b;
339 return strcmp(i->uri, j->uri);
342 void
343 history_sort(void)
345 qsort(history.items, history.len, sizeof(history.items[0]),
346 history_cmp);
349 void
350 history_add(const char *uri)
352 size_t i, j, insert = 0, oldest = 0;
353 char *u;
354 int c;
356 for (i = 0; i < history.len; ++i) {
357 if (history.items[i].ts < history.items[oldest].ts)
358 oldest = i;
360 if (insert != 0 && insert < i)
361 continue;
363 c = strcmp(uri, history.items[i].uri);
364 if (c == 0) {
365 history.items[i].ts = time(NULL);
366 history.items[i].dirty = 1;
367 history.dirty++;
368 autosave_hook();
369 return;
372 if (c > 0)
373 insert = i;
376 u = xstrdup(uri);
378 /* if history is full, replace the oldest one */
379 if (history.len == HISTORY_CAP) {
380 free(history.items[oldest].uri);
381 history.items[oldest].uri = u;
382 history.items[oldest].ts = time(NULL);
383 history.items[oldest].dirty = 1;
384 history.dirty++;
385 history_sort();
386 autosave_hook();
387 return;
390 /* otherwise just insert in the right spot */
392 for (j = history.len; j > insert; --j)
393 memcpy(&history.items[j], &history.items[j-1],
394 sizeof(history.items[j]));
396 history.items[insert].ts = time(NULL);
397 history.items[insert].uri = u;
398 history.items[insert].dirty = 1;
399 history.dirty++;
400 history.len++;
401 autosave_hook();
404 void
405 autosave_init(void)
407 return;
410 void
411 autosave_timer(int fd, int event, void *data)
413 save_session();
416 /*
417 * Function to be called in "interesting" places where we may want to
418 * schedule an autosave (like on new tab or before loading an url.)
419 */
420 void
421 autosave_hook(void)
423 struct timeval tv;
425 if (autosave <= 0)
426 return;
428 if (!ev_timer_pending(autosavetimer)) {
429 tv.tv_sec = autosave;
430 tv.tv_usec = 0;
432 autosavetimer = ev_timer(&tv, autosave_timer, NULL);
436 static inline int
437 parse_khost_line(char *line, char *tmp[3])
439 char **ap;
441 for (ap = tmp; ap < &tmp[3] &&
442 (*ap = strsep(&line, " \t\n")) != NULL;) {
443 if (**ap != '\0')
444 ap++;
447 return ap == &tmp[3] && *line == '\0';
450 static void
451 load_certs(struct ohash *certs)
453 char *tmp[3], *line = NULL;
454 const char *errstr;
455 size_t lineno = 0, linesize = 0;
456 ssize_t linelen;
457 FILE *f;
458 struct tofu_entry *e;
460 if ((f = fopen(known_hosts_file, "r")) == NULL)
461 return;
463 e = xcalloc(1, sizeof(*e));
465 while ((linelen = getline(&line, &linesize, f)) != -1) {
466 lineno++;
468 if (parse_khost_line(line, tmp)) {
469 strlcpy(e->domain, tmp[0], sizeof(e->domain));
470 strlcpy(e->hash, tmp[1], sizeof(e->hash));
472 e->verified = strtonum(tmp[2], 0, 1, &errstr);
473 if (errstr != NULL)
474 errx(1, "%s:%zu verification for %s is %s: %s",
475 known_hosts_file, lineno,
476 e->domain, errstr, tmp[2]);
478 tofu_add(certs, e);
479 } else
480 warnx("%s:%zu invalid entry",
481 known_hosts_file, lineno);
484 free(line);
485 fclose(f);
486 return;
490 static void
491 load_hist(void)
493 FILE *hist;
494 size_t linesize = 0;
495 ssize_t linelen;
496 char *nl, *spc, *line = NULL;
497 const char *errstr;
498 struct histitem hi;
500 if ((hist = fopen(history_file, "r")) == NULL)
501 return;
503 while ((linelen = getline(&line, &linesize, hist)) != -1) {
504 if ((nl = strchr(line, '\n')) != NULL)
505 *nl = '\0';
506 if ((spc = strchr(line, ' ')) == NULL)
507 continue;
508 *spc = '\0';
509 spc++;
511 memset(&hi, 0, sizeof(hi));
512 hi.ts = strtonum(line, INT64_MIN, INT64_MAX, &errstr);
513 if (errstr != NULL)
514 continue;
515 if (strlcpy(hi.uri, spc, sizeof(hi.uri)) >= sizeof(hi.uri))
516 continue;
518 history_push(&hi);
521 fclose(hist);
522 free(line);
524 history_sort();
527 /*
528 * Check if the last time telescope crashed. The check is done by
529 * looking at `crashed_file': if it exists then last time we crashed.
530 * Then, while here, touch the file too, it's removed during the
531 * teardown.
532 */
533 static int
534 last_time_crashed(void)
536 int fd, crashed = 1;
538 if (safe_mode)
539 return 0;
541 if (unlink(crashed_file) == -1 && errno == ENOENT)
542 crashed = 0;
544 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
545 return crashed;
546 close(fd);
548 return crashed;
551 /*
552 * Parse and restore a tab from the session file. The format is:
554 * URL [flags,...] [title]\n
555 */
556 static inline struct tab *
557 parse_tab_line(char *line, struct tab **ct)
559 struct tab *tab;
560 char *s, *t, *ap;
561 const char *uri, *title = "";
562 int current = 0, killed = 0;
563 size_t tline = 0, cline = 0;
565 uri = line;
566 if ((s = strchr(line, ' ')) == NULL)
567 return NULL;
568 *s++ = '\0';
570 if ((t = strchr(s, ' ')) != NULL) {
571 *t++ = '\0';
572 title = t;
575 while ((ap = strsep(&s, ",")) != NULL) {
576 if (!strcmp(ap, "current"))
577 current = 1;
578 else if (!strcmp(ap, "killed"))
579 killed = 1;
580 else if (!strncmp(ap, "top=", 4))
581 tline = strtonum(ap+4, 0, UINT32_MAX, NULL);
582 else if (!strncmp(ap, "cur=", 4))
583 cline = strtonum(ap + 4, 0, UINT32_MAX, NULL);
586 if (tline > cline) {
587 tline = 0;
588 cline = 0;
591 if ((tab = new_tab(uri, NULL, NULL)) == NULL)
592 err(1, "new_tab");
593 hist_set_offs(tab->hist, tline, cline);
594 strlcpy(tab->buffer.title, title, sizeof(tab->buffer.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 FILE *session;
609 size_t lineno = 0, linesize = 0;
610 ssize_t linelen;
611 char *uri, *line = NULL;
613 if ((session = fopen(session_file, "r")) == NULL) {
614 new_tab("about:new", NULL, NULL);
615 new_tab("about:help", NULL, NULL);
616 return;
619 while ((linelen = getline(&line, &linesize, session)) != -1) {
620 lineno++;
622 if (linelen > 0 && line[linelen-1] == '\n')
623 line[linelen-1] = '\0';
625 if (*line == '<' || *line == '>') {
626 uri = line + 1;
627 if (*uri != ' ' || tab == NULL) {
628 fprintf(stderr, "%s:%zu invalid line\n",
629 session_file, lineno);
630 continue;
632 uri++;
634 if (*line == '>') /* future hist */
635 hist_append(tab->hist, uri);
636 else
637 hist_prepend(tab->hist, uri);
638 } else
639 tab = parse_tab_line(line, &ct);
642 fclose(session);
643 free(line);
645 if (ct == NULL || TAILQ_EMPTY(&tabshead))
646 ct = new_tab("about:new", NULL, NULL);
648 switch_to_tab(ct);
650 if (last_time_crashed())
651 new_tab("about:crash", NULL, NULL);
654 int
655 load_session(struct ohash *certs)
657 load_certs(certs);
658 load_hist();
659 load_tabs();
660 return 0;
663 int
664 lock_session(void)
666 struct flock lock;
667 int fd;
669 if ((fd = open(lockfile_path, O_WRONLY|O_CREAT, 0600)) == -1)
670 return -1;
672 lock.l_start = 0;
673 lock.l_len = 0;
674 lock.l_type = F_WRLCK;
675 lock.l_whence = SEEK_SET;
677 if (fcntl(fd, F_SETLK, &lock) == -1) {
678 close(fd);
679 return -1;
682 return fd;