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/socket.h>
21 #include <errno.h>
22 #include <getopt.h>
23 #include <limits.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
30 #include "defaults.h"
31 #include "minibuffer.h"
32 #include "parser.h"
33 #include "telescope.h"
34 #include "ui.h"
36 static struct option longopts[] = {
37 {"colors", no_argument, NULL, 'c'},
38 {"help", no_argument, NULL, 'h'},
39 {"version", no_argument, NULL, 'v'},
40 {NULL, 0, NULL, 0},
41 };
43 static const char *opts = "Cc:hnT:v";
45 static struct imsgev *iev_fs, *iev_net;
47 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
48 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
50 enum telescope_process {
51 PROC_UI,
52 PROC_FS,
53 PROC_NET,
54 };
56 #define CANNOT_FETCH 0
57 #define TOO_MUCH_REDIRECTS 1
58 #define MALFORMED_RESPONSE 2
59 #define UNKNOWN_TYPE_OR_CSET 3
60 #define UNKNOWN_PROTOCOL 4
62 /* XXX: keep in sync with telescope.c:/^normalize_code/ */
63 const char *err_pages[70] = {
64 [CANNOT_FETCH] = "# Couldn't load the page\n",
65 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
66 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
67 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
68 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
70 [10] = "# Input required\n",
71 [11] = "# Input required\n",
72 [40] = "# Temporary failure\n",
73 [41] = "# Server unavailable\n",
74 [42] = "# CGI error\n",
75 [43] = "# Proxy error\n",
76 [44] = "# Slow down\n",
77 [50] = "# Permanent failure\n",
78 [51] = "# Not found\n",
79 [52] = "# Gone\n",
80 [53] = "# Proxy request refused\n",
81 [59] = "# Bad request\n",
82 [60] = "# Client certificate required\n",
83 [61] = "# Certificate not authorised\n",
84 [62] = "# Certificate not valid\n"
85 };
87 static void die(void) __attribute__((__noreturn__));
88 static struct tab *tab_by_id(uint32_t);
89 static void handle_imsg_err(struct imsg*, size_t);
90 static void handle_imsg_check_cert(struct imsg*, size_t);
91 static void handle_check_cert_user_choice(int, struct tab *);
92 static void handle_maybe_save_new_cert(int, struct tab *);
93 static void handle_imsg_got_code(struct imsg*, size_t);
94 static void handle_imsg_got_meta(struct imsg*, size_t);
95 static void handle_maybe_save_page(int, struct tab *);
96 static void handle_save_page_path(const char *, struct tab *);
97 static void handle_imsg_file_opened(struct imsg*, size_t);
98 static void handle_imsg_buf(struct imsg*, size_t);
99 static void handle_imsg_eof(struct imsg*, size_t);
100 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
101 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
102 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
103 static void handle_dispatch_imsg(int, short, void*);
104 static void load_page_from_str(struct tab*, const char*);
105 static void load_about_url(struct tab*, const char*);
106 static void load_finger_url(struct tab *, const char *);
107 static void load_gemini_url(struct tab*, const char*);
108 static void load_via_proxy(struct tab *, const char *,
109 struct proxy *);
110 static int do_load_url(struct tab*, const char *, const char *);
111 static void parse_session_line(char *, const char **, uint32_t *);
112 static void load_last_session(void);
113 static pid_t start_child(enum telescope_process, const char *, int);
114 static int ui_send_net(int, uint32_t, const void *, uint16_t);
115 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
117 static struct proto protos[] = {
118 { "about", load_about_url },
119 { "finger", load_finger_url },
120 { "gemini", load_gemini_url },
121 { NULL, NULL },
122 };
124 static imsg_handlerfn *handlers[] = {
125 [IMSG_ERR] = handle_imsg_err,
126 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
127 [IMSG_GOT_CODE] = handle_imsg_got_code,
128 [IMSG_GOT_META] = handle_imsg_got_meta,
129 [IMSG_BUF] = handle_imsg_buf,
130 [IMSG_EOF] = handle_imsg_eof,
131 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
132 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
133 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
134 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
135 };
137 static struct ohash certs;
139 static void __attribute__((__noreturn__))
140 die(void)
142 abort(); /* TODO */
145 static struct tab *
146 tab_by_id(uint32_t id)
148 struct tab *t;
150 TAILQ_FOREACH(t, &tabshead, tabs) {
151 if (t->id == id)
152 return t;
155 return NULL;
158 static void
159 handle_imsg_err(struct imsg *imsg, size_t datalen)
161 struct tab *tab;
162 char *page;
164 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
165 return;
167 page = imsg->data;
168 page[datalen-1] = '\0';
170 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
171 tab->hist_cur->h, page) == -1)
172 die();
173 load_page_from_str(tab, page);
174 free(page);
177 static void
178 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
180 const char *hash, *host, *port;
181 int tofu_res;
182 struct tofu_entry *e;
183 struct tab *tab;
185 hash = imsg->data;
186 if (hash[datalen-1] != '\0')
187 abort();
189 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
190 return;
192 if (tab->proxy != NULL) {
193 host = tab->proxy->host;
194 port = tab->proxy->port;
195 } else {
196 host = tab->uri.host;
197 port = tab->uri.port;
200 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
201 /* TODO: an update in libressl/libretls changed
202 * significantly. Find a better approach at storing
203 * the certs! */
204 if (datalen > sizeof(e->hash))
205 abort();
207 tofu_res = 1; /* trust on first use */
208 if ((e = calloc(1, sizeof(*e))) == NULL)
209 abort();
210 strlcpy(e->domain, host, sizeof(e->domain));
211 if (*port != '\0' && strcmp(port, "1965")) {
212 strlcat(e->domain, ":", sizeof(e->domain));
213 strlcat(e->domain, port, sizeof(e->domain));
215 strlcpy(e->hash, hash, sizeof(e->hash));
216 tofu_add(&certs, e);
217 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
218 } else
219 tofu_res = !strcmp(hash, e->hash);
221 if (tofu_res) {
222 if (e->verified == -1)
223 tab->trust = TS_TEMP_TRUSTED;
224 else if (e->verified == 1)
225 tab->trust = TS_VERIFIED;
226 else
227 tab->trust = TS_TRUSTED;
229 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
230 &tofu_res, sizeof(tofu_res));
231 } else {
232 tab->trust = TS_UNTRUSTED;
233 load_page_from_str(tab, "# Certificate mismatch\n");
234 if ((tab->cert = strdup(hash)) == NULL)
235 die();
236 ui_yornp("Certificate mismatch. Proceed?",
237 handle_check_cert_user_choice, tab);
241 static void
242 handle_check_cert_user_choice(int accept, struct tab *tab)
244 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
245 sizeof(accept));
247 if (accept) {
248 /*
249 * trust the certificate for this session only. If
250 * the page results in a redirect while we're asking
251 * the user to save, we'll end up with an invalid
252 * tabid (one request == one tab id) and crash. It
253 * also makes sense to save it for the current session
254 * if the user accepted it.
255 */
256 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
258 ui_yornp("Save the new certificate?",
259 handle_maybe_save_new_cert, tab);
260 } else {
261 free(tab->cert);
262 tab->cert = NULL;
266 static void
267 handle_maybe_save_new_cert(int accept, struct tab *tab)
269 struct tofu_entry *e;
270 const char *host, *port;
272 if (tab->proxy != NULL) {
273 host = tab->proxy->host;
274 port = tab->proxy->port;
275 } else {
276 host = tab->uri.host;
277 port = tab->uri.port;
280 if (!accept)
281 goto end;
283 if ((e = calloc(1, sizeof(*e))) == NULL)
284 die();
286 strlcpy(e->domain, host, sizeof(e->domain));
287 if (*port != '\0' && strcmp(port, "1965")) {
288 strlcat(e->domain, ":", sizeof(e->domain));
289 strlcat(e->domain, port, sizeof(e->domain));
291 strlcpy(e->hash, tab->cert, sizeof(e->hash));
292 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
294 tofu_update(&certs, e);
296 tab->trust = TS_TRUSTED;
298 end:
299 free(tab->cert);
300 tab->cert = NULL;
303 static inline int
304 normalize_code(int n)
306 if (n < 20) {
307 if (n == 10 || n == 11)
308 return n;
309 return 10;
310 } else if (n < 30) {
311 return 20;
312 } else if (n < 40) {
313 if (n == 30 || n == 31)
314 return n;
315 return 30;
316 } else if (n < 50) {
317 if (n <= 44)
318 return n;
319 return 40;
320 } else if (n < 60) {
321 if (n <= 53 || n == 59)
322 return n;
323 return 50;
324 } else if (n < 70) {
325 if (n <= 62)
326 return n;
327 return 60;
328 } else
329 return MALFORMED_RESPONSE;
332 static void
333 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
335 struct tab *tab;
337 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
338 return;
340 if (sizeof(tab->code) != datalen)
341 die();
343 memcpy(&tab->code, imsg->data, sizeof(tab->code));
344 tab->code = normalize_code(tab->code);
345 if (tab->code != 30 && tab->code != 31)
346 tab->redirect_count = 0;
349 static void
350 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
352 struct tab *tab;
354 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
355 return;
357 if (sizeof(tab->meta) <= datalen)
358 die();
360 memcpy(tab->meta, imsg->data, datalen);
362 if (tab->code < 10) { /* internal errors */
363 load_page_from_str(tab, err_pages[tab->code]);
364 } else if (tab->code < 20) { /* 1x */
365 load_page_from_str(tab, err_pages[tab->code]);
366 ui_require_input(tab, tab->code == 11);
367 } else if (tab->code == 20) {
368 if (setup_parser_for(tab)) {
369 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
370 } else {
371 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
372 ui_yornp("Can't display page, wanna save?",
373 handle_maybe_save_page, tab);
375 } else if (tab->code < 40) { /* 3x */
376 tab->redirect_count++;
378 /* TODO: make customizable? */
379 if (tab->redirect_count > 5) {
380 load_page_from_str(tab,
381 err_pages[TOO_MUCH_REDIRECTS]);
382 } else
383 do_load_url(tab, tab->meta, NULL);
384 } else { /* 4x, 5x & 6x */
385 load_page_from_str(tab, err_pages[tab->code]);
389 static void
390 handle_maybe_save_page(int dosave, struct tab *tab)
392 if (dosave)
393 ui_read("Save to path", handle_save_page_path, tab);
394 else
395 stop_tab(tab);
398 static void
399 handle_save_page_path(const char *path, struct tab *tab)
401 if (path == NULL) {
402 stop_tab(tab);
403 return;
406 tab->path = strdup(path);
408 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
411 static void
412 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
414 struct tab *tab;
415 char *page;
416 const char *e;
417 int l;
419 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
420 if (imsg->fd != -1)
421 close(imsg->fd);
422 return;
425 if (imsg->fd == -1) {
426 stop_tab(tab);
428 e = imsg->data;
429 if (e[datalen-1] != '\0')
430 die();
431 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
432 tab->path, e);
433 if (l == -1)
434 die();
435 load_page_from_str(tab, page);
436 free(page);
437 } else {
438 tab->fd = imsg->fd;
439 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
443 static void
444 handle_imsg_buf(struct imsg *imsg, size_t datalen)
446 struct tab *tab;
447 int l;
448 char *page, buf[FMT_SCALED_STRSIZE] = {0};
450 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
451 return;
453 tab->bytes += datalen;
454 if (tab->fd == -1) {
455 if (!tab->buffer.page.parse(&tab->buffer.page,
456 imsg->data, datalen))
457 die();
458 } else {
459 write(tab->fd, imsg->data, datalen);
460 fmt_scaled(tab->bytes, buf);
461 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
462 tab->path,
463 buf);
464 if (l == -1)
465 die();
466 load_page_from_str(tab, page);
467 free(page);
470 ui_on_tab_refresh(tab);
473 static void
474 handle_imsg_eof(struct imsg *imsg, size_t datalen)
476 struct tab *tab;
477 int l;
478 char *page, buf[FMT_SCALED_STRSIZE] = {0};
480 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
481 return;
483 if (tab->fd == -1) {
484 if (!tab->buffer.page.free(&tab->buffer.page))
485 die();
486 } else {
487 fmt_scaled(tab->bytes, buf);
488 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
489 tab->path,
490 buf);
491 if (l == -1)
492 die();
493 load_page_from_str(tab, page);
494 free(page);
496 close(tab->fd);
497 tab->fd = -1;
498 free(tab->path);
499 tab->path = NULL;
502 ui_on_tab_refresh(tab);
503 ui_on_tab_loaded(tab);
506 static void
507 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
509 int res;
511 if (datalen != sizeof(res))
512 die();
514 memcpy(&res, imsg->data, sizeof(res));
515 if (res == 0)
516 message("Added to bookmarks!");
517 else
518 message("Failed to add to bookmarks: %s",
519 strerror(res));
522 static void
523 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
525 int res;
527 if (datalen != sizeof(res))
528 die();
529 memcpy(&res, imsg->data, datalen);
530 if (res != 0)
531 message("Failed to save the cert for: %s",
532 strerror(res));
535 static void
536 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
538 int res;
540 if (datalen != sizeof(res))
541 die();
542 memcpy(&res, imsg->data, datalen);
543 if (!res)
544 message("Failed to update the certificate");
547 static void
548 handle_dispatch_imsg(int fd, short ev, void *d)
550 struct imsgev *iev = d;
552 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
553 err(1, "connection closed");
556 static void
557 load_page_from_str(struct tab *tab, const char *page)
559 erase_buffer(&tab->buffer);
560 gemtext_initparser(&tab->buffer.page);
561 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
562 die();
563 if (!tab->buffer.page.free(&tab->buffer.page))
564 die();
565 ui_on_tab_refresh(tab);
566 ui_on_tab_loaded(tab);
569 static void
570 load_about_url(struct tab *tab, const char *url)
572 tab->trust = TS_VERIFIED;
574 gemtext_initparser(&tab->buffer.page);
576 ui_send_fs(IMSG_GET, tab->id,
577 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
580 static void
581 load_finger_url(struct tab *tab, const char *url)
583 struct get_req req;
584 size_t len;
585 char *at;
587 stop_tab(tab);
588 tab->id = tab_new_id();
590 memset(&req, 0, sizeof(req));
591 if (*tab->uri.port != '\0')
592 strlcpy(req.port, tab->uri.port, sizeof(req.port));
593 else
594 strlcpy(req.port, "79", sizeof(req.port));
596 /*
597 * Sometimes the finger url have the user as path component
598 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
599 * userinfo (e.g. finger://cobradile@finger.farm).
600 */
601 if ((at = strchr(tab->uri.host, '@')) != NULL) {
602 len = at - tab->uri.host;
603 memcpy(req.req, tab->uri.host, len);
605 if (len >= sizeof(req.req))
606 die();
607 req.req[len] = '\0';
609 strlcpy(req.host, at+1, sizeof(req.host));
610 } else {
611 strlcpy(req.host, tab->uri.host, sizeof(req.host));
613 /* +1 to skip the initial `/' */
614 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
617 strlcat(req.req, "\r\n", sizeof(req.req));
619 req.proto = PROTO_FINGER;
621 ui_send_net(IMSG_GET_RAW, tab->id, &req, sizeof(req));
623 textplain_initparser(&tab->buffer.page);
626 static void
627 load_gemini_url(struct tab *tab, const char *url)
629 struct get_req req;
631 stop_tab(tab);
632 tab->id = tab_new_id();
634 memset(&req, 0, sizeof(req));
635 strlcpy(req.host, tab->uri.host, sizeof(req.host));
636 strlcpy(req.port, tab->uri.port, sizeof(req.host));
638 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
639 strlcat(req.req, "\r\n", sizeof(req.req));
641 req.proto = PROTO_GEMINI;
643 ui_send_net(IMSG_GET_RAW, tab->id,
644 &req, sizeof(req));
647 static void
648 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
650 struct get_req req;
652 stop_tab(tab);
653 tab->id = tab_new_id();
654 tab->proxy = p;
656 memset(&req, 0, sizeof(req));
657 strlcpy(req.host, p->host, sizeof(req.host));
658 strlcpy(req.port, p->port, sizeof(req.host));
660 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
661 strlcat(req.req, "\r\n", sizeof(req.req));
663 req.proto = p->proto;
665 ui_send_net(IMSG_GET_RAW, tab->id,
666 &req, sizeof(req));
669 /*
670 * Effectively load the given url in the given tab. Return 1 when
671 * loading the page asynchronously, and thus when an erase_buffer can
672 * be done right after this function return, or 0 when loading the
673 * page synchronously. In this last case, erase_buffer *MUST* be
674 * called by the handling function (such as load_page_from_str).
675 */
676 static int
677 do_load_url(struct tab *tab, const char *url, const char *base)
679 struct phos_uri uri;
680 struct proto *p;
681 struct proxy *proxy;
682 char *t;
684 tab->proxy = NULL;
686 if (tab->fd != -1) {
687 close(tab->fd);
688 tab->fd = -1;
689 free(tab->path);
690 tab->path = NULL;
693 tab->trust = TS_UNKNOWN;
695 if (base == NULL)
696 memcpy(&uri, &tab->uri, sizeof(tab->uri));
697 else
698 phos_parse_absolute_uri(base, &uri);
700 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
701 if (asprintf(&t, "#error loading %s\n>%s\n",
702 url, "Can't parse the URI") == -1)
703 die();
704 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
705 load_page_from_str(tab, t);
706 free(t);
707 return 0;
710 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
711 sizeof(tab->hist_cur->h));
713 for (p = protos; p->schema != NULL; ++p) {
714 if (!strcmp(tab->uri.scheme, p->schema)) {
715 p->loadfn(tab, url);
716 return 1;
720 TAILQ_FOREACH(proxy, &proxies, proxies) {
721 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
722 load_via_proxy(tab, url, proxy);
723 return 1;
727 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
728 return 0;
731 /*
732 * Load url in tab. If tab is marked as lazy, only prepare the url
733 * but don't load it. If tab is lazy and a url was already prepared,
734 * do load it!
735 */
736 void
737 load_url(struct tab *tab, const char *url, const char *base)
739 int lazy;
741 lazy = tab->flags & TAB_LAZY;
743 if (lazy && tab->hist_cur != NULL) {
744 lazy = 0;
745 tab->flags &= ~TAB_LAZY;
748 if (!lazy || tab->hist_cur == NULL) {
749 if (tab->hist_cur != NULL)
750 hist_clear_forward(&tab->hist,
751 TAILQ_NEXT(tab->hist_cur, entries));
753 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
754 event_loopbreak();
755 return;
758 strlcpy(tab->buffer.page.title, url,
759 sizeof(tab->buffer.page.title));
760 hist_push(&tab->hist, tab->hist_cur);
762 if (lazy)
763 strlcpy(tab->hist_cur->h, url,
764 sizeof(tab->hist_cur->h));
767 if (!lazy && do_load_url(tab, url, base))
768 erase_buffer(&tab->buffer);
771 int
772 load_previous_page(struct tab *tab)
774 struct hist *h;
776 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
777 return 0;
778 tab->hist_cur = h;
779 do_load_url(tab, h->h, NULL);
780 return 1;
783 int
784 load_next_page(struct tab *tab)
786 struct hist *h;
788 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
789 return 0;
790 tab->hist_cur = h;
791 do_load_url(tab, h->h, NULL);
792 return 1;
795 /*
796 * Free every resource linked to the tab, including the tab itself.
797 * Removes the tab from the tablist, but doesn't update the
798 * current_tab though.
799 */
800 void
801 free_tab(struct tab *tab)
803 stop_tab(tab);
805 if (evtimer_pending(&tab->loadingev, NULL))
806 evtimer_del(&tab->loadingev);
808 TAILQ_REMOVE(&tabshead, tab, tabs);
809 free(tab);
812 void
813 stop_tab(struct tab *tab)
815 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
817 if (tab->fd != -1) {
818 close(tab->fd);
819 tab->fd = -1;
820 free(tab->path);
821 tab->path = NULL;
822 load_page_from_str(tab, "Stopped.\n");
826 void
827 add_to_bookmarks(const char *str)
829 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
830 str, strlen(str)+1);
833 void
834 save_session(void)
836 struct tab *tab;
837 char *t;
838 int flags;
840 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
842 TAILQ_FOREACH(tab, &tabshead, tabs) {
843 flags = tab->flags;
844 if (tab == current_tab)
845 flags |= TAB_CURRENT;
847 t = tab->hist_cur->h;
848 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
850 t = tab->buffer.page.title;
851 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
854 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
857 /*
858 * Parse a line of the session file. The format is:
860 * URL [flags,...] [title]\n
861 */
862 static void
863 parse_session_line(char *line, const char **title, uint32_t *flags)
865 char *s, *t, *ap;
867 *title = "";
868 *flags = 0;
869 if ((s = strchr(line, ' ')) == NULL)
870 return;
872 *s++ = '\0';
874 if ((t = strchr(s, ' ')) != NULL) {
875 *t++ = '\0';
876 *title = t;
879 while ((ap = strsep(&s, ",")) != NULL) {
880 if (*ap == '\0')
882 else if (!strcmp(ap, "current"))
883 *flags |= TAB_CURRENT;
884 else
885 message("unknown tab flag: %s", ap);
889 static void
890 load_last_session(void)
892 const char *title;
893 char *nl, *line = NULL;
894 uint32_t flags;
895 size_t linesize = 0;
896 ssize_t linelen;
897 FILE *session;
898 struct tab *tab, *curr = NULL;
900 if ((session = fopen(session_file, "r")) == NULL) {
901 /* first time? */
902 new_tab("about:new", NULL);
903 switch_to_tab(new_tab("about:help", NULL));
904 return;
907 while ((linelen = getline(&line, &linesize, session)) != -1) {
908 if ((nl = strchr(line, '\n')) != NULL)
909 *nl = '\0';
910 parse_session_line(line, &title, &flags);
911 if ((tab = new_tab(line, NULL)) == NULL)
912 err(1, "new_tab");
913 strlcpy(tab->buffer.page.title, title,
914 sizeof(tab->buffer.page.title));
915 if (flags & TAB_CURRENT)
916 curr = tab;
919 if (ferror(session))
920 message("error reading %s: %s",
921 session_file, strerror(errno));
922 fclose(session);
923 free(line);
925 if (curr != NULL)
926 switch_to_tab(curr);
928 if (last_time_crashed())
929 switch_to_tab(new_tab("about:crash", NULL));
931 return;
934 static pid_t
935 start_child(enum telescope_process p, const char *argv0, int fd)
937 const char *argv[4];
938 int argc = 0;
939 pid_t pid;
941 switch (pid = fork()) {
942 case -1:
943 die();
944 case 0:
945 break;
946 default:
947 close(fd);
948 return pid;
951 if (dup2(fd, 3) == -1)
952 err(1, "cannot setup imsg fd");
954 argv[argc++] = argv0;
955 switch (p) {
956 case PROC_UI:
957 errx(1, "Can't start ui process");
958 case PROC_FS:
959 argv[argc++] = "-Tf";
960 break;
961 case PROC_NET:
962 argv[argc++] = "-Tn";
963 break;
966 argv[argc++] = NULL;
967 execvp(argv0, (char *const *)argv);
968 err(1, "execvp(%s)", argv0);
971 static int
972 ui_send_net(int type, uint32_t peerid, const void *data,
973 uint16_t datalen)
975 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
976 datalen);
979 static int
980 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
982 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
983 datalen);
986 static void __attribute__((noreturn))
987 usage(int r)
989 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
990 getprogname());
991 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
992 exit(r);
995 int
996 main(int argc, char * const *argv)
998 struct imsgev net_ibuf, fs_ibuf;
999 int pipe2net[2], pipe2fs[2];
1000 int ch, configtest = 0, fail = 0;
1001 int has_url = 0;
1002 int proc = -1;
1003 int sessionfd;
1004 char path[PATH_MAX];
1005 const char *url = NEW_TAB_URL;
1006 const char *argv0;
1008 argv0 = argv[0];
1010 signal(SIGCHLD, SIG_IGN);
1011 signal(SIGPIPE, SIG_IGN);
1013 if (getenv("NO_COLOR") != NULL)
1014 enable_colors = 0;
1016 strlcpy(path, getenv("HOME"), sizeof(path));
1017 strlcat(path, "/.telescope/config", sizeof(path));
1019 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1020 switch (ch) {
1021 case 'C':
1022 exit(ui_print_colors());
1023 case 'c':
1024 fail = 1;
1025 strlcpy(path, optarg, sizeof(path));
1026 break;
1027 case 'n':
1028 configtest = 1;
1029 break;
1030 case 'h':
1031 usage(0);
1032 case 'T':
1033 switch (*optarg) {
1034 case 'f':
1035 proc = PROC_FS;
1036 break;
1037 case 'n':
1038 proc = PROC_NET;
1039 break;
1040 default:
1041 errx(1, "invalid process spec %c",
1042 *optarg);
1044 break;
1045 case 'v':
1046 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1047 exit(0);
1048 break;
1049 default:
1050 usage(1);
1054 argc -= optind;
1055 argv += optind;
1057 if (proc != -1) {
1058 if (argc > 0)
1059 usage(1);
1060 else if (proc == PROC_FS)
1061 return fs_main();
1062 else if (proc == PROC_NET)
1063 return net_main();
1064 else
1065 usage(1);
1068 if (argc != 0) {
1069 has_url = 1;
1070 url = argv[0];
1073 /* setup keys before reading the config */
1074 TAILQ_INIT(&global_map.m);
1075 global_map.unhandled_input = global_key_unbound;
1076 TAILQ_INIT(&minibuffer_map.m);
1078 config_init();
1079 parseconfig(path, fail);
1080 if (configtest){
1081 puts("config OK");
1082 exit(0);
1085 fs_init();
1086 if ((sessionfd = lock_session()) == -1)
1087 errx(1, "can't lock session, is another instance of "
1088 "telescope already running?");
1090 /* Start children. */
1091 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1092 err(1, "socketpair");
1093 start_child(PROC_FS, argv0, pipe2fs[1]);
1094 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1095 iev_fs = &fs_ibuf;
1096 iev_fs->handler = handle_dispatch_imsg;
1098 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1099 err(1, "socketpair");
1100 start_child(PROC_NET, argv0, pipe2net[1]);
1101 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1102 iev_net = &net_ibuf;
1103 iev_net->handler = handle_dispatch_imsg;
1105 setproctitle("ui");
1107 /* initialize tofu & load certificates */
1108 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1109 load_certs(&certs);
1111 event_init();
1113 /* Setup event handlers for pipes to fs/net */
1114 iev_fs->events = EV_READ;
1115 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1116 iev_fs->handler, iev_fs);
1117 event_add(&iev_fs->ev, NULL);
1119 iev_net->events = EV_READ;
1120 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1121 iev_net->handler, iev_net);
1122 event_add(&iev_net->ev, NULL);
1124 if (ui_init()) {
1125 load_last_session();
1126 if (has_url || TAILQ_EMPTY(&tabshead))
1127 new_tab(url, NULL);
1129 sandbox_ui_process();
1130 ui_main_loop();
1131 ui_end();
1134 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1135 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1136 imsg_flush(&iev_fs->ibuf);
1137 imsg_flush(&iev_net->ibuf);
1139 close(sessionfd);
1141 return 0;