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 int load_page_from_str(struct tab*, const char*);
105 static int load_about_url(struct tab*, const char*);
106 static int load_file_url(struct tab *, const char *);
107 static int load_finger_url(struct tab *, const char *);
108 static int load_gemini_url(struct tab*, const char*);
109 static int load_gopher_url(struct tab *, const char *);
110 static int load_via_proxy(struct tab *, const char *,
111 struct proxy *);
112 static int make_request(struct tab *, struct get_req *, int,
113 const char *);
114 static int make_fs_request(struct tab *, int, const char *);
115 static int do_load_url(struct tab*, const char *, const char *);
116 static void parse_session_line(char *, const char **, uint32_t *);
117 static void load_last_session(void);
118 static pid_t start_child(enum telescope_process, const char *, int);
119 static int ui_send_net(int, uint32_t, const void *, uint16_t);
120 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
122 static struct proto {
123 const char *schema;
124 const char *port;
125 int (*loadfn)(struct tab*, const char*);
126 } protos[] = {
127 {"about", NULL, load_about_url},
128 {"file", NULL, load_file_url},
129 {"finger", "79", load_finger_url},
130 {"gemini", "1965", load_gemini_url},
131 {"gopher", "70", load_gopher_url},
132 {NULL, NULL, NULL},
133 };
135 static imsg_handlerfn *handlers[] = {
136 [IMSG_ERR] = handle_imsg_err,
137 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
138 [IMSG_GOT_CODE] = handle_imsg_got_code,
139 [IMSG_GOT_META] = handle_imsg_got_meta,
140 [IMSG_BUF] = handle_imsg_buf,
141 [IMSG_EOF] = handle_imsg_eof,
142 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
143 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
144 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
145 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
146 };
148 static struct ohash certs;
150 static void __attribute__((__noreturn__))
151 die(void)
153 abort(); /* TODO */
156 static struct tab *
157 tab_by_id(uint32_t id)
159 struct tab *t;
161 TAILQ_FOREACH(t, &tabshead, tabs) {
162 if (t->id == id)
163 return t;
166 return NULL;
169 static void
170 handle_imsg_err(struct imsg *imsg, size_t datalen)
172 struct tab *tab;
173 char *page;
175 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
176 return;
178 page = imsg->data;
179 page[datalen-1] = '\0';
181 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
182 tab->hist_cur->h, page) == -1)
183 die();
184 load_page_from_str(tab, page);
185 free(page);
188 static void
189 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
191 const char *hash, *host, *port;
192 int tofu_res;
193 struct tofu_entry *e;
194 struct tab *tab;
196 hash = imsg->data;
197 if (hash[datalen-1] != '\0')
198 abort();
200 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
201 return;
203 if (tab->proxy != NULL) {
204 host = tab->proxy->host;
205 port = tab->proxy->port;
206 } else {
207 host = tab->uri.host;
208 port = tab->uri.port;
211 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
212 /* TODO: an update in libressl/libretls changed
213 * significantly. Find a better approach at storing
214 * the certs! */
215 if (datalen > sizeof(e->hash))
216 abort();
218 tofu_res = 1; /* trust on first use */
219 if ((e = calloc(1, sizeof(*e))) == NULL)
220 abort();
221 strlcpy(e->domain, host, sizeof(e->domain));
222 if (*port != '\0' && strcmp(port, "1965")) {
223 strlcat(e->domain, ":", sizeof(e->domain));
224 strlcat(e->domain, port, sizeof(e->domain));
226 strlcpy(e->hash, hash, sizeof(e->hash));
227 tofu_add(&certs, e);
228 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
229 } else
230 tofu_res = !strcmp(hash, e->hash);
232 if (tofu_res) {
233 if (e->verified == -1)
234 tab->trust = TS_TEMP_TRUSTED;
235 else if (e->verified == 1)
236 tab->trust = TS_VERIFIED;
237 else
238 tab->trust = TS_TRUSTED;
240 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
241 &tofu_res, sizeof(tofu_res));
242 } else {
243 tab->trust = TS_UNTRUSTED;
244 load_page_from_str(tab, "# Certificate mismatch\n");
245 if ((tab->cert = strdup(hash)) == NULL)
246 die();
247 ui_yornp("Certificate mismatch. Proceed?",
248 handle_check_cert_user_choice, tab);
252 static void
253 handle_check_cert_user_choice(int accept, struct tab *tab)
255 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
256 sizeof(accept));
258 if (accept) {
259 /*
260 * trust the certificate for this session only. If
261 * the page results in a redirect while we're asking
262 * the user to save, we'll end up with an invalid
263 * tabid (one request == one tab id) and crash. It
264 * also makes sense to save it for the current session
265 * if the user accepted it.
266 */
267 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
269 ui_yornp("Save the new certificate?",
270 handle_maybe_save_new_cert, tab);
271 } else {
272 free(tab->cert);
273 tab->cert = NULL;
277 static void
278 handle_maybe_save_new_cert(int accept, struct tab *tab)
280 struct tofu_entry *e;
281 const char *host, *port;
283 if (tab->proxy != NULL) {
284 host = tab->proxy->host;
285 port = tab->proxy->port;
286 } else {
287 host = tab->uri.host;
288 port = tab->uri.port;
291 if (!accept)
292 goto end;
294 if ((e = calloc(1, sizeof(*e))) == NULL)
295 die();
297 strlcpy(e->domain, host, sizeof(e->domain));
298 if (*port != '\0' && strcmp(port, "1965")) {
299 strlcat(e->domain, ":", sizeof(e->domain));
300 strlcat(e->domain, port, sizeof(e->domain));
302 strlcpy(e->hash, tab->cert, sizeof(e->hash));
303 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
305 tofu_update(&certs, e);
307 tab->trust = TS_TRUSTED;
309 end:
310 free(tab->cert);
311 tab->cert = NULL;
314 static inline int
315 normalize_code(int n)
317 if (n < 20) {
318 if (n == 10 || n == 11)
319 return n;
320 return 10;
321 } else if (n < 30) {
322 return 20;
323 } else if (n < 40) {
324 if (n == 30 || n == 31)
325 return n;
326 return 30;
327 } else if (n < 50) {
328 if (n <= 44)
329 return n;
330 return 40;
331 } else if (n < 60) {
332 if (n <= 53 || n == 59)
333 return n;
334 return 50;
335 } else if (n < 70) {
336 if (n <= 62)
337 return n;
338 return 60;
339 } else
340 return MALFORMED_RESPONSE;
343 static void
344 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
346 struct tab *tab;
348 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
349 return;
351 if (sizeof(tab->code) != datalen)
352 die();
354 memcpy(&tab->code, imsg->data, sizeof(tab->code));
355 tab->code = normalize_code(tab->code);
356 if (tab->code != 30 && tab->code != 31)
357 tab->redirect_count = 0;
360 static void
361 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
363 struct tab *tab;
365 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
366 return;
368 if (sizeof(tab->meta) <= datalen)
369 die();
371 memcpy(tab->meta, imsg->data, datalen);
373 if (tab->code < 10) { /* internal errors */
374 load_page_from_str(tab, err_pages[tab->code]);
375 } else if (tab->code < 20) { /* 1x */
376 load_page_from_str(tab, err_pages[tab->code]);
377 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
378 } else if (tab->code == 20) {
379 if (setup_parser_for(tab)) {
380 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
381 } else {
382 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
383 ui_yornp("Can't display page, wanna save?",
384 handle_maybe_save_page, tab);
386 } else if (tab->code < 40) { /* 3x */
387 tab->redirect_count++;
389 /* TODO: make customizable? */
390 if (tab->redirect_count > 5) {
391 load_page_from_str(tab,
392 err_pages[TOO_MUCH_REDIRECTS]);
393 } else
394 do_load_url(tab, tab->meta, NULL);
395 } else { /* 4x, 5x & 6x */
396 load_page_from_str(tab, err_pages[tab->code]);
400 static void
401 handle_maybe_save_page(int dosave, struct tab *tab)
403 if (dosave)
404 ui_read("Save to path", handle_save_page_path, tab);
405 else
406 stop_tab(tab);
409 static void
410 handle_save_page_path(const char *path, struct tab *tab)
412 if (path == NULL) {
413 stop_tab(tab);
414 return;
417 tab->path = strdup(path);
419 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
422 static void
423 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
425 struct tab *tab;
426 char *page;
427 const char *e;
428 int l;
430 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
431 if (imsg->fd != -1)
432 close(imsg->fd);
433 return;
436 if (imsg->fd == -1) {
437 stop_tab(tab);
439 e = imsg->data;
440 if (e[datalen-1] != '\0')
441 die();
442 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
443 tab->path, e);
444 if (l == -1)
445 die();
446 load_page_from_str(tab, page);
447 free(page);
448 } else {
449 tab->fd = imsg->fd;
450 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
454 static void
455 handle_imsg_buf(struct imsg *imsg, size_t datalen)
457 struct tab *tab;
458 int l;
459 char *page, buf[FMT_SCALED_STRSIZE] = {0};
461 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
462 return;
464 tab->bytes += datalen;
465 if (tab->fd == -1) {
466 if (!parser_parse(tab, imsg->data, datalen))
467 die();
468 } else {
469 write(tab->fd, imsg->data, datalen);
470 fmt_scaled(tab->bytes, buf);
471 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
472 tab->path,
473 buf);
474 if (l == -1)
475 die();
476 load_page_from_str(tab, page);
477 free(page);
480 ui_on_tab_refresh(tab);
483 static void
484 handle_imsg_eof(struct imsg *imsg, size_t datalen)
486 struct tab *tab;
487 int l;
488 char *page, buf[FMT_SCALED_STRSIZE] = {0};
490 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
491 return;
493 if (tab->fd == -1) {
494 if (!parser_free(tab))
495 die();
496 } else {
497 fmt_scaled(tab->bytes, buf);
498 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
499 tab->path,
500 buf);
501 if (l == -1)
502 die();
503 load_page_from_str(tab, page);
504 free(page);
506 close(tab->fd);
507 tab->fd = -1;
508 free(tab->path);
509 tab->path = NULL;
512 ui_on_tab_refresh(tab);
513 ui_on_tab_loaded(tab);
516 static void
517 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
519 int res;
521 if (datalen != sizeof(res))
522 die();
524 memcpy(&res, imsg->data, sizeof(res));
525 if (res == 0)
526 message("Added to bookmarks!");
527 else
528 message("Failed to add to bookmarks: %s",
529 strerror(res));
532 static void
533 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
535 int res;
537 if (datalen != sizeof(res))
538 die();
539 memcpy(&res, imsg->data, datalen);
540 if (res != 0)
541 message("Failed to save the cert for: %s",
542 strerror(res));
545 static void
546 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
548 int res;
550 if (datalen != sizeof(res))
551 die();
552 memcpy(&res, imsg->data, datalen);
553 if (!res)
554 message("Failed to update the certificate");
557 static void
558 handle_dispatch_imsg(int fd, short ev, void *d)
560 struct imsgev *iev = d;
562 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
563 err(1, "connection closed");
566 static int
567 load_page_from_str(struct tab *tab, const char *page)
569 erase_buffer(&tab->buffer);
570 parser_init(tab, gemtext_initparser);
571 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
572 die();
573 if (!tab->buffer.page.free(&tab->buffer.page))
574 die();
575 ui_on_tab_refresh(tab);
576 ui_on_tab_loaded(tab);
577 return 0;
580 static int
581 load_about_url(struct tab *tab, const char *url)
583 tab->trust = TS_VERIFIED;
584 parser_init(tab, gemtext_initparser);
585 return make_fs_request(tab, IMSG_GET, url);
588 static int
589 load_file_url(struct tab *tab, const char *url)
591 tab->trust = TS_UNKNOWN;
592 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
595 static int
596 load_finger_url(struct tab *tab, const char *url)
598 struct get_req req;
599 size_t len;
600 char *at;
602 memset(&req, 0, sizeof(req));
603 strlcpy(req.port, tab->uri.port, sizeof(req.port));
605 /*
606 * Sometimes the finger url have the user as path component
607 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
608 * userinfo (e.g. finger://cobradile@finger.farm).
609 */
610 if ((at = strchr(tab->uri.host, '@')) != NULL) {
611 len = at - tab->uri.host;
612 memcpy(req.req, tab->uri.host, len);
614 if (len >= sizeof(req.req))
615 die();
616 req.req[len] = '\0';
618 strlcpy(req.host, at+1, sizeof(req.host));
619 } else {
620 strlcpy(req.host, tab->uri.host, sizeof(req.host));
622 /* +1 to skip the initial `/' */
623 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
625 strlcat(req.req, "\r\n", sizeof(req.req));
627 parser_init(tab, textplain_initparser);
628 return make_request(tab, &req, PROTO_FINGER, NULL);
631 static int
632 load_gemini_url(struct tab *tab, const char *url)
634 struct get_req req;
636 memset(&req, 0, sizeof(req));
637 strlcpy(req.host, tab->uri.host, sizeof(req.host));
638 strlcpy(req.port, tab->uri.port, sizeof(req.host));
640 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
643 static int
644 load_gopher_url(struct tab *tab, const char *url)
646 struct get_req req;
647 const char *path;
649 memset(&req, 0, sizeof(req));
650 strlcpy(req.host, tab->uri.host, sizeof(req.host));
651 strlcpy(req.port, tab->uri.port, sizeof(req.host));
653 path = tab->uri.path;
654 if (!strcmp(path, "/") || *path == '\0') {
655 /* expect the top directory to be a gophermap */
656 parser_init(tab, gophermap_initparser);
657 } else if (has_prefix(path, "/1/")) {
658 /* gophermap menu/submenu */
659 parser_init(tab, gophermap_initparser);
660 path += 2;
661 } else if (has_prefix(path, "/0/")) {
662 parser_init(tab, textplain_initparser);
663 path += 2;
664 } else if (has_prefix(path, "/7/")) {
665 /* show input request if there is no query */
666 ui_require_input(tab, 0, PROTO_GOPHER);
667 return load_page_from_str(tab, err_pages[10]);
668 } else {
669 return 0;
672 strlcpy(req.req, path, sizeof(req.req));
673 if (*tab->uri.query != '\0') {
674 strlcat(req.req, "?", sizeof(req.req));
675 strlcat(req.req, tab->uri.query, sizeof(req.req));
677 strlcat(req.req, "\r\n", sizeof(req.req));
679 return make_request(tab, &req, PROTO_GOPHER, NULL);
682 static int
683 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
685 struct get_req req;
687 memset(&req, 0, sizeof(req));
688 strlcpy(req.host, p->host, sizeof(req.host));
689 strlcpy(req.port, p->port, sizeof(req.host));
691 tab->proxy = p;
693 return make_request(tab, &req, p->proto, tab->hist_cur->h);
696 static int
697 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
699 stop_tab(tab);
700 tab->id = tab_new_id();
701 req->proto = proto;
703 if (r != NULL) {
704 strlcpy(req->req, r, sizeof(req->req));
705 strlcat(req->req, "\r\n", sizeof(req->req));
708 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
710 /*
711 * So the various load_*_url can `return make_request` and
712 * do_load_url is happy.
713 */
714 return 1;
717 static int
718 make_fs_request(struct tab *tab, int type, const char *r)
720 stop_tab(tab);
721 tab->id = tab_new_id();
723 ui_send_fs(type, tab->id, r, strlen(r)+1);
725 /*
726 * So load_{about,file}_url can `return make_fs_request` and
727 * do_load_url is happy.
728 */
729 return 1;
732 void
733 gopher_send_search_req(struct tab *tab, const char *text)
735 struct get_req req;
737 start_loading_anim(tab);
739 memset(&req, 0, sizeof(req));
740 strlcpy(req.host, tab->uri.host, sizeof(req.host));
741 strlcpy(req.port, tab->uri.port, sizeof(req.host));
743 /* +2 to skip /7 */
744 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
745 if (*tab->uri.query != '\0') {
746 strlcat(req.req, "?", sizeof(req.req));
747 strlcat(req.req, tab->uri.query, sizeof(req.req));
750 strlcat(req.req, "\t", sizeof(req.req));
751 strlcat(req.req, text, sizeof(req.req));
752 strlcat(req.req, "\r\n", sizeof(req.req));
754 erase_buffer(&tab->buffer);
755 parser_init(tab, gophermap_initparser);
757 make_request(tab, &req, PROTO_GOPHER, NULL);
760 /*
761 * Effectively load the given url in the given tab. Return 1 when
762 * loading the page asynchronously, and thus when an erase_buffer can
763 * be done right after this function return, or 0 when loading the
764 * page synchronously. In this last case, erase_buffer *MUST* be
765 * called by the handling function (such as load_page_from_str).
766 */
767 static int
768 do_load_url(struct tab *tab, const char *url, const char *base)
770 struct phos_uri uri;
771 struct proto *p;
772 struct proxy *proxy;
773 char *t;
775 tab->proxy = NULL;
777 if (tab->fd != -1) {
778 close(tab->fd);
779 tab->fd = -1;
780 free(tab->path);
781 tab->path = NULL;
784 tab->trust = TS_UNKNOWN;
786 if (base == NULL)
787 memcpy(&uri, &tab->uri, sizeof(tab->uri));
788 else
789 phos_parse_absolute_uri(base, &uri);
791 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
792 if (asprintf(&t, "#error loading %s\n>%s\n",
793 url, "Can't parse the URI") == -1)
794 die();
795 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
796 load_page_from_str(tab, t);
797 free(t);
798 return 0;
801 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
802 sizeof(tab->hist_cur->h));
804 for (p = protos; p->schema != NULL; ++p) {
805 if (!strcmp(tab->uri.scheme, p->schema)) {
806 /* patch the port */
807 if (*tab->uri.port == '\0' && p->port != NULL)
808 strlcpy(tab->uri.port, p->port,
809 sizeof(tab->uri.port));
811 return p->loadfn(tab, url);
815 TAILQ_FOREACH(proxy, &proxies, proxies) {
816 if (!strcmp(tab->uri.scheme, proxy->match_proto))
817 return load_via_proxy(tab, url, proxy);
820 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
823 /*
824 * Load url in tab. If tab is marked as lazy, only prepare the url
825 * but don't load it. If tab is lazy and a url was already prepared,
826 * do load it!
827 */
828 void
829 load_url(struct tab *tab, const char *url, const char *base, int nohist)
831 int lazy;
833 lazy = tab->flags & TAB_LAZY;
835 if (lazy && tab->hist_cur != NULL) {
836 lazy = 0;
837 tab->flags &= ~TAB_LAZY;
840 /* can't have both nohist and lazy at the same time. */
841 if (nohist && lazy)
842 nohist = 0;
844 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
845 if (tab->hist_cur != NULL)
846 hist_clear_forward(&tab->hist,
847 TAILQ_NEXT(tab->hist_cur, entries));
849 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
850 event_loopbreak();
851 return;
854 strlcpy(tab->buffer.page.title, url,
855 sizeof(tab->buffer.page.title));
856 hist_push(&tab->hist, tab->hist_cur);
858 if (lazy)
859 strlcpy(tab->hist_cur->h, url,
860 sizeof(tab->hist_cur->h));
863 if (!lazy && do_load_url(tab, url, base))
864 erase_buffer(&tab->buffer);
867 int
868 load_previous_page(struct tab *tab)
870 struct hist *h;
872 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
873 return 0;
874 tab->hist_cur = h;
875 do_load_url(tab, h->h, NULL);
876 return 1;
879 int
880 load_next_page(struct tab *tab)
882 struct hist *h;
884 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
885 return 0;
886 tab->hist_cur = h;
887 do_load_url(tab, h->h, NULL);
888 return 1;
891 /*
892 * Free every resource linked to the tab, including the tab itself.
893 * Removes the tab from the tablist, but doesn't update the
894 * current_tab though.
895 */
896 void
897 free_tab(struct tab *tab)
899 stop_tab(tab);
901 if (evtimer_pending(&tab->loadingev, NULL))
902 evtimer_del(&tab->loadingev);
904 TAILQ_REMOVE(&tabshead, tab, tabs);
905 free(tab);
908 void
909 stop_tab(struct tab *tab)
911 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
913 if (tab->fd != -1) {
914 close(tab->fd);
915 tab->fd = -1;
916 free(tab->path);
917 tab->path = NULL;
918 load_page_from_str(tab, "Stopped.\n");
922 void
923 add_to_bookmarks(const char *str)
925 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
926 str, strlen(str)+1);
929 void
930 save_session(void)
932 struct tab *tab;
933 char *t;
934 int flags;
936 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
938 TAILQ_FOREACH(tab, &tabshead, tabs) {
939 flags = tab->flags;
940 if (tab == current_tab)
941 flags |= TAB_CURRENT;
943 t = tab->hist_cur->h;
944 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
946 t = tab->buffer.page.title;
947 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
950 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
953 /*
954 * Parse a line of the session file. The format is:
956 * URL [flags,...] [title]\n
957 */
958 static void
959 parse_session_line(char *line, const char **title, uint32_t *flags)
961 char *s, *t, *ap;
963 *title = "";
964 *flags = 0;
965 if ((s = strchr(line, ' ')) == NULL)
966 return;
968 *s++ = '\0';
970 if ((t = strchr(s, ' ')) != NULL) {
971 *t++ = '\0';
972 *title = t;
975 while ((ap = strsep(&s, ",")) != NULL) {
976 if (*ap == '\0')
978 else if (!strcmp(ap, "current"))
979 *flags |= TAB_CURRENT;
980 else
981 message("unknown tab flag: %s", ap);
985 static void
986 load_last_session(void)
988 const char *title;
989 char *nl, *line = NULL;
990 uint32_t flags;
991 size_t linesize = 0;
992 ssize_t linelen;
993 FILE *session;
994 struct tab *tab, *curr = NULL;
996 if ((session = fopen(session_file, "r")) == NULL) {
997 /* first time? */
998 new_tab("about:new", NULL, NULL);
999 switch_to_tab(new_tab("about:help", NULL, NULL));
1000 return;
1003 while ((linelen = getline(&line, &linesize, session)) != -1) {
1004 if ((nl = strchr(line, '\n')) != NULL)
1005 *nl = '\0';
1006 parse_session_line(line, &title, &flags);
1007 if ((tab = new_tab(line, NULL, NULL)) == NULL)
1008 err(1, "new_tab");
1009 strlcpy(tab->buffer.page.title, title,
1010 sizeof(tab->buffer.page.title));
1011 if (flags & TAB_CURRENT)
1012 curr = tab;
1015 if (ferror(session))
1016 message("error reading %s: %s",
1017 session_file, strerror(errno));
1018 fclose(session);
1019 free(line);
1021 if (curr != NULL)
1022 switch_to_tab(curr);
1024 if (last_time_crashed())
1025 switch_to_tab(new_tab("about:crash", NULL, NULL));
1027 return;
1030 static pid_t
1031 start_child(enum telescope_process p, const char *argv0, int fd)
1033 const char *argv[4];
1034 int argc = 0;
1035 pid_t pid;
1037 switch (pid = fork()) {
1038 case -1:
1039 die();
1040 case 0:
1041 break;
1042 default:
1043 close(fd);
1044 return pid;
1047 if (dup2(fd, 3) == -1)
1048 err(1, "cannot setup imsg fd");
1050 argv[argc++] = argv0;
1051 switch (p) {
1052 case PROC_UI:
1053 errx(1, "Can't start ui process");
1054 case PROC_FS:
1055 argv[argc++] = "-Tf";
1056 break;
1057 case PROC_NET:
1058 argv[argc++] = "-Tn";
1059 break;
1062 argv[argc++] = NULL;
1063 execvp(argv0, (char *const *)argv);
1064 err(1, "execvp(%s)", argv0);
1067 static int
1068 ui_send_net(int type, uint32_t peerid, const void *data,
1069 uint16_t datalen)
1071 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1072 datalen);
1075 static int
1076 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1078 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1079 datalen);
1082 static void __attribute__((noreturn))
1083 usage(int r)
1085 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
1086 getprogname());
1087 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1088 exit(r);
1091 int
1092 main(int argc, char * const *argv)
1094 struct imsgev net_ibuf, fs_ibuf;
1095 int pipe2net[2], pipe2fs[2];
1096 int ch, configtest = 0, fail = 0;
1097 int has_url = 0;
1098 int proc = -1;
1099 int sessionfd;
1100 char path[PATH_MAX];
1101 const char *url = NEW_TAB_URL;
1102 const char *argv0;
1104 argv0 = argv[0];
1106 signal(SIGCHLD, SIG_IGN);
1107 signal(SIGPIPE, SIG_IGN);
1109 if (getenv("NO_COLOR") != NULL)
1110 enable_colors = 0;
1112 strlcpy(path, getenv("HOME"), sizeof(path));
1113 strlcat(path, "/.telescope/config", sizeof(path));
1115 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1116 switch (ch) {
1117 case 'C':
1118 exit(ui_print_colors());
1119 case 'c':
1120 fail = 1;
1121 strlcpy(path, optarg, sizeof(path));
1122 break;
1123 case 'n':
1124 configtest = 1;
1125 break;
1126 case 'h':
1127 usage(0);
1128 case 'T':
1129 switch (*optarg) {
1130 case 'f':
1131 proc = PROC_FS;
1132 break;
1133 case 'n':
1134 proc = PROC_NET;
1135 break;
1136 default:
1137 errx(1, "invalid process spec %c",
1138 *optarg);
1140 break;
1141 case 'v':
1142 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1143 exit(0);
1144 break;
1145 default:
1146 usage(1);
1150 argc -= optind;
1151 argv += optind;
1153 if (proc != -1) {
1154 if (argc > 0)
1155 usage(1);
1156 else if (proc == PROC_FS)
1157 return fs_main();
1158 else if (proc == PROC_NET)
1159 return net_main();
1160 else
1161 usage(1);
1164 if (argc != 0) {
1165 has_url = 1;
1166 url = argv[0];
1169 /* setup keys before reading the config */
1170 TAILQ_INIT(&global_map.m);
1171 global_map.unhandled_input = global_key_unbound;
1172 TAILQ_INIT(&minibuffer_map.m);
1174 config_init();
1175 parseconfig(path, fail);
1176 if (configtest){
1177 puts("config OK");
1178 exit(0);
1181 fs_init();
1182 if ((sessionfd = lock_session()) == -1)
1183 errx(1, "can't lock session, is another instance of "
1184 "telescope already running?");
1186 /* Start children. */
1187 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1188 err(1, "socketpair");
1189 start_child(PROC_FS, argv0, pipe2fs[1]);
1190 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1191 iev_fs = &fs_ibuf;
1192 iev_fs->handler = handle_dispatch_imsg;
1194 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1195 err(1, "socketpair");
1196 start_child(PROC_NET, argv0, pipe2net[1]);
1197 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1198 iev_net = &net_ibuf;
1199 iev_net->handler = handle_dispatch_imsg;
1201 setproctitle("ui");
1203 /* initialize tofu & load certificates */
1204 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1205 load_certs(&certs);
1207 event_init();
1209 /* Setup event handlers for pipes to fs/net */
1210 iev_fs->events = EV_READ;
1211 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1212 iev_fs->handler, iev_fs);
1213 event_add(&iev_fs->ev, NULL);
1215 iev_net->events = EV_READ;
1216 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1217 iev_net->handler, iev_net);
1218 event_add(&iev_net->ev, NULL);
1220 if (ui_init()) {
1221 load_last_session();
1222 if (has_url || TAILQ_EMPTY(&tabshead))
1223 new_tab(url, NULL, NULL);
1225 sandbox_ui_process();
1226 ui_main_loop();
1227 ui_end();
1230 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1231 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1232 imsg_flush(&iev_fs->ibuf);
1233 imsg_flush(&iev_net->ibuf);
1235 close(sessionfd);
1237 return 0;