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_UNKNOWN;
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 inline const char *
644 gopher_skip_selector(const char *path, int *ret_type)
646 *ret_type = 0;
648 if (!strcmp(path, "/") || *path == '\0') {
649 *ret_type = '1';
650 return path;
653 if (*path != '/')
654 return path;
655 path++;
657 switch (*ret_type = *path) {
658 case '0':
659 case '1':
660 case '7':
661 break;
663 default:
664 *ret_type = 0;
665 path -= 1;
666 return path;
669 path++;
670 if (*path == '/')
671 path++;
673 return path;
676 static int
677 load_gopher_url(struct tab *tab, const char *url)
679 struct get_req req;
680 int type;
681 const char *path;
683 memset(&req, 0, sizeof(req));
684 strlcpy(req.host, tab->uri.host, sizeof(req.host));
685 strlcpy(req.port, tab->uri.port, sizeof(req.host));
687 path = gopher_skip_selector(tab->uri.path, &type);
688 switch (type) {
689 case '0':
690 parser_init(tab, textplain_initparser);
691 break;
692 case '1':
693 parser_init(tab, gophermap_initparser);
694 break;
695 case '7':
696 ui_require_input(tab, 0, PROTO_GOPHER);
697 return load_page_from_str(tab, err_pages[10]);
698 default:
699 return load_page_from_str(tab, "Unknown gopher selector");
702 strlcpy(req.req, path, sizeof(req.req));
703 if (*tab->uri.query != '\0') {
704 strlcat(req.req, "?", sizeof(req.req));
705 strlcat(req.req, tab->uri.query, sizeof(req.req));
707 strlcat(req.req, "\r\n", sizeof(req.req));
709 return make_request(tab, &req, PROTO_GOPHER, NULL);
712 static int
713 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
715 struct get_req req;
717 memset(&req, 0, sizeof(req));
718 strlcpy(req.host, p->host, sizeof(req.host));
719 strlcpy(req.port, p->port, sizeof(req.host));
721 tab->proxy = p;
723 return make_request(tab, &req, p->proto, tab->hist_cur->h);
726 static int
727 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
729 stop_tab(tab);
730 tab->id = tab_new_id();
731 req->proto = proto;
733 if (r != NULL) {
734 strlcpy(req->req, r, sizeof(req->req));
735 strlcat(req->req, "\r\n", sizeof(req->req));
738 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
740 /*
741 * So the various load_*_url can `return make_request` and
742 * do_load_url is happy.
743 */
744 return 1;
747 static int
748 make_fs_request(struct tab *tab, int type, const char *r)
750 stop_tab(tab);
751 tab->id = tab_new_id();
753 ui_send_fs(type, tab->id, r, strlen(r)+1);
755 /*
756 * So load_{about,file}_url can `return make_fs_request` and
757 * do_load_url is happy.
758 */
759 return 1;
762 void
763 gopher_send_search_req(struct tab *tab, const char *text)
765 struct get_req req;
767 start_loading_anim(tab);
769 memset(&req, 0, sizeof(req));
770 strlcpy(req.host, tab->uri.host, sizeof(req.host));
771 strlcpy(req.port, tab->uri.port, sizeof(req.host));
773 /* +2 to skip /7 */
774 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
775 if (*tab->uri.query != '\0') {
776 strlcat(req.req, "?", sizeof(req.req));
777 strlcat(req.req, tab->uri.query, sizeof(req.req));
780 strlcat(req.req, "\t", sizeof(req.req));
781 strlcat(req.req, text, sizeof(req.req));
782 strlcat(req.req, "\r\n", sizeof(req.req));
784 erase_buffer(&tab->buffer);
785 parser_init(tab, gophermap_initparser);
787 make_request(tab, &req, PROTO_GOPHER, NULL);
790 /*
791 * Effectively load the given url in the given tab. Return 1 when
792 * loading the page asynchronously, and thus when an erase_buffer can
793 * be done right after this function return, or 0 when loading the
794 * page synchronously. In this last case, erase_buffer *MUST* be
795 * called by the handling function (such as load_page_from_str).
796 */
797 static int
798 do_load_url(struct tab *tab, const char *url, const char *base)
800 struct phos_uri uri;
801 struct proto *p;
802 struct proxy *proxy;
803 char *t;
805 tab->proxy = NULL;
807 if (tab->fd != -1) {
808 close(tab->fd);
809 tab->fd = -1;
810 free(tab->path);
811 tab->path = NULL;
814 tab->trust = TS_UNKNOWN;
816 if (base == NULL)
817 memcpy(&uri, &tab->uri, sizeof(tab->uri));
818 else
819 phos_parse_absolute_uri(base, &uri);
821 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
822 if (asprintf(&t, "#error loading %s\n>%s\n",
823 url, "Can't parse the URI") == -1)
824 die();
825 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
826 load_page_from_str(tab, t);
827 free(t);
828 return 0;
831 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
832 sizeof(tab->hist_cur->h));
834 for (p = protos; p->schema != NULL; ++p) {
835 if (!strcmp(tab->uri.scheme, p->schema)) {
836 /* patch the port */
837 if (*tab->uri.port == '\0' && p->port != NULL)
838 strlcpy(tab->uri.port, p->port,
839 sizeof(tab->uri.port));
841 return p->loadfn(tab, url);
845 TAILQ_FOREACH(proxy, &proxies, proxies) {
846 if (!strcmp(tab->uri.scheme, proxy->match_proto))
847 return load_via_proxy(tab, url, proxy);
850 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
853 /*
854 * Load url in tab. If tab is marked as lazy, only prepare the url
855 * but don't load it. If tab is lazy and a url was already prepared,
856 * do load it!
857 */
858 void
859 load_url(struct tab *tab, const char *url, const char *base, int nohist)
861 int lazy;
863 lazy = tab->flags & TAB_LAZY;
865 if (lazy && tab->hist_cur != NULL) {
866 lazy = 0;
867 tab->flags &= ~TAB_LAZY;
870 /* can't have both nohist and lazy at the same time. */
871 if (nohist && lazy)
872 nohist = 0;
874 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
875 if (tab->hist_cur != NULL)
876 hist_clear_forward(&tab->hist,
877 TAILQ_NEXT(tab->hist_cur, entries));
879 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
880 event_loopbreak();
881 return;
884 strlcpy(tab->buffer.page.title, url,
885 sizeof(tab->buffer.page.title));
886 hist_push(&tab->hist, tab->hist_cur);
888 if (lazy)
889 strlcpy(tab->hist_cur->h, url,
890 sizeof(tab->hist_cur->h));
893 if (!lazy && do_load_url(tab, url, base))
894 erase_buffer(&tab->buffer);
897 int
898 load_previous_page(struct tab *tab)
900 struct hist *h;
902 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
903 return 0;
904 tab->hist_cur = h;
905 do_load_url(tab, h->h, NULL);
906 return 1;
909 int
910 load_next_page(struct tab *tab)
912 struct hist *h;
914 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
915 return 0;
916 tab->hist_cur = h;
917 do_load_url(tab, h->h, NULL);
918 return 1;
921 /*
922 * Free every resource linked to the tab, including the tab itself.
923 * Removes the tab from the tablist, but doesn't update the
924 * current_tab though.
925 */
926 void
927 free_tab(struct tab *tab)
929 stop_tab(tab);
931 if (evtimer_pending(&tab->loadingev, NULL))
932 evtimer_del(&tab->loadingev);
934 TAILQ_REMOVE(&tabshead, tab, tabs);
935 free(tab);
938 void
939 stop_tab(struct tab *tab)
941 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
943 if (tab->fd != -1) {
944 close(tab->fd);
945 tab->fd = -1;
946 free(tab->path);
947 tab->path = NULL;
948 load_page_from_str(tab, "Stopped.\n");
952 void
953 add_to_bookmarks(const char *str)
955 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
956 str, strlen(str)+1);
959 void
960 save_session(void)
962 struct tab *tab;
963 char *t;
964 int flags;
966 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
968 TAILQ_FOREACH(tab, &tabshead, tabs) {
969 flags = tab->flags;
970 if (tab == current_tab)
971 flags |= TAB_CURRENT;
973 t = tab->hist_cur->h;
974 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
976 t = tab->buffer.page.title;
977 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
980 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
983 /*
984 * Parse a line of the session file. The format is:
986 * URL [flags,...] [title]\n
987 */
988 static void
989 parse_session_line(char *line, const char **title, uint32_t *flags)
991 char *s, *t, *ap;
993 *title = "";
994 *flags = 0;
995 if ((s = strchr(line, ' ')) == NULL)
996 return;
998 *s++ = '\0';
1000 if ((t = strchr(s, ' ')) != NULL) {
1001 *t++ = '\0';
1002 *title = t;
1005 while ((ap = strsep(&s, ",")) != NULL) {
1006 if (*ap == '\0')
1008 else if (!strcmp(ap, "current"))
1009 *flags |= TAB_CURRENT;
1010 else
1011 message("unknown tab flag: %s", ap);
1015 static void
1016 load_last_session(void)
1018 const char *title;
1019 char *nl, *line = NULL;
1020 uint32_t flags;
1021 size_t linesize = 0;
1022 ssize_t linelen;
1023 FILE *session;
1024 struct tab *tab, *curr = NULL;
1026 if ((session = fopen(session_file, "r")) == NULL) {
1027 /* first time? */
1028 new_tab("about:new", NULL, NULL);
1029 switch_to_tab(new_tab("about:help", NULL, NULL));
1030 return;
1033 while ((linelen = getline(&line, &linesize, session)) != -1) {
1034 if ((nl = strchr(line, '\n')) != NULL)
1035 *nl = '\0';
1036 parse_session_line(line, &title, &flags);
1037 if ((tab = new_tab(line, NULL, NULL)) == NULL)
1038 err(1, "new_tab");
1039 strlcpy(tab->buffer.page.title, title,
1040 sizeof(tab->buffer.page.title));
1041 if (flags & TAB_CURRENT)
1042 curr = tab;
1045 if (ferror(session))
1046 message("error reading %s: %s",
1047 session_file, strerror(errno));
1048 fclose(session);
1049 free(line);
1051 if (curr != NULL)
1052 switch_to_tab(curr);
1054 if (last_time_crashed())
1055 switch_to_tab(new_tab("about:crash", NULL, NULL));
1057 return;
1060 static pid_t
1061 start_child(enum telescope_process p, const char *argv0, int fd)
1063 const char *argv[4];
1064 int argc = 0;
1065 pid_t pid;
1067 switch (pid = fork()) {
1068 case -1:
1069 die();
1070 case 0:
1071 break;
1072 default:
1073 close(fd);
1074 return pid;
1077 if (dup2(fd, 3) == -1)
1078 err(1, "cannot setup imsg fd");
1080 argv[argc++] = argv0;
1081 switch (p) {
1082 case PROC_UI:
1083 errx(1, "Can't start ui process");
1084 case PROC_FS:
1085 argv[argc++] = "-Tf";
1086 break;
1087 case PROC_NET:
1088 argv[argc++] = "-Tn";
1089 break;
1092 argv[argc++] = NULL;
1093 execvp(argv0, (char *const *)argv);
1094 err(1, "execvp(%s)", argv0);
1097 static int
1098 ui_send_net(int type, uint32_t peerid, const void *data,
1099 uint16_t datalen)
1101 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1102 datalen);
1105 static int
1106 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1108 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1109 datalen);
1112 static void __attribute__((noreturn))
1113 usage(int r)
1115 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
1116 getprogname());
1117 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1118 exit(r);
1121 int
1122 main(int argc, char * const *argv)
1124 struct imsgev net_ibuf, fs_ibuf;
1125 int pipe2net[2], pipe2fs[2];
1126 int ch, configtest = 0, fail = 0;
1127 int has_url = 0;
1128 int proc = -1;
1129 int sessionfd;
1130 char path[PATH_MAX];
1131 const char *url = NEW_TAB_URL;
1132 const char *argv0;
1134 argv0 = argv[0];
1136 signal(SIGCHLD, SIG_IGN);
1137 signal(SIGPIPE, SIG_IGN);
1139 if (getenv("NO_COLOR") != NULL)
1140 enable_colors = 0;
1142 strlcpy(path, getenv("HOME"), sizeof(path));
1143 strlcat(path, "/.telescope/config", sizeof(path));
1145 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1146 switch (ch) {
1147 case 'C':
1148 exit(ui_print_colors());
1149 case 'c':
1150 fail = 1;
1151 strlcpy(path, optarg, sizeof(path));
1152 break;
1153 case 'n':
1154 configtest = 1;
1155 break;
1156 case 'h':
1157 usage(0);
1158 case 'T':
1159 switch (*optarg) {
1160 case 'f':
1161 proc = PROC_FS;
1162 break;
1163 case 'n':
1164 proc = PROC_NET;
1165 break;
1166 default:
1167 errx(1, "invalid process spec %c",
1168 *optarg);
1170 break;
1171 case 'v':
1172 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1173 exit(0);
1174 break;
1175 default:
1176 usage(1);
1180 argc -= optind;
1181 argv += optind;
1183 if (proc != -1) {
1184 if (argc > 0)
1185 usage(1);
1186 else if (proc == PROC_FS)
1187 return fs_main();
1188 else if (proc == PROC_NET)
1189 return net_main();
1190 else
1191 usage(1);
1194 if (argc != 0) {
1195 has_url = 1;
1196 url = argv[0];
1199 /* setup keys before reading the config */
1200 TAILQ_INIT(&global_map.m);
1201 global_map.unhandled_input = global_key_unbound;
1202 TAILQ_INIT(&minibuffer_map.m);
1204 config_init();
1205 parseconfig(path, fail);
1206 if (configtest){
1207 puts("config OK");
1208 exit(0);
1211 fs_init();
1212 if ((sessionfd = lock_session()) == -1)
1213 errx(1, "can't lock session, is another instance of "
1214 "telescope already running?");
1216 /* Start children. */
1217 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1218 err(1, "socketpair");
1219 start_child(PROC_FS, argv0, pipe2fs[1]);
1220 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1221 iev_fs = &fs_ibuf;
1222 iev_fs->handler = handle_dispatch_imsg;
1224 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1225 err(1, "socketpair");
1226 start_child(PROC_NET, argv0, pipe2net[1]);
1227 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1228 iev_net = &net_ibuf;
1229 iev_net->handler = handle_dispatch_imsg;
1231 setproctitle("ui");
1233 /* initialize tofu & load certificates */
1234 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1235 load_certs(&certs);
1237 event_init();
1239 /* Setup event handlers for pipes to fs/net */
1240 iev_fs->events = EV_READ;
1241 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1242 iev_fs->handler, iev_fs);
1243 event_add(&iev_fs->ev, NULL);
1245 iev_net->events = EV_READ;
1246 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1247 iev_net->handler, iev_net);
1248 event_add(&iev_net->ev, NULL);
1250 if (ui_init()) {
1251 load_last_session();
1252 if (has_url || TAILQ_EMPTY(&tabshead))
1253 new_tab(url, NULL, NULL);
1255 sandbox_ui_process();
1256 ui_main_loop();
1257 ui_end();
1260 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1261 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1262 imsg_flush(&iev_fs->ibuf);
1263 imsg_flush(&iev_net->ibuf);
1265 close(sessionfd);
1267 return 0;