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 void make_request(struct tab *, struct get_req *, int,
111 const char *);
112 static int do_load_url(struct tab*, const char *, const char *);
113 static void parse_session_line(char *, const char **, uint32_t *);
114 static void load_last_session(void);
115 static pid_t start_child(enum telescope_process, const char *, int);
116 static int ui_send_net(int, uint32_t, const void *, uint16_t);
117 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
119 static struct proto {
120 const char *schema;
121 const char *port;
122 void (*loadfn)(struct tab*, const char*);
123 } protos[] = {
124 {"about", NULL, load_about_url},
125 {"finger", "79", load_finger_url},
126 {"gemini", "1965", load_gemini_url},
127 {NULL, NULL, NULL},
128 };
130 static imsg_handlerfn *handlers[] = {
131 [IMSG_ERR] = handle_imsg_err,
132 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
133 [IMSG_GOT_CODE] = handle_imsg_got_code,
134 [IMSG_GOT_META] = handle_imsg_got_meta,
135 [IMSG_BUF] = handle_imsg_buf,
136 [IMSG_EOF] = handle_imsg_eof,
137 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
138 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
139 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
140 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
141 };
143 static struct ohash certs;
145 static void __attribute__((__noreturn__))
146 die(void)
148 abort(); /* TODO */
151 static struct tab *
152 tab_by_id(uint32_t id)
154 struct tab *t;
156 TAILQ_FOREACH(t, &tabshead, tabs) {
157 if (t->id == id)
158 return t;
161 return NULL;
164 static void
165 handle_imsg_err(struct imsg *imsg, size_t datalen)
167 struct tab *tab;
168 char *page;
170 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
171 return;
173 page = imsg->data;
174 page[datalen-1] = '\0';
176 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
177 tab->hist_cur->h, page) == -1)
178 die();
179 load_page_from_str(tab, page);
180 free(page);
183 static void
184 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
186 const char *hash, *host, *port;
187 int tofu_res;
188 struct tofu_entry *e;
189 struct tab *tab;
191 hash = imsg->data;
192 if (hash[datalen-1] != '\0')
193 abort();
195 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
196 return;
198 if (tab->proxy != NULL) {
199 host = tab->proxy->host;
200 port = tab->proxy->port;
201 } else {
202 host = tab->uri.host;
203 port = tab->uri.port;
206 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
207 /* TODO: an update in libressl/libretls changed
208 * significantly. Find a better approach at storing
209 * the certs! */
210 if (datalen > sizeof(e->hash))
211 abort();
213 tofu_res = 1; /* trust on first use */
214 if ((e = calloc(1, sizeof(*e))) == NULL)
215 abort();
216 strlcpy(e->domain, host, sizeof(e->domain));
217 if (*port != '\0' && strcmp(port, "1965")) {
218 strlcat(e->domain, ":", sizeof(e->domain));
219 strlcat(e->domain, port, sizeof(e->domain));
221 strlcpy(e->hash, hash, sizeof(e->hash));
222 tofu_add(&certs, e);
223 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
224 } else
225 tofu_res = !strcmp(hash, e->hash);
227 if (tofu_res) {
228 if (e->verified == -1)
229 tab->trust = TS_TEMP_TRUSTED;
230 else if (e->verified == 1)
231 tab->trust = TS_VERIFIED;
232 else
233 tab->trust = TS_TRUSTED;
235 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
236 &tofu_res, sizeof(tofu_res));
237 } else {
238 tab->trust = TS_UNTRUSTED;
239 load_page_from_str(tab, "# Certificate mismatch\n");
240 if ((tab->cert = strdup(hash)) == NULL)
241 die();
242 ui_yornp("Certificate mismatch. Proceed?",
243 handle_check_cert_user_choice, tab);
247 static void
248 handle_check_cert_user_choice(int accept, struct tab *tab)
250 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
251 sizeof(accept));
253 if (accept) {
254 /*
255 * trust the certificate for this session only. If
256 * the page results in a redirect while we're asking
257 * the user to save, we'll end up with an invalid
258 * tabid (one request == one tab id) and crash. It
259 * also makes sense to save it for the current session
260 * if the user accepted it.
261 */
262 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
264 ui_yornp("Save the new certificate?",
265 handle_maybe_save_new_cert, tab);
266 } else {
267 free(tab->cert);
268 tab->cert = NULL;
272 static void
273 handle_maybe_save_new_cert(int accept, struct tab *tab)
275 struct tofu_entry *e;
276 const char *host, *port;
278 if (tab->proxy != NULL) {
279 host = tab->proxy->host;
280 port = tab->proxy->port;
281 } else {
282 host = tab->uri.host;
283 port = tab->uri.port;
286 if (!accept)
287 goto end;
289 if ((e = calloc(1, sizeof(*e))) == NULL)
290 die();
292 strlcpy(e->domain, host, sizeof(e->domain));
293 if (*port != '\0' && strcmp(port, "1965")) {
294 strlcat(e->domain, ":", sizeof(e->domain));
295 strlcat(e->domain, port, sizeof(e->domain));
297 strlcpy(e->hash, tab->cert, sizeof(e->hash));
298 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
300 tofu_update(&certs, e);
302 tab->trust = TS_TRUSTED;
304 end:
305 free(tab->cert);
306 tab->cert = NULL;
309 static inline int
310 normalize_code(int n)
312 if (n < 20) {
313 if (n == 10 || n == 11)
314 return n;
315 return 10;
316 } else if (n < 30) {
317 return 20;
318 } else if (n < 40) {
319 if (n == 30 || n == 31)
320 return n;
321 return 30;
322 } else if (n < 50) {
323 if (n <= 44)
324 return n;
325 return 40;
326 } else if (n < 60) {
327 if (n <= 53 || n == 59)
328 return n;
329 return 50;
330 } else if (n < 70) {
331 if (n <= 62)
332 return n;
333 return 60;
334 } else
335 return MALFORMED_RESPONSE;
338 static void
339 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
341 struct tab *tab;
343 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
344 return;
346 if (sizeof(tab->code) != datalen)
347 die();
349 memcpy(&tab->code, imsg->data, sizeof(tab->code));
350 tab->code = normalize_code(tab->code);
351 if (tab->code != 30 && tab->code != 31)
352 tab->redirect_count = 0;
355 static void
356 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
358 struct tab *tab;
360 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
361 return;
363 if (sizeof(tab->meta) <= datalen)
364 die();
366 memcpy(tab->meta, imsg->data, datalen);
368 if (tab->code < 10) { /* internal errors */
369 load_page_from_str(tab, err_pages[tab->code]);
370 } else if (tab->code < 20) { /* 1x */
371 load_page_from_str(tab, err_pages[tab->code]);
372 ui_require_input(tab, tab->code == 11);
373 } else if (tab->code == 20) {
374 if (setup_parser_for(tab)) {
375 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
376 } else {
377 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
378 ui_yornp("Can't display page, wanna save?",
379 handle_maybe_save_page, tab);
381 } else if (tab->code < 40) { /* 3x */
382 tab->redirect_count++;
384 /* TODO: make customizable? */
385 if (tab->redirect_count > 5) {
386 load_page_from_str(tab,
387 err_pages[TOO_MUCH_REDIRECTS]);
388 } else
389 do_load_url(tab, tab->meta, NULL);
390 } else { /* 4x, 5x & 6x */
391 load_page_from_str(tab, err_pages[tab->code]);
395 static void
396 handle_maybe_save_page(int dosave, struct tab *tab)
398 if (dosave)
399 ui_read("Save to path", handle_save_page_path, tab);
400 else
401 stop_tab(tab);
404 static void
405 handle_save_page_path(const char *path, struct tab *tab)
407 if (path == NULL) {
408 stop_tab(tab);
409 return;
412 tab->path = strdup(path);
414 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
417 static void
418 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
420 struct tab *tab;
421 char *page;
422 const char *e;
423 int l;
425 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
426 if (imsg->fd != -1)
427 close(imsg->fd);
428 return;
431 if (imsg->fd == -1) {
432 stop_tab(tab);
434 e = imsg->data;
435 if (e[datalen-1] != '\0')
436 die();
437 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
438 tab->path, e);
439 if (l == -1)
440 die();
441 load_page_from_str(tab, page);
442 free(page);
443 } else {
444 tab->fd = imsg->fd;
445 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
449 static void
450 handle_imsg_buf(struct imsg *imsg, size_t datalen)
452 struct tab *tab;
453 int l;
454 char *page, buf[FMT_SCALED_STRSIZE] = {0};
456 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
457 return;
459 tab->bytes += datalen;
460 if (tab->fd == -1) {
461 if (!tab->buffer.page.parse(&tab->buffer.page,
462 imsg->data, datalen))
463 die();
464 } else {
465 write(tab->fd, imsg->data, datalen);
466 fmt_scaled(tab->bytes, buf);
467 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
468 tab->path,
469 buf);
470 if (l == -1)
471 die();
472 load_page_from_str(tab, page);
473 free(page);
476 ui_on_tab_refresh(tab);
479 static void
480 handle_imsg_eof(struct imsg *imsg, size_t datalen)
482 struct tab *tab;
483 int l;
484 char *page, buf[FMT_SCALED_STRSIZE] = {0};
486 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
487 return;
489 if (tab->fd == -1) {
490 if (!tab->buffer.page.free(&tab->buffer.page))
491 die();
492 } else {
493 fmt_scaled(tab->bytes, buf);
494 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
495 tab->path,
496 buf);
497 if (l == -1)
498 die();
499 load_page_from_str(tab, page);
500 free(page);
502 close(tab->fd);
503 tab->fd = -1;
504 free(tab->path);
505 tab->path = NULL;
508 ui_on_tab_refresh(tab);
509 ui_on_tab_loaded(tab);
512 static void
513 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
515 int res;
517 if (datalen != sizeof(res))
518 die();
520 memcpy(&res, imsg->data, sizeof(res));
521 if (res == 0)
522 message("Added to bookmarks!");
523 else
524 message("Failed to add to bookmarks: %s",
525 strerror(res));
528 static void
529 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
531 int res;
533 if (datalen != sizeof(res))
534 die();
535 memcpy(&res, imsg->data, datalen);
536 if (res != 0)
537 message("Failed to save the cert for: %s",
538 strerror(res));
541 static void
542 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
544 int res;
546 if (datalen != sizeof(res))
547 die();
548 memcpy(&res, imsg->data, datalen);
549 if (!res)
550 message("Failed to update the certificate");
553 static void
554 handle_dispatch_imsg(int fd, short ev, void *d)
556 struct imsgev *iev = d;
558 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
559 err(1, "connection closed");
562 static void
563 load_page_from_str(struct tab *tab, const char *page)
565 erase_buffer(&tab->buffer);
566 gemtext_initparser(&tab->buffer.page);
567 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
568 die();
569 if (!tab->buffer.page.free(&tab->buffer.page))
570 die();
571 ui_on_tab_refresh(tab);
572 ui_on_tab_loaded(tab);
575 static void
576 load_about_url(struct tab *tab, const char *url)
578 tab->trust = TS_VERIFIED;
580 gemtext_initparser(&tab->buffer.page);
582 ui_send_fs(IMSG_GET, tab->id,
583 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
586 static void
587 load_finger_url(struct tab *tab, const char *url)
589 struct get_req req;
590 size_t len;
591 char *at;
593 memset(&req, 0, sizeof(req));
594 strlcpy(req.port, tab->uri.port, 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));
616 strlcat(req.req, "\r\n", sizeof(req.req));
618 textplain_initparser(&tab->buffer.page);
619 make_request(tab, &req, PROTO_FINGER, NULL);
622 static void
623 load_gemini_url(struct tab *tab, const char *url)
625 struct get_req req;
627 memset(&req, 0, sizeof(req));
628 strlcpy(req.host, tab->uri.host, sizeof(req.host));
629 strlcpy(req.port, tab->uri.port, sizeof(req.host));
631 make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
634 static void
635 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
637 struct get_req req;
639 memset(&req, 0, sizeof(req));
640 strlcpy(req.host, p->host, sizeof(req.host));
641 strlcpy(req.port, p->port, sizeof(req.host));
643 tab->proxy = p;
645 make_request(tab, &req, p->proto, tab->hist_cur->h);
648 static void
649 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
651 stop_tab(tab);
652 tab->id = tab_new_id();
653 req->proto = proto;
655 if (r != NULL) {
656 strlcpy(req->req, r, sizeof(req->req));
657 strlcat(req->req, "\r\n", sizeof(req->req));
660 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
663 /*
664 * Effectively load the given url in the given tab. Return 1 when
665 * loading the page asynchronously, and thus when an erase_buffer can
666 * be done right after this function return, or 0 when loading the
667 * page synchronously. In this last case, erase_buffer *MUST* be
668 * called by the handling function (such as load_page_from_str).
669 */
670 static int
671 do_load_url(struct tab *tab, const char *url, const char *base)
673 struct phos_uri uri;
674 struct proto *p;
675 struct proxy *proxy;
676 char *t;
678 tab->proxy = NULL;
680 if (tab->fd != -1) {
681 close(tab->fd);
682 tab->fd = -1;
683 free(tab->path);
684 tab->path = NULL;
687 tab->trust = TS_UNKNOWN;
689 if (base == NULL)
690 memcpy(&uri, &tab->uri, sizeof(tab->uri));
691 else
692 phos_parse_absolute_uri(base, &uri);
694 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
695 if (asprintf(&t, "#error loading %s\n>%s\n",
696 url, "Can't parse the URI") == -1)
697 die();
698 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
699 load_page_from_str(tab, t);
700 free(t);
701 return 0;
704 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
705 sizeof(tab->hist_cur->h));
707 for (p = protos; p->schema != NULL; ++p) {
708 if (!strcmp(tab->uri.scheme, p->schema)) {
709 /* patch the port */
710 if (*tab->uri.port == '\0' && p->port != NULL)
711 strlcpy(tab->uri.port, p->port,
712 sizeof(tab->uri.port));
714 p->loadfn(tab, url);
715 return 1;
719 TAILQ_FOREACH(proxy, &proxies, proxies) {
720 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
721 load_via_proxy(tab, url, proxy);
722 return 1;
726 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
727 return 0;
730 /*
731 * Load url in tab. If tab is marked as lazy, only prepare the url
732 * but don't load it. If tab is lazy and a url was already prepared,
733 * do load it!
734 */
735 void
736 load_url(struct tab *tab, const char *url, const char *base)
738 int lazy;
740 lazy = tab->flags & TAB_LAZY;
742 if (lazy && tab->hist_cur != NULL) {
743 lazy = 0;
744 tab->flags &= ~TAB_LAZY;
747 if (!lazy || tab->hist_cur == NULL) {
748 if (tab->hist_cur != NULL)
749 hist_clear_forward(&tab->hist,
750 TAILQ_NEXT(tab->hist_cur, entries));
752 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
753 event_loopbreak();
754 return;
757 strlcpy(tab->buffer.page.title, url,
758 sizeof(tab->buffer.page.title));
759 hist_push(&tab->hist, tab->hist_cur);
761 if (lazy)
762 strlcpy(tab->hist_cur->h, url,
763 sizeof(tab->hist_cur->h));
766 if (!lazy && do_load_url(tab, url, base))
767 erase_buffer(&tab->buffer);
770 int
771 load_previous_page(struct tab *tab)
773 struct hist *h;
775 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
776 return 0;
777 tab->hist_cur = h;
778 do_load_url(tab, h->h, NULL);
779 return 1;
782 int
783 load_next_page(struct tab *tab)
785 struct hist *h;
787 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
788 return 0;
789 tab->hist_cur = h;
790 do_load_url(tab, h->h, NULL);
791 return 1;
794 /*
795 * Free every resource linked to the tab, including the tab itself.
796 * Removes the tab from the tablist, but doesn't update the
797 * current_tab though.
798 */
799 void
800 free_tab(struct tab *tab)
802 stop_tab(tab);
804 if (evtimer_pending(&tab->loadingev, NULL))
805 evtimer_del(&tab->loadingev);
807 TAILQ_REMOVE(&tabshead, tab, tabs);
808 free(tab);
811 void
812 stop_tab(struct tab *tab)
814 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
816 if (tab->fd != -1) {
817 close(tab->fd);
818 tab->fd = -1;
819 free(tab->path);
820 tab->path = NULL;
821 load_page_from_str(tab, "Stopped.\n");
825 void
826 add_to_bookmarks(const char *str)
828 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
829 str, strlen(str)+1);
832 void
833 save_session(void)
835 struct tab *tab;
836 char *t;
837 int flags;
839 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
841 TAILQ_FOREACH(tab, &tabshead, tabs) {
842 flags = tab->flags;
843 if (tab == current_tab)
844 flags |= TAB_CURRENT;
846 t = tab->hist_cur->h;
847 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
849 t = tab->buffer.page.title;
850 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
853 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
856 /*
857 * Parse a line of the session file. The format is:
859 * URL [flags,...] [title]\n
860 */
861 static void
862 parse_session_line(char *line, const char **title, uint32_t *flags)
864 char *s, *t, *ap;
866 *title = "";
867 *flags = 0;
868 if ((s = strchr(line, ' ')) == NULL)
869 return;
871 *s++ = '\0';
873 if ((t = strchr(s, ' ')) != NULL) {
874 *t++ = '\0';
875 *title = t;
878 while ((ap = strsep(&s, ",")) != NULL) {
879 if (*ap == '\0')
881 else if (!strcmp(ap, "current"))
882 *flags |= TAB_CURRENT;
883 else
884 message("unknown tab flag: %s", ap);
888 static void
889 load_last_session(void)
891 const char *title;
892 char *nl, *line = NULL;
893 uint32_t flags;
894 size_t linesize = 0;
895 ssize_t linelen;
896 FILE *session;
897 struct tab *tab, *curr = NULL;
899 if ((session = fopen(session_file, "r")) == NULL) {
900 /* first time? */
901 new_tab("about:new", NULL);
902 switch_to_tab(new_tab("about:help", NULL));
903 return;
906 while ((linelen = getline(&line, &linesize, session)) != -1) {
907 if ((nl = strchr(line, '\n')) != NULL)
908 *nl = '\0';
909 parse_session_line(line, &title, &flags);
910 if ((tab = new_tab(line, NULL)) == NULL)
911 err(1, "new_tab");
912 strlcpy(tab->buffer.page.title, title,
913 sizeof(tab->buffer.page.title));
914 if (flags & TAB_CURRENT)
915 curr = tab;
918 if (ferror(session))
919 message("error reading %s: %s",
920 session_file, strerror(errno));
921 fclose(session);
922 free(line);
924 if (curr != NULL)
925 switch_to_tab(curr);
927 if (last_time_crashed())
928 switch_to_tab(new_tab("about:crash", NULL));
930 return;
933 static pid_t
934 start_child(enum telescope_process p, const char *argv0, int fd)
936 const char *argv[4];
937 int argc = 0;
938 pid_t pid;
940 switch (pid = fork()) {
941 case -1:
942 die();
943 case 0:
944 break;
945 default:
946 close(fd);
947 return pid;
950 if (dup2(fd, 3) == -1)
951 err(1, "cannot setup imsg fd");
953 argv[argc++] = argv0;
954 switch (p) {
955 case PROC_UI:
956 errx(1, "Can't start ui process");
957 case PROC_FS:
958 argv[argc++] = "-Tf";
959 break;
960 case PROC_NET:
961 argv[argc++] = "-Tn";
962 break;
965 argv[argc++] = NULL;
966 execvp(argv0, (char *const *)argv);
967 err(1, "execvp(%s)", argv0);
970 static int
971 ui_send_net(int type, uint32_t peerid, const void *data,
972 uint16_t datalen)
974 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
975 datalen);
978 static int
979 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
981 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
982 datalen);
985 static void __attribute__((noreturn))
986 usage(int r)
988 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
989 getprogname());
990 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
991 exit(r);
994 int
995 main(int argc, char * const *argv)
997 struct imsgev net_ibuf, fs_ibuf;
998 int pipe2net[2], pipe2fs[2];
999 int ch, configtest = 0, fail = 0;
1000 int has_url = 0;
1001 int proc = -1;
1002 int sessionfd;
1003 char path[PATH_MAX];
1004 const char *url = NEW_TAB_URL;
1005 const char *argv0;
1007 argv0 = argv[0];
1009 signal(SIGCHLD, SIG_IGN);
1010 signal(SIGPIPE, SIG_IGN);
1012 if (getenv("NO_COLOR") != NULL)
1013 enable_colors = 0;
1015 strlcpy(path, getenv("HOME"), sizeof(path));
1016 strlcat(path, "/.telescope/config", sizeof(path));
1018 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1019 switch (ch) {
1020 case 'C':
1021 exit(ui_print_colors());
1022 case 'c':
1023 fail = 1;
1024 strlcpy(path, optarg, sizeof(path));
1025 break;
1026 case 'n':
1027 configtest = 1;
1028 break;
1029 case 'h':
1030 usage(0);
1031 case 'T':
1032 switch (*optarg) {
1033 case 'f':
1034 proc = PROC_FS;
1035 break;
1036 case 'n':
1037 proc = PROC_NET;
1038 break;
1039 default:
1040 errx(1, "invalid process spec %c",
1041 *optarg);
1043 break;
1044 case 'v':
1045 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1046 exit(0);
1047 break;
1048 default:
1049 usage(1);
1053 argc -= optind;
1054 argv += optind;
1056 if (proc != -1) {
1057 if (argc > 0)
1058 usage(1);
1059 else if (proc == PROC_FS)
1060 return fs_main();
1061 else if (proc == PROC_NET)
1062 return net_main();
1063 else
1064 usage(1);
1067 if (argc != 0) {
1068 has_url = 1;
1069 url = argv[0];
1072 /* setup keys before reading the config */
1073 TAILQ_INIT(&global_map.m);
1074 global_map.unhandled_input = global_key_unbound;
1075 TAILQ_INIT(&minibuffer_map.m);
1077 config_init();
1078 parseconfig(path, fail);
1079 if (configtest){
1080 puts("config OK");
1081 exit(0);
1084 fs_init();
1085 if ((sessionfd = lock_session()) == -1)
1086 errx(1, "can't lock session, is another instance of "
1087 "telescope already running?");
1089 /* Start children. */
1090 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1091 err(1, "socketpair");
1092 start_child(PROC_FS, argv0, pipe2fs[1]);
1093 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1094 iev_fs = &fs_ibuf;
1095 iev_fs->handler = handle_dispatch_imsg;
1097 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1098 err(1, "socketpair");
1099 start_child(PROC_NET, argv0, pipe2net[1]);
1100 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1101 iev_net = &net_ibuf;
1102 iev_net->handler = handle_dispatch_imsg;
1104 setproctitle("ui");
1106 /* initialize tofu & load certificates */
1107 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1108 load_certs(&certs);
1110 event_init();
1112 /* Setup event handlers for pipes to fs/net */
1113 iev_fs->events = EV_READ;
1114 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1115 iev_fs->handler, iev_fs);
1116 event_add(&iev_fs->ev, NULL);
1118 iev_net->events = EV_READ;
1119 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1120 iev_net->handler, iev_net);
1121 event_add(&iev_net->ev, NULL);
1123 if (ui_init()) {
1124 load_last_session();
1125 if (has_url || TAILQ_EMPTY(&tabshead))
1126 new_tab(url, NULL);
1128 sandbox_ui_process();
1129 ui_main_loop();
1130 ui_end();
1133 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1134 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1135 imsg_flush(&iev_fs->ibuf);
1136 imsg_flush(&iev_net->ibuf);
1138 close(sessionfd);
1140 return 0;