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 "hist.h"
31 #include "minibuffer.h"
32 #include "session.h"
33 #include "tofu.h"
34 #include "ui.h"
36 struct history history;
38 static struct event autosaveev;
40 void
41 switch_to_tab(struct tab *tab)
42 {
43 current_tab = tab;
44 tab->flags &= ~TAB_URGENT;
46 if (operating && tab->flags & TAB_LAZY)
47 load_url_in_tab(tab, hist_cur(tab->hist), NULL,
48 LU_MODE_NOHIST);
49 }
51 unsigned int
52 tab_new_id(void)
53 {
54 static uint32_t tab_counter;
56 return tab_counter++;
57 }
59 struct tab *
60 new_tab(const char *url, const char *base, struct tab *after)
61 {
62 struct tab *tab;
64 ui_schedule_redraw();
65 autosave_hook();
67 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
68 event_loopbreak();
69 return NULL;
70 }
72 if ((tab->hist = hist_new(HIST_LINEAR)) == NULL) {
73 free(tab);
74 event_loopbreak();
75 return NULL;
76 }
78 TAILQ_INIT(&tab->buffer.head);
79 TAILQ_INIT(&tab->buffer.page.head);
80 evtimer_set(&tab->loadingev, NULL, NULL);
82 tab->id = tab_new_id();
84 if (after != NULL)
85 TAILQ_INSERT_AFTER(&tabshead, after, tab, tabs);
86 else
87 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
89 if (!operating)
90 tab->flags |= TAB_LAZY;
91 load_url_in_tab(tab, url, base, 0);
92 switch_to_tab(tab);
93 return tab;
94 }
96 /*
97 * Move a tab from the tablist to the killed tab list and erase its
98 * contents. Append should always be 0 to prepend tabs so unkill_tab
99 * can work correctly; appending is only useful during startup when
100 * receiving the list of killed tabs to keep the correct order.
101 * NB: doesn't update the current_tab.
102 */
103 void
104 kill_tab(struct tab *tab, int append)
106 int count;
108 stop_tab(tab);
109 erase_buffer(&tab->buffer);
110 TAILQ_REMOVE(&tabshead, tab, tabs);
111 ui_schedule_redraw();
112 autosave_hook();
114 if (evtimer_pending(&tab->loadingev, NULL))
115 evtimer_del(&tab->loadingev);
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.page.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 if ((uri = strdup(hi->uri)) == NULL)
318 abort();
320 /* don't grow too much; replace the oldest */
321 if (history.len == HISTORY_CAP) {
322 history.items[oldest].ts = hi->ts;
323 free(history.items[oldest].uri);
324 history.items[oldest].uri = uri;
326 /* Growed past the max value, signal to regen the file. */
327 history.extra++;
328 return;
331 history.items[history.len].ts = hi->ts;
332 history.items[history.len].uri = uri;
333 history.len++;
336 static int
337 history_cmp(const void *a, const void *b)
339 const struct history_item *i = a, *j = b;
340 return strcmp(i->uri, j->uri);
343 void
344 history_sort(void)
346 qsort(history.items, history.len, sizeof(history.items[0]),
347 history_cmp);
350 void
351 history_add(const char *uri)
353 size_t i, j, insert = 0, oldest = 0;
354 char *u;
355 int c;
357 for (i = 0; i < history.len; ++i) {
358 if (history.items[i].ts < history.items[oldest].ts)
359 oldest = i;
361 if (insert != 0 && insert < i)
362 continue;
364 c = strcmp(uri, history.items[i].uri);
365 if (c == 0) {
366 history.items[i].ts = time(NULL);
367 history.items[i].dirty = 1;
368 history.dirty++;
369 autosave_hook();
370 return;
373 if (c > 0)
374 insert = i;
377 if ((u = strdup(uri)) == NULL)
378 return;
380 /* if history is full, replace the oldest one */
381 if (history.len == HISTORY_CAP) {
382 free(history.items[oldest].uri);
383 history.items[oldest].uri = u;
384 history.items[oldest].ts = time(NULL);
385 history.items[oldest].dirty = 1;
386 history.dirty++;
387 history_sort();
388 autosave_hook();
389 return;
392 /* otherwise just insert in the right spot */
394 for (j = history.len; j > insert; --j)
395 memcpy(&history.items[j], &history.items[j-1],
396 sizeof(history.items[j]));
398 history.items[insert].ts = time(NULL);
399 history.items[insert].uri = u;
400 history.items[insert].dirty = 1;
401 history.dirty++;
402 history.len++;
403 autosave_hook();
406 void
407 autosave_init(void)
409 evtimer_set(&autosaveev, autosave_timer, NULL);
412 void
413 autosave_timer(int fd, short event, void *data)
415 save_session();
418 /*
419 * Function to be called in "interesting" places where we may want to
420 * schedule an autosave (like on new tab or before loading an url.)
421 */
422 void
423 autosave_hook(void)
425 struct timeval tv;
427 if (autosave <= 0)
428 return;
430 if (!evtimer_pending(&autosaveev, NULL)) {
431 tv.tv_sec = autosave;
432 tv.tv_usec = 0;
434 evtimer_add(&autosaveev, &tv);
438 static inline int
439 parse_khost_line(char *line, char *tmp[3])
441 char **ap;
443 for (ap = tmp; ap < &tmp[3] &&
444 (*ap = strsep(&line, " \t\n")) != NULL;) {
445 if (**ap != '\0')
446 ap++;
449 return ap == &tmp[3] && *line == '\0';
452 static void
453 load_certs(struct ohash *certs)
455 char *tmp[3], *line = NULL;
456 const char *errstr;
457 size_t lineno = 0, linesize = 0;
458 ssize_t linelen;
459 FILE *f;
460 struct tofu_entry *e;
462 if ((f = fopen(known_hosts_file, "r")) == NULL)
463 return;
465 if ((e = calloc(1, sizeof(*e))) == NULL) {
466 fclose(f);
467 return;
470 while ((linelen = getline(&line, &linesize, f)) != -1) {
471 lineno++;
473 if (parse_khost_line(line, tmp)) {
474 strlcpy(e->domain, tmp[0], sizeof(e->domain));
475 strlcpy(e->hash, tmp[1], sizeof(e->hash));
477 e->verified = strtonum(tmp[2], 0, 1, &errstr);
478 if (errstr != NULL)
479 errx(1, "%s:%zu verification for %s is %s: %s",
480 known_hosts_file, lineno,
481 e->domain, errstr, tmp[2]);
483 tofu_add(certs, e);
484 } else
485 warnx("%s:%zu invalid entry",
486 known_hosts_file, lineno);
489 free(line);
490 fclose(f);
491 return;
495 static void
496 load_hist(void)
498 FILE *hist;
499 size_t linesize = 0;
500 ssize_t linelen;
501 char *nl, *spc, *line = NULL;
502 const char *errstr;
503 struct histitem hi;
505 if ((hist = fopen(history_file, "r")) == NULL)
506 return;
508 while ((linelen = getline(&line, &linesize, hist)) != -1) {
509 if ((nl = strchr(line, '\n')) != NULL)
510 *nl = '\0';
511 if ((spc = strchr(line, ' ')) == NULL)
512 continue;
513 *spc = '\0';
514 spc++;
516 memset(&hi, 0, sizeof(hi));
517 hi.ts = strtonum(line, INT64_MIN, INT64_MAX, &errstr);
518 if (errstr != NULL)
519 continue;
520 if (strlcpy(hi.uri, spc, sizeof(hi.uri)) >= sizeof(hi.uri))
521 continue;
523 history_push(&hi);
526 fclose(hist);
527 free(line);
529 history_sort();
532 /*
533 * Check if the last time telescope crashed. The check is done by
534 * looking at `crashed_file': if it exists then last time we crashed.
535 * Then, while here, touch the file too, it's removed during the
536 * teardown.
537 */
538 static int
539 last_time_crashed(void)
541 int fd, crashed = 1;
543 if (safe_mode)
544 return 0;
546 if (unlink(crashed_file) == -1 && errno == ENOENT)
547 crashed = 0;
549 if ((fd = open(crashed_file, O_CREAT|O_WRONLY, 0600)) == -1)
550 return crashed;
551 close(fd);
553 return crashed;
556 /*
557 * Parse and restore a tab from the session file. The format is:
559 * URL [flags,...] [title]\n
560 */
561 static inline struct tab *
562 parse_tab_line(char *line, struct tab **ct)
564 struct tab *tab;
565 char *s, *t, *ap;
566 const char *uri, *title = "";
567 int current = 0, killed = 0;
568 size_t tline = 0, cline = 0;
570 uri = line;
571 if ((s = strchr(line, ' ')) == NULL)
572 return NULL;
573 *s++ = '\0';
575 if ((t = strchr(s, ' ')) != NULL) {
576 *t++ = '\0';
577 title = t;
580 while ((ap = strsep(&s, ",")) != NULL) {
581 if (!strcmp(ap, "current"))
582 current = 1;
583 else if (!strcmp(ap, "killed"))
584 killed = 1;
585 else if (!strncmp(ap, "top=", 4))
586 tline = strtonum(ap+4, 0, UINT32_MAX, NULL);
587 else if (!strncmp(ap, "cur=", 4))
588 cline = strtonum(ap + 4, 0, UINT32_MAX, NULL);
591 if (tline > cline) {
592 tline = 0;
593 cline = 0;
596 if ((tab = new_tab(uri, NULL, NULL)) == NULL)
597 err(1, "new_tab");
598 hist_set_offs(tab->hist, tline, cline);
599 strlcpy(tab->buffer.page.title, title, sizeof(tab->buffer.page.title));
601 if (current)
602 *ct = tab;
603 else if (killed)
604 kill_tab(tab, 1);
606 return tab;
609 static void
610 load_tabs(void)
612 struct tab *tab = NULL, *ct = NULL;
613 FILE *session;
614 size_t lineno = 0, linesize = 0;
615 ssize_t linelen;
616 char *uri, *line = NULL;
618 if ((session = fopen(session_file, "r")) == NULL) {
619 new_tab("about:new", NULL, NULL);
620 new_tab("about:help", NULL, NULL);
621 return;
624 while ((linelen = getline(&line, &linesize, session)) != -1) {
625 lineno++;
627 if (linelen > 0 && line[linelen-1] == '\n')
628 line[linelen-1] = '\0';
630 if (*line == '<' || *line == '>') {
631 uri = line + 1;
632 if (*uri != ' ' || tab == NULL) {
633 fprintf(stderr, "%s:%zu invalid line\n",
634 session_file, lineno);
635 continue;
637 uri++;
639 if (*line == '>') /* future hist */
640 hist_append(tab->hist, uri);
641 else
642 hist_prepend(tab->hist, uri);
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;