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_gopher_url(struct tab *, const char *);
109 static void load_via_proxy(struct tab *, const char *,
110 struct proxy *);
111 static void make_request(struct tab *, struct get_req *, int,
112 const char *);
113 static int do_load_url(struct tab*, const char *, const char *);
114 static void parse_session_line(char *, const char **, uint32_t *);
115 static void load_last_session(void);
116 static pid_t start_child(enum telescope_process, const char *, int);
117 static int ui_send_net(int, uint32_t, const void *, uint16_t);
118 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
120 static struct proto {
121 const char *schema;
122 const char *port;
123 void (*loadfn)(struct tab*, const char*);
124 } protos[] = {
125 {"about", NULL, load_about_url},
126 {"finger", "79", load_finger_url},
127 {"gemini", "1965", load_gemini_url},
128 {"gopher", "70", load_gopher_url},
129 {NULL, NULL, NULL},
130 };
132 static imsg_handlerfn *handlers[] = {
133 [IMSG_ERR] = handle_imsg_err,
134 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
135 [IMSG_GOT_CODE] = handle_imsg_got_code,
136 [IMSG_GOT_META] = handle_imsg_got_meta,
137 [IMSG_BUF] = handle_imsg_buf,
138 [IMSG_EOF] = handle_imsg_eof,
139 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
140 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
141 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
142 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
143 };
145 static struct ohash certs;
147 static void __attribute__((__noreturn__))
148 die(void)
150 abort(); /* TODO */
153 static struct tab *
154 tab_by_id(uint32_t id)
156 struct tab *t;
158 TAILQ_FOREACH(t, &tabshead, tabs) {
159 if (t->id == id)
160 return t;
163 return NULL;
166 static void
167 handle_imsg_err(struct imsg *imsg, size_t datalen)
169 struct tab *tab;
170 char *page;
172 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
173 return;
175 page = imsg->data;
176 page[datalen-1] = '\0';
178 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
179 tab->hist_cur->h, page) == -1)
180 die();
181 load_page_from_str(tab, page);
182 free(page);
185 static void
186 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
188 const char *hash, *host, *port;
189 int tofu_res;
190 struct tofu_entry *e;
191 struct tab *tab;
193 hash = imsg->data;
194 if (hash[datalen-1] != '\0')
195 abort();
197 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
198 return;
200 if (tab->proxy != NULL) {
201 host = tab->proxy->host;
202 port = tab->proxy->port;
203 } else {
204 host = tab->uri.host;
205 port = tab->uri.port;
208 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
209 /* TODO: an update in libressl/libretls changed
210 * significantly. Find a better approach at storing
211 * the certs! */
212 if (datalen > sizeof(e->hash))
213 abort();
215 tofu_res = 1; /* trust on first use */
216 if ((e = calloc(1, sizeof(*e))) == NULL)
217 abort();
218 strlcpy(e->domain, host, sizeof(e->domain));
219 if (*port != '\0' && strcmp(port, "1965")) {
220 strlcat(e->domain, ":", sizeof(e->domain));
221 strlcat(e->domain, port, sizeof(e->domain));
223 strlcpy(e->hash, hash, sizeof(e->hash));
224 tofu_add(&certs, e);
225 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
226 } else
227 tofu_res = !strcmp(hash, e->hash);
229 if (tofu_res) {
230 if (e->verified == -1)
231 tab->trust = TS_TEMP_TRUSTED;
232 else if (e->verified == 1)
233 tab->trust = TS_VERIFIED;
234 else
235 tab->trust = TS_TRUSTED;
237 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
238 &tofu_res, sizeof(tofu_res));
239 } else {
240 tab->trust = TS_UNTRUSTED;
241 load_page_from_str(tab, "# Certificate mismatch\n");
242 if ((tab->cert = strdup(hash)) == NULL)
243 die();
244 ui_yornp("Certificate mismatch. Proceed?",
245 handle_check_cert_user_choice, tab);
249 static void
250 handle_check_cert_user_choice(int accept, struct tab *tab)
252 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
253 sizeof(accept));
255 if (accept) {
256 /*
257 * trust the certificate for this session only. If
258 * the page results in a redirect while we're asking
259 * the user to save, we'll end up with an invalid
260 * tabid (one request == one tab id) and crash. It
261 * also makes sense to save it for the current session
262 * if the user accepted it.
263 */
264 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
266 ui_yornp("Save the new certificate?",
267 handle_maybe_save_new_cert, tab);
268 } else {
269 free(tab->cert);
270 tab->cert = NULL;
274 static void
275 handle_maybe_save_new_cert(int accept, struct tab *tab)
277 struct tofu_entry *e;
278 const char *host, *port;
280 if (tab->proxy != NULL) {
281 host = tab->proxy->host;
282 port = tab->proxy->port;
283 } else {
284 host = tab->uri.host;
285 port = tab->uri.port;
288 if (!accept)
289 goto end;
291 if ((e = calloc(1, sizeof(*e))) == NULL)
292 die();
294 strlcpy(e->domain, host, sizeof(e->domain));
295 if (*port != '\0' && strcmp(port, "1965")) {
296 strlcat(e->domain, ":", sizeof(e->domain));
297 strlcat(e->domain, port, sizeof(e->domain));
299 strlcpy(e->hash, tab->cert, sizeof(e->hash));
300 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
302 tofu_update(&certs, e);
304 tab->trust = TS_TRUSTED;
306 end:
307 free(tab->cert);
308 tab->cert = NULL;
311 static inline int
312 normalize_code(int n)
314 if (n < 20) {
315 if (n == 10 || n == 11)
316 return n;
317 return 10;
318 } else if (n < 30) {
319 return 20;
320 } else if (n < 40) {
321 if (n == 30 || n == 31)
322 return n;
323 return 30;
324 } else if (n < 50) {
325 if (n <= 44)
326 return n;
327 return 40;
328 } else if (n < 60) {
329 if (n <= 53 || n == 59)
330 return n;
331 return 50;
332 } else if (n < 70) {
333 if (n <= 62)
334 return n;
335 return 60;
336 } else
337 return MALFORMED_RESPONSE;
340 static void
341 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
343 struct tab *tab;
345 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
346 return;
348 if (sizeof(tab->code) != datalen)
349 die();
351 memcpy(&tab->code, imsg->data, sizeof(tab->code));
352 tab->code = normalize_code(tab->code);
353 if (tab->code != 30 && tab->code != 31)
354 tab->redirect_count = 0;
357 static void
358 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
360 struct tab *tab;
362 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
363 return;
365 if (sizeof(tab->meta) <= datalen)
366 die();
368 memcpy(tab->meta, imsg->data, datalen);
370 if (tab->code < 10) { /* internal errors */
371 load_page_from_str(tab, err_pages[tab->code]);
372 } else if (tab->code < 20) { /* 1x */
373 load_page_from_str(tab, err_pages[tab->code]);
374 ui_require_input(tab, tab->code == 11);
375 } else if (tab->code == 20) {
376 if (setup_parser_for(tab)) {
377 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
378 } else {
379 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
380 ui_yornp("Can't display page, wanna save?",
381 handle_maybe_save_page, tab);
383 } else if (tab->code < 40) { /* 3x */
384 tab->redirect_count++;
386 /* TODO: make customizable? */
387 if (tab->redirect_count > 5) {
388 load_page_from_str(tab,
389 err_pages[TOO_MUCH_REDIRECTS]);
390 } else
391 do_load_url(tab, tab->meta, NULL);
392 } else { /* 4x, 5x & 6x */
393 load_page_from_str(tab, err_pages[tab->code]);
397 static void
398 handle_maybe_save_page(int dosave, struct tab *tab)
400 if (dosave)
401 ui_read("Save to path", handle_save_page_path, tab);
402 else
403 stop_tab(tab);
406 static void
407 handle_save_page_path(const char *path, struct tab *tab)
409 if (path == NULL) {
410 stop_tab(tab);
411 return;
414 tab->path = strdup(path);
416 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
419 static void
420 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
422 struct tab *tab;
423 char *page;
424 const char *e;
425 int l;
427 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
428 if (imsg->fd != -1)
429 close(imsg->fd);
430 return;
433 if (imsg->fd == -1) {
434 stop_tab(tab);
436 e = imsg->data;
437 if (e[datalen-1] != '\0')
438 die();
439 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
440 tab->path, e);
441 if (l == -1)
442 die();
443 load_page_from_str(tab, page);
444 free(page);
445 } else {
446 tab->fd = imsg->fd;
447 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
451 static void
452 handle_imsg_buf(struct imsg *imsg, size_t datalen)
454 struct tab *tab;
455 int l;
456 char *page, buf[FMT_SCALED_STRSIZE] = {0};
458 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
459 return;
461 tab->bytes += datalen;
462 if (tab->fd == -1) {
463 if (!tab->buffer.page.parse(&tab->buffer.page,
464 imsg->data, datalen))
465 die();
466 } else {
467 write(tab->fd, imsg->data, datalen);
468 fmt_scaled(tab->bytes, buf);
469 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
470 tab->path,
471 buf);
472 if (l == -1)
473 die();
474 load_page_from_str(tab, page);
475 free(page);
478 ui_on_tab_refresh(tab);
481 static void
482 handle_imsg_eof(struct imsg *imsg, size_t datalen)
484 struct tab *tab;
485 int l;
486 char *page, buf[FMT_SCALED_STRSIZE] = {0};
488 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
489 return;
491 if (tab->fd == -1) {
492 if (!tab->buffer.page.free(&tab->buffer.page))
493 die();
494 } else {
495 fmt_scaled(tab->bytes, buf);
496 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
497 tab->path,
498 buf);
499 if (l == -1)
500 die();
501 load_page_from_str(tab, page);
502 free(page);
504 close(tab->fd);
505 tab->fd = -1;
506 free(tab->path);
507 tab->path = NULL;
510 ui_on_tab_refresh(tab);
511 ui_on_tab_loaded(tab);
514 static void
515 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
517 int res;
519 if (datalen != sizeof(res))
520 die();
522 memcpy(&res, imsg->data, sizeof(res));
523 if (res == 0)
524 message("Added to bookmarks!");
525 else
526 message("Failed to add to bookmarks: %s",
527 strerror(res));
530 static void
531 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
533 int res;
535 if (datalen != sizeof(res))
536 die();
537 memcpy(&res, imsg->data, datalen);
538 if (res != 0)
539 message("Failed to save the cert for: %s",
540 strerror(res));
543 static void
544 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
546 int res;
548 if (datalen != sizeof(res))
549 die();
550 memcpy(&res, imsg->data, datalen);
551 if (!res)
552 message("Failed to update the certificate");
555 static void
556 handle_dispatch_imsg(int fd, short ev, void *d)
558 struct imsgev *iev = d;
560 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
561 err(1, "connection closed");
564 static void
565 load_page_from_str(struct tab *tab, const char *page)
567 erase_buffer(&tab->buffer);
568 gemtext_initparser(&tab->buffer.page);
569 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
570 die();
571 if (!tab->buffer.page.free(&tab->buffer.page))
572 die();
573 ui_on_tab_refresh(tab);
574 ui_on_tab_loaded(tab);
577 static void
578 load_about_url(struct tab *tab, const char *url)
580 tab->trust = TS_VERIFIED;
582 gemtext_initparser(&tab->buffer.page);
584 ui_send_fs(IMSG_GET, tab->id,
585 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
588 static void
589 load_finger_url(struct tab *tab, const char *url)
591 struct get_req req;
592 size_t len;
593 char *at;
595 memset(&req, 0, sizeof(req));
596 strlcpy(req.port, tab->uri.port, sizeof(req.port));
598 /*
599 * Sometimes the finger url have the user as path component
600 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
601 * userinfo (e.g. finger://cobradile@finger.farm).
602 */
603 if ((at = strchr(tab->uri.host, '@')) != NULL) {
604 len = at - tab->uri.host;
605 memcpy(req.req, tab->uri.host, len);
607 if (len >= sizeof(req.req))
608 die();
609 req.req[len] = '\0';
611 strlcpy(req.host, at+1, sizeof(req.host));
612 } else {
613 strlcpy(req.host, tab->uri.host, sizeof(req.host));
615 /* +1 to skip the initial `/' */
616 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
618 strlcat(req.req, "\r\n", sizeof(req.req));
620 textplain_initparser(&tab->buffer.page);
621 make_request(tab, &req, PROTO_FINGER, NULL);
624 static void
625 load_gemini_url(struct tab *tab, const char *url)
627 struct get_req req;
629 memset(&req, 0, sizeof(req));
630 strlcpy(req.host, tab->uri.host, sizeof(req.host));
631 strlcpy(req.port, tab->uri.port, sizeof(req.host));
633 make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
636 static void
637 load_gopher_url(struct tab *tab, const char *url)
639 struct get_req req;
640 const char *path;
642 memset(&req, 0, sizeof(req));
643 strlcpy(req.host, tab->uri.host, sizeof(req.host));
644 strlcpy(req.port, tab->uri.port, sizeof(req.host));
646 path = tab->uri.path;
647 if (!strcmp(path, "/") || *path == '\0') {
648 /* expect the top directory to be a gophermap */
649 gophermap_initparser(&tab->buffer.page);
650 } else if (has_prefix(path, "/1/")) {
651 /* gophermap menu/submenu */
652 gophermap_initparser(&tab->buffer.page);
653 path += 3;
654 } else if (has_prefix(path, "/0/")) {
655 textplain_initparser(&tab->buffer.page);
656 path += 3;
657 } else {
658 return;
661 make_request(tab, &req, PROTO_GOPHER, path);
664 static void
665 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
667 struct get_req req;
669 memset(&req, 0, sizeof(req));
670 strlcpy(req.host, p->host, sizeof(req.host));
671 strlcpy(req.port, p->port, sizeof(req.host));
673 tab->proxy = p;
675 make_request(tab, &req, p->proto, tab->hist_cur->h);
678 static void
679 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
681 stop_tab(tab);
682 tab->id = tab_new_id();
683 req->proto = proto;
685 if (r != NULL) {
686 strlcpy(req->req, r, sizeof(req->req));
687 strlcat(req->req, "\r\n", sizeof(req->req));
690 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
693 /*
694 * Effectively load the given url in the given tab. Return 1 when
695 * loading the page asynchronously, and thus when an erase_buffer can
696 * be done right after this function return, or 0 when loading the
697 * page synchronously. In this last case, erase_buffer *MUST* be
698 * called by the handling function (such as load_page_from_str).
699 */
700 static int
701 do_load_url(struct tab *tab, const char *url, const char *base)
703 struct phos_uri uri;
704 struct proto *p;
705 struct proxy *proxy;
706 char *t;
708 tab->proxy = NULL;
710 if (tab->fd != -1) {
711 close(tab->fd);
712 tab->fd = -1;
713 free(tab->path);
714 tab->path = NULL;
717 tab->trust = TS_UNKNOWN;
719 if (base == NULL)
720 memcpy(&uri, &tab->uri, sizeof(tab->uri));
721 else
722 phos_parse_absolute_uri(base, &uri);
724 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
725 if (asprintf(&t, "#error loading %s\n>%s\n",
726 url, "Can't parse the URI") == -1)
727 die();
728 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
729 load_page_from_str(tab, t);
730 free(t);
731 return 0;
734 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
735 sizeof(tab->hist_cur->h));
737 for (p = protos; p->schema != NULL; ++p) {
738 if (!strcmp(tab->uri.scheme, p->schema)) {
739 /* patch the port */
740 if (*tab->uri.port == '\0' && p->port != NULL)
741 strlcpy(tab->uri.port, p->port,
742 sizeof(tab->uri.port));
744 p->loadfn(tab, url);
745 return 1;
749 TAILQ_FOREACH(proxy, &proxies, proxies) {
750 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
751 load_via_proxy(tab, url, proxy);
752 return 1;
756 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
757 return 0;
760 /*
761 * Load url in tab. If tab is marked as lazy, only prepare the url
762 * but don't load it. If tab is lazy and a url was already prepared,
763 * do load it!
764 */
765 void
766 load_url(struct tab *tab, const char *url, const char *base)
768 int lazy;
770 lazy = tab->flags & TAB_LAZY;
772 if (lazy && tab->hist_cur != NULL) {
773 lazy = 0;
774 tab->flags &= ~TAB_LAZY;
777 if (!lazy || tab->hist_cur == NULL) {
778 if (tab->hist_cur != NULL)
779 hist_clear_forward(&tab->hist,
780 TAILQ_NEXT(tab->hist_cur, entries));
782 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
783 event_loopbreak();
784 return;
787 strlcpy(tab->buffer.page.title, url,
788 sizeof(tab->buffer.page.title));
789 hist_push(&tab->hist, tab->hist_cur);
791 if (lazy)
792 strlcpy(tab->hist_cur->h, url,
793 sizeof(tab->hist_cur->h));
796 if (!lazy && do_load_url(tab, url, base))
797 erase_buffer(&tab->buffer);
800 int
801 load_previous_page(struct tab *tab)
803 struct hist *h;
805 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
806 return 0;
807 tab->hist_cur = h;
808 do_load_url(tab, h->h, NULL);
809 return 1;
812 int
813 load_next_page(struct tab *tab)
815 struct hist *h;
817 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
818 return 0;
819 tab->hist_cur = h;
820 do_load_url(tab, h->h, NULL);
821 return 1;
824 /*
825 * Free every resource linked to the tab, including the tab itself.
826 * Removes the tab from the tablist, but doesn't update the
827 * current_tab though.
828 */
829 void
830 free_tab(struct tab *tab)
832 stop_tab(tab);
834 if (evtimer_pending(&tab->loadingev, NULL))
835 evtimer_del(&tab->loadingev);
837 TAILQ_REMOVE(&tabshead, tab, tabs);
838 free(tab);
841 void
842 stop_tab(struct tab *tab)
844 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
846 if (tab->fd != -1) {
847 close(tab->fd);
848 tab->fd = -1;
849 free(tab->path);
850 tab->path = NULL;
851 load_page_from_str(tab, "Stopped.\n");
855 void
856 add_to_bookmarks(const char *str)
858 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
859 str, strlen(str)+1);
862 void
863 save_session(void)
865 struct tab *tab;
866 char *t;
867 int flags;
869 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
871 TAILQ_FOREACH(tab, &tabshead, tabs) {
872 flags = tab->flags;
873 if (tab == current_tab)
874 flags |= TAB_CURRENT;
876 t = tab->hist_cur->h;
877 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
879 t = tab->buffer.page.title;
880 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
883 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
886 /*
887 * Parse a line of the session file. The format is:
889 * URL [flags,...] [title]\n
890 */
891 static void
892 parse_session_line(char *line, const char **title, uint32_t *flags)
894 char *s, *t, *ap;
896 *title = "";
897 *flags = 0;
898 if ((s = strchr(line, ' ')) == NULL)
899 return;
901 *s++ = '\0';
903 if ((t = strchr(s, ' ')) != NULL) {
904 *t++ = '\0';
905 *title = t;
908 while ((ap = strsep(&s, ",")) != NULL) {
909 if (*ap == '\0')
911 else if (!strcmp(ap, "current"))
912 *flags |= TAB_CURRENT;
913 else
914 message("unknown tab flag: %s", ap);
918 static void
919 load_last_session(void)
921 const char *title;
922 char *nl, *line = NULL;
923 uint32_t flags;
924 size_t linesize = 0;
925 ssize_t linelen;
926 FILE *session;
927 struct tab *tab, *curr = NULL;
929 if ((session = fopen(session_file, "r")) == NULL) {
930 /* first time? */
931 new_tab("about:new", NULL);
932 switch_to_tab(new_tab("about:help", NULL));
933 return;
936 while ((linelen = getline(&line, &linesize, session)) != -1) {
937 if ((nl = strchr(line, '\n')) != NULL)
938 *nl = '\0';
939 parse_session_line(line, &title, &flags);
940 if ((tab = new_tab(line, NULL)) == NULL)
941 err(1, "new_tab");
942 strlcpy(tab->buffer.page.title, title,
943 sizeof(tab->buffer.page.title));
944 if (flags & TAB_CURRENT)
945 curr = tab;
948 if (ferror(session))
949 message("error reading %s: %s",
950 session_file, strerror(errno));
951 fclose(session);
952 free(line);
954 if (curr != NULL)
955 switch_to_tab(curr);
957 if (last_time_crashed())
958 switch_to_tab(new_tab("about:crash", NULL));
960 return;
963 static pid_t
964 start_child(enum telescope_process p, const char *argv0, int fd)
966 const char *argv[4];
967 int argc = 0;
968 pid_t pid;
970 switch (pid = fork()) {
971 case -1:
972 die();
973 case 0:
974 break;
975 default:
976 close(fd);
977 return pid;
980 if (dup2(fd, 3) == -1)
981 err(1, "cannot setup imsg fd");
983 argv[argc++] = argv0;
984 switch (p) {
985 case PROC_UI:
986 errx(1, "Can't start ui process");
987 case PROC_FS:
988 argv[argc++] = "-Tf";
989 break;
990 case PROC_NET:
991 argv[argc++] = "-Tn";
992 break;
995 argv[argc++] = NULL;
996 execvp(argv0, (char *const *)argv);
997 err(1, "execvp(%s)", argv0);
1000 static int
1001 ui_send_net(int type, uint32_t peerid, const void *data,
1002 uint16_t datalen)
1004 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1005 datalen);
1008 static int
1009 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1011 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1012 datalen);
1015 static void __attribute__((noreturn))
1016 usage(int r)
1018 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
1019 getprogname());
1020 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1021 exit(r);
1024 int
1025 main(int argc, char * const *argv)
1027 struct imsgev net_ibuf, fs_ibuf;
1028 int pipe2net[2], pipe2fs[2];
1029 int ch, configtest = 0, fail = 0;
1030 int has_url = 0;
1031 int proc = -1;
1032 int sessionfd;
1033 char path[PATH_MAX];
1034 const char *url = NEW_TAB_URL;
1035 const char *argv0;
1037 argv0 = argv[0];
1039 signal(SIGCHLD, SIG_IGN);
1040 signal(SIGPIPE, SIG_IGN);
1042 if (getenv("NO_COLOR") != NULL)
1043 enable_colors = 0;
1045 strlcpy(path, getenv("HOME"), sizeof(path));
1046 strlcat(path, "/.telescope/config", sizeof(path));
1048 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1049 switch (ch) {
1050 case 'C':
1051 exit(ui_print_colors());
1052 case 'c':
1053 fail = 1;
1054 strlcpy(path, optarg, sizeof(path));
1055 break;
1056 case 'n':
1057 configtest = 1;
1058 break;
1059 case 'h':
1060 usage(0);
1061 case 'T':
1062 switch (*optarg) {
1063 case 'f':
1064 proc = PROC_FS;
1065 break;
1066 case 'n':
1067 proc = PROC_NET;
1068 break;
1069 default:
1070 errx(1, "invalid process spec %c",
1071 *optarg);
1073 break;
1074 case 'v':
1075 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1076 exit(0);
1077 break;
1078 default:
1079 usage(1);
1083 argc -= optind;
1084 argv += optind;
1086 if (proc != -1) {
1087 if (argc > 0)
1088 usage(1);
1089 else if (proc == PROC_FS)
1090 return fs_main();
1091 else if (proc == PROC_NET)
1092 return net_main();
1093 else
1094 usage(1);
1097 if (argc != 0) {
1098 has_url = 1;
1099 url = argv[0];
1102 /* setup keys before reading the config */
1103 TAILQ_INIT(&global_map.m);
1104 global_map.unhandled_input = global_key_unbound;
1105 TAILQ_INIT(&minibuffer_map.m);
1107 config_init();
1108 parseconfig(path, fail);
1109 if (configtest){
1110 puts("config OK");
1111 exit(0);
1114 fs_init();
1115 if ((sessionfd = lock_session()) == -1)
1116 errx(1, "can't lock session, is another instance of "
1117 "telescope already running?");
1119 /* Start children. */
1120 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1121 err(1, "socketpair");
1122 start_child(PROC_FS, argv0, pipe2fs[1]);
1123 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1124 iev_fs = &fs_ibuf;
1125 iev_fs->handler = handle_dispatch_imsg;
1127 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1128 err(1, "socketpair");
1129 start_child(PROC_NET, argv0, pipe2net[1]);
1130 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1131 iev_net = &net_ibuf;
1132 iev_net->handler = handle_dispatch_imsg;
1134 setproctitle("ui");
1136 /* initialize tofu & load certificates */
1137 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1138 load_certs(&certs);
1140 event_init();
1142 /* Setup event handlers for pipes to fs/net */
1143 iev_fs->events = EV_READ;
1144 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1145 iev_fs->handler, iev_fs);
1146 event_add(&iev_fs->ev, NULL);
1148 iev_net->events = EV_READ;
1149 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1150 iev_net->handler, iev_net);
1151 event_add(&iev_net->ev, NULL);
1153 if (ui_init()) {
1154 load_last_session();
1155 if (has_url || TAILQ_EMPTY(&tabshead))
1156 new_tab(url, NULL);
1158 sandbox_ui_process();
1159 ui_main_loop();
1160 ui_end();
1163 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1164 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1165 imsg_flush(&iev_fs->ibuf);
1166 imsg_flush(&iev_net->ibuf);
1168 close(sessionfd);
1170 return 0;