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 "session.h"
34 #include "telescope.h"
35 #include "ui.h"
37 static struct option longopts[] = {
38 {"colors", no_argument, NULL, 'c'},
39 {"help", no_argument, NULL, 'h'},
40 {"version", no_argument, NULL, 'v'},
41 {NULL, 0, NULL, 0},
42 };
44 static const char *opts = "Cc:hnT:v";
46 /*
47 * Used to know when we're finished loading.
48 */
49 int operating;
51 static struct imsgev *iev_fs, *iev_net;
53 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
54 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
56 enum telescope_process {
57 PROC_UI,
58 PROC_FS,
59 PROC_NET,
60 };
62 #define CANNOT_FETCH 0
63 #define TOO_MUCH_REDIRECTS 1
64 #define MALFORMED_RESPONSE 2
65 #define UNKNOWN_TYPE_OR_CSET 3
66 #define UNKNOWN_PROTOCOL 4
68 /* XXX: keep in sync with telescope.c:/^normalize_code/ */
69 const char *err_pages[70] = {
70 [CANNOT_FETCH] = "# Couldn't load the page\n",
71 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
72 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
73 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
74 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
76 [10] = "# Input required\n",
77 [11] = "# Input required\n",
78 [40] = "# Temporary failure\n",
79 [41] = "# Server unavailable\n",
80 [42] = "# CGI error\n",
81 [43] = "# Proxy error\n",
82 [44] = "# Slow down\n",
83 [50] = "# Permanent failure\n",
84 [51] = "# Not found\n",
85 [52] = "# Gone\n",
86 [53] = "# Proxy request refused\n",
87 [59] = "# Bad request\n",
88 [60] = "# Client certificate required\n",
89 [61] = "# Certificate not authorised\n",
90 [62] = "# Certificate not valid\n"
91 };
93 static void die(void) __attribute__((__noreturn__));
94 static struct tab *tab_by_id(uint32_t);
95 static void handle_imsg_err(struct imsg*, size_t);
96 static void handle_imsg_check_cert(struct imsg*, size_t);
97 static void handle_check_cert_user_choice(int, struct tab *);
98 static void handle_maybe_save_new_cert(int, struct tab *);
99 static void handle_imsg_got_code(struct imsg*, size_t);
100 static void handle_imsg_got_meta(struct imsg*, size_t);
101 static void handle_maybe_save_page(int, struct tab *);
102 static void handle_save_page_path(const char *, struct tab *);
103 static void handle_imsg_file_opened(struct imsg*, size_t);
104 static void handle_imsg_buf(struct imsg*, size_t);
105 static void handle_imsg_eof(struct imsg*, size_t);
106 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
107 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
108 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
109 static void handle_dispatch_imsg(int, short, void*);
110 static int load_about_url(struct tab*, const char*);
111 static int load_file_url(struct tab *, const char *);
112 static int load_finger_url(struct tab *, const char *);
113 static int load_gemini_url(struct tab*, const char*);
114 static int load_gopher_url(struct tab *, const char *);
115 static int load_via_proxy(struct tab *, const char *,
116 struct proxy *);
117 static int make_request(struct tab *, struct get_req *, int,
118 const char *);
119 static int make_fs_request(struct tab *, int, const char *);
120 static int do_load_url(struct tab*, const char *, const char *);
121 static pid_t start_child(enum telescope_process, const char *, int);
123 static struct proto {
124 const char *schema;
125 const char *port;
126 int (*loadfn)(struct tab*, const char*);
127 } protos[] = {
128 {"about", NULL, load_about_url},
129 {"file", NULL, load_file_url},
130 {"finger", "79", load_finger_url},
131 {"gemini", "1965", load_gemini_url},
132 {"gopher", "70", load_gopher_url},
133 {NULL, NULL, NULL},
134 };
136 static imsg_handlerfn *handlers[] = {
137 [IMSG_ERR] = handle_imsg_err,
138 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
139 [IMSG_GOT_CODE] = handle_imsg_got_code,
140 [IMSG_GOT_META] = handle_imsg_got_meta,
141 [IMSG_BUF] = handle_imsg_buf,
142 [IMSG_EOF] = handle_imsg_eof,
143 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
144 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
145 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
146 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
147 };
149 static struct ohash certs;
151 static void __attribute__((__noreturn__))
152 die(void)
154 abort(); /* TODO */
157 static struct tab *
158 tab_by_id(uint32_t id)
160 struct tab *t;
162 TAILQ_FOREACH(t, &tabshead, tabs) {
163 if (t->id == id)
164 return t;
167 return NULL;
170 static void
171 handle_imsg_err(struct imsg *imsg, size_t datalen)
173 struct tab *tab;
174 char *page;
176 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
177 return;
179 page = imsg->data;
180 page[datalen-1] = '\0';
182 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
183 tab->hist_cur->h, page) == -1)
184 die();
185 load_page_from_str(tab, page);
186 free(page);
189 static void
190 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
192 const char *hash, *host, *port;
193 int tofu_res;
194 struct tofu_entry *e;
195 struct tab *tab;
197 hash = imsg->data;
198 if (hash[datalen-1] != '\0')
199 abort();
201 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
202 return;
204 if (tab->proxy != NULL) {
205 host = tab->proxy->host;
206 port = tab->proxy->port;
207 } else {
208 host = tab->uri.host;
209 port = tab->uri.port;
212 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
213 /* TODO: an update in libressl/libretls changed
214 * significantly. Find a better approach at storing
215 * the certs! */
216 if (datalen > sizeof(e->hash))
217 abort();
219 tofu_res = 1; /* trust on first use */
220 if ((e = calloc(1, sizeof(*e))) == NULL)
221 abort();
222 strlcpy(e->domain, host, sizeof(e->domain));
223 if (*port != '\0' && strcmp(port, "1965")) {
224 strlcat(e->domain, ":", sizeof(e->domain));
225 strlcat(e->domain, port, sizeof(e->domain));
227 strlcpy(e->hash, hash, sizeof(e->hash));
228 tofu_add(&certs, e);
229 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
230 } else
231 tofu_res = !strcmp(hash, e->hash);
233 if (tofu_res) {
234 if (e->verified == -1)
235 tab->trust = TS_TEMP_TRUSTED;
236 else if (e->verified == 1)
237 tab->trust = TS_VERIFIED;
238 else
239 tab->trust = TS_TRUSTED;
241 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
242 &tofu_res, sizeof(tofu_res));
243 } else {
244 tab->trust = TS_UNTRUSTED;
245 load_page_from_str(tab, "# Certificate mismatch\n");
246 if ((tab->cert = strdup(hash)) == NULL)
247 die();
248 ui_yornp("Certificate mismatch. Proceed?",
249 handle_check_cert_user_choice, tab);
253 static void
254 handle_check_cert_user_choice(int accept, struct tab *tab)
256 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
257 sizeof(accept));
259 if (accept) {
260 /*
261 * trust the certificate for this session only. If
262 * the page results in a redirect while we're asking
263 * the user to save, we'll end up with an invalid
264 * tabid (one request == one tab id) and crash. It
265 * also makes sense to save it for the current session
266 * if the user accepted it.
267 */
268 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
270 ui_yornp("Save the new certificate?",
271 handle_maybe_save_new_cert, tab);
272 } else {
273 free(tab->cert);
274 tab->cert = NULL;
278 static void
279 handle_maybe_save_new_cert(int accept, struct tab *tab)
281 struct tofu_entry *e;
282 const char *host, *port;
284 if (tab->proxy != NULL) {
285 host = tab->proxy->host;
286 port = tab->proxy->port;
287 } else {
288 host = tab->uri.host;
289 port = tab->uri.port;
292 if (!accept)
293 goto end;
295 if ((e = calloc(1, sizeof(*e))) == NULL)
296 die();
298 strlcpy(e->domain, host, sizeof(e->domain));
299 if (*port != '\0' && strcmp(port, "1965")) {
300 strlcat(e->domain, ":", sizeof(e->domain));
301 strlcat(e->domain, port, sizeof(e->domain));
303 strlcpy(e->hash, tab->cert, sizeof(e->hash));
304 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
306 tofu_update(&certs, e);
308 tab->trust = TS_TRUSTED;
310 end:
311 free(tab->cert);
312 tab->cert = NULL;
315 static inline int
316 normalize_code(int n)
318 if (n < 20) {
319 if (n == 10 || n == 11)
320 return n;
321 return 10;
322 } else if (n < 30) {
323 return 20;
324 } else if (n < 40) {
325 if (n == 30 || n == 31)
326 return n;
327 return 30;
328 } else if (n < 50) {
329 if (n <= 44)
330 return n;
331 return 40;
332 } else if (n < 60) {
333 if (n <= 53 || n == 59)
334 return n;
335 return 50;
336 } else if (n < 70) {
337 if (n <= 62)
338 return n;
339 return 60;
340 } else
341 return MALFORMED_RESPONSE;
344 static void
345 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
347 struct tab *tab;
349 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
350 return;
352 if (sizeof(tab->code) != datalen)
353 die();
355 memcpy(&tab->code, imsg->data, sizeof(tab->code));
356 tab->code = normalize_code(tab->code);
357 if (tab->code != 30 && tab->code != 31)
358 tab->redirect_count = 0;
361 static void
362 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
364 struct tab *tab;
366 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
367 return;
369 if (sizeof(tab->meta) <= datalen)
370 die();
372 memcpy(tab->meta, imsg->data, datalen);
374 if (tab->code < 10) { /* internal errors */
375 load_page_from_str(tab, err_pages[tab->code]);
376 } else if (tab->code < 20) { /* 1x */
377 load_page_from_str(tab, err_pages[tab->code]);
378 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
379 } else if (tab->code == 20) {
380 if (setup_parser_for(tab)) {
381 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
382 } else {
383 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
384 ui_yornp("Can't display page, wanna save?",
385 handle_maybe_save_page, tab);
387 } else if (tab->code < 40) { /* 3x */
388 tab->redirect_count++;
390 /* TODO: make customizable? */
391 if (tab->redirect_count > 5) {
392 load_page_from_str(tab,
393 err_pages[TOO_MUCH_REDIRECTS]);
394 } else
395 do_load_url(tab, tab->meta, NULL);
396 } else { /* 4x, 5x & 6x */
397 load_page_from_str(tab, err_pages[tab->code]);
401 static void
402 handle_maybe_save_page(int dosave, struct tab *tab)
404 if (dosave)
405 ui_read("Save to path", handle_save_page_path, tab);
406 else
407 stop_tab(tab);
410 static void
411 handle_save_page_path(const char *path, struct tab *tab)
413 if (path == NULL) {
414 stop_tab(tab);
415 return;
418 tab->path = strdup(path);
420 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
423 static void
424 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
426 struct tab *tab;
427 char *page;
428 const char *e;
429 int l;
431 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
432 if (imsg->fd != -1)
433 close(imsg->fd);
434 return;
437 if (imsg->fd == -1) {
438 stop_tab(tab);
440 e = imsg->data;
441 if (e[datalen-1] != '\0')
442 die();
443 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
444 tab->path, e);
445 if (l == -1)
446 die();
447 load_page_from_str(tab, page);
448 free(page);
449 } else {
450 tab->fd = imsg->fd;
451 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
455 static void
456 handle_imsg_buf(struct imsg *imsg, size_t datalen)
458 struct tab *tab;
459 int l;
460 char *page, buf[FMT_SCALED_STRSIZE] = {0};
462 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
463 return;
465 tab->bytes += datalen;
466 if (tab->fd == -1) {
467 if (!parser_parse(tab, imsg->data, datalen))
468 die();
469 } else {
470 write(tab->fd, imsg->data, datalen);
471 fmt_scaled(tab->bytes, buf);
472 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
473 tab->path,
474 buf);
475 if (l == -1)
476 die();
477 load_page_from_str(tab, page);
478 free(page);
481 ui_on_tab_refresh(tab);
484 static void
485 handle_imsg_eof(struct imsg *imsg, size_t datalen)
487 struct tab *tab;
488 int l;
489 char *page, buf[FMT_SCALED_STRSIZE] = {0};
491 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
492 return;
494 if (tab->fd == -1) {
495 if (!parser_free(tab))
496 die();
497 } else {
498 fmt_scaled(tab->bytes, buf);
499 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
500 tab->path,
501 buf);
502 if (l == -1)
503 die();
504 load_page_from_str(tab, page);
505 free(page);
507 close(tab->fd);
508 tab->fd = -1;
509 free(tab->path);
510 tab->path = NULL;
513 ui_on_tab_refresh(tab);
514 ui_on_tab_loaded(tab);
517 static void
518 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
520 int res;
522 if (datalen != sizeof(res))
523 die();
525 memcpy(&res, imsg->data, sizeof(res));
526 if (res == 0)
527 message("Added to bookmarks!");
528 else
529 message("Failed to add to bookmarks: %s",
530 strerror(res));
533 static void
534 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
536 int res;
538 if (datalen != sizeof(res))
539 die();
540 memcpy(&res, imsg->data, datalen);
541 if (res != 0)
542 message("Failed to save the cert for: %s",
543 strerror(res));
546 static void
547 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
549 int res;
551 if (datalen != sizeof(res))
552 die();
553 memcpy(&res, imsg->data, datalen);
554 if (!res)
555 message("Failed to update the certificate");
558 static void
559 handle_dispatch_imsg(int fd, short ev, void *d)
561 struct imsgev *iev = d;
563 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
564 err(1, "connection closed");
567 static int
568 load_about_url(struct tab *tab, const char *url)
570 tab->trust = TS_UNKNOWN;
571 parser_init(tab, gemtext_initparser);
572 return make_fs_request(tab, IMSG_GET, url);
575 static int
576 load_file_url(struct tab *tab, const char *url)
578 tab->trust = TS_UNKNOWN;
579 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
582 static int
583 load_finger_url(struct tab *tab, const char *url)
585 struct get_req req;
586 size_t len;
587 char *at;
589 memset(&req, 0, sizeof(req));
590 strlcpy(req.port, tab->uri.port, sizeof(req.port));
592 /*
593 * Sometimes the finger url have the user as path component
594 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
595 * userinfo (e.g. finger://cobradile@finger.farm).
596 */
597 if ((at = strchr(tab->uri.host, '@')) != NULL) {
598 len = at - tab->uri.host;
599 memcpy(req.req, tab->uri.host, len);
601 if (len >= sizeof(req.req))
602 die();
603 req.req[len] = '\0';
605 strlcpy(req.host, at+1, sizeof(req.host));
606 } else {
607 strlcpy(req.host, tab->uri.host, sizeof(req.host));
609 /* +1 to skip the initial `/' */
610 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
612 strlcat(req.req, "\r\n", sizeof(req.req));
614 parser_init(tab, textplain_initparser);
615 return make_request(tab, &req, PROTO_FINGER, NULL);
618 static int
619 load_gemini_url(struct tab *tab, const char *url)
621 struct get_req req;
623 memset(&req, 0, sizeof(req));
624 strlcpy(req.host, tab->uri.host, sizeof(req.host));
625 strlcpy(req.port, tab->uri.port, sizeof(req.host));
627 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
630 static inline const char *
631 gopher_skip_selector(const char *path, int *ret_type)
633 *ret_type = 0;
635 if (!strcmp(path, "/") || *path == '\0') {
636 *ret_type = '1';
637 return path;
640 if (*path != '/')
641 return path;
642 path++;
644 switch (*ret_type = *path) {
645 case '0':
646 case '1':
647 case '7':
648 break;
650 default:
651 *ret_type = 0;
652 path -= 1;
653 return path;
656 path++;
657 if (*path == '/')
658 path++;
660 return path;
663 static int
664 load_gopher_url(struct tab *tab, const char *url)
666 struct get_req req;
667 int type;
668 const char *path;
670 memset(&req, 0, sizeof(req));
671 strlcpy(req.host, tab->uri.host, sizeof(req.host));
672 strlcpy(req.port, tab->uri.port, sizeof(req.host));
674 path = gopher_skip_selector(tab->uri.path, &type);
675 switch (type) {
676 case '0':
677 parser_init(tab, textplain_initparser);
678 break;
679 case '1':
680 parser_init(tab, gophermap_initparser);
681 break;
682 case '7':
683 ui_require_input(tab, 0, PROTO_GOPHER);
684 return load_page_from_str(tab, err_pages[10]);
685 default:
686 return load_page_from_str(tab, "Unknown gopher selector");
689 strlcpy(req.req, path, sizeof(req.req));
690 if (*tab->uri.query != '\0') {
691 strlcat(req.req, "?", sizeof(req.req));
692 strlcat(req.req, tab->uri.query, sizeof(req.req));
694 strlcat(req.req, "\r\n", sizeof(req.req));
696 return make_request(tab, &req, PROTO_GOPHER, NULL);
699 static int
700 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
702 struct get_req req;
704 memset(&req, 0, sizeof(req));
705 strlcpy(req.host, p->host, sizeof(req.host));
706 strlcpy(req.port, p->port, sizeof(req.host));
708 tab->proxy = p;
710 return make_request(tab, &req, p->proto, tab->hist_cur->h);
713 static int
714 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
716 stop_tab(tab);
717 tab->id = tab_new_id();
718 req->proto = proto;
720 if (r != NULL) {
721 strlcpy(req->req, r, sizeof(req->req));
722 strlcat(req->req, "\r\n", sizeof(req->req));
725 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
727 /*
728 * So the various load_*_url can `return make_request` and
729 * do_load_url is happy.
730 */
731 return 1;
734 static int
735 make_fs_request(struct tab *tab, int type, const char *r)
737 stop_tab(tab);
738 tab->id = tab_new_id();
740 ui_send_fs(type, tab->id, r, strlen(r)+1);
742 /*
743 * So load_{about,file}_url can `return make_fs_request` and
744 * do_load_url is happy.
745 */
746 return 1;
749 void
750 gopher_send_search_req(struct tab *tab, const char *text)
752 struct get_req req;
754 start_loading_anim(tab);
756 memset(&req, 0, sizeof(req));
757 strlcpy(req.host, tab->uri.host, sizeof(req.host));
758 strlcpy(req.port, tab->uri.port, sizeof(req.host));
760 /* +2 to skip /7 */
761 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
762 if (*tab->uri.query != '\0') {
763 strlcat(req.req, "?", sizeof(req.req));
764 strlcat(req.req, tab->uri.query, sizeof(req.req));
767 strlcat(req.req, "\t", sizeof(req.req));
768 strlcat(req.req, text, sizeof(req.req));
769 strlcat(req.req, "\r\n", sizeof(req.req));
771 erase_buffer(&tab->buffer);
772 parser_init(tab, gophermap_initparser);
774 make_request(tab, &req, PROTO_GOPHER, NULL);
777 /*
778 * Effectively load the given url in the given tab. Return 1 when
779 * loading the page asynchronously, and thus when an erase_buffer can
780 * be done right after this function return, or 0 when loading the
781 * page synchronously. In this last case, erase_buffer *MUST* be
782 * called by the handling function (such as load_page_from_str).
783 */
784 static int
785 do_load_url(struct tab *tab, const char *url, const char *base)
787 struct phos_uri uri;
788 struct proto *p;
789 struct proxy *proxy;
790 char *t;
792 tab->proxy = NULL;
794 if (tab->fd != -1) {
795 close(tab->fd);
796 tab->fd = -1;
797 free(tab->path);
798 tab->path = NULL;
801 tab->trust = TS_UNKNOWN;
803 if (base == NULL)
804 memcpy(&uri, &tab->uri, sizeof(tab->uri));
805 else
806 phos_parse_absolute_uri(base, &uri);
808 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
809 if (asprintf(&t, "#error loading %s\n>%s\n",
810 url, "Can't parse the URI") == -1)
811 die();
812 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
813 load_page_from_str(tab, t);
814 free(t);
815 return 0;
818 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
819 sizeof(tab->hist_cur->h));
821 for (p = protos; p->schema != NULL; ++p) {
822 if (!strcmp(tab->uri.scheme, p->schema)) {
823 /* patch the port */
824 if (*tab->uri.port == '\0' && p->port != NULL)
825 strlcpy(tab->uri.port, p->port,
826 sizeof(tab->uri.port));
828 return p->loadfn(tab, url);
832 TAILQ_FOREACH(proxy, &proxies, proxies) {
833 if (!strcmp(tab->uri.scheme, proxy->match_proto))
834 return load_via_proxy(tab, url, proxy);
837 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
840 /*
841 * Load url in tab. If tab is marked as lazy, only prepare the url
842 * but don't load it. If tab is lazy and a url was already prepared,
843 * do load it!
844 */
845 void
846 load_url(struct tab *tab, const char *url, const char *base, int nohist)
848 int lazy;
850 lazy = tab->flags & TAB_LAZY;
852 if (lazy && tab->hist_cur != NULL) {
853 lazy = 0;
854 tab->flags &= ~TAB_LAZY;
857 /* can't have both nohist and lazy at the same time. */
858 if (nohist && lazy)
859 nohist = 0;
861 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
862 if (tab->hist_cur != NULL)
863 hist_clear_forward(&tab->hist,
864 TAILQ_NEXT(tab->hist_cur, entries));
866 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
867 event_loopbreak();
868 return;
871 strlcpy(tab->buffer.page.title, url,
872 sizeof(tab->buffer.page.title));
873 hist_push(&tab->hist, tab->hist_cur);
875 if (lazy)
876 strlcpy(tab->hist_cur->h, url,
877 sizeof(tab->hist_cur->h));
880 if (!lazy && do_load_url(tab, url, base))
881 erase_buffer(&tab->buffer);
884 void
885 load_url_in_tab(struct tab *tab, const char *url, const char *base, int nohist)
887 if (!operating) {
888 load_url(tab, url, base, nohist);
889 return;
892 autosave_hook();
894 message("Loading %s...", url);
895 start_loading_anim(tab);
896 load_url(tab, url, base, nohist);
899 int
900 load_previous_page(struct tab *tab)
902 struct hist *h;
904 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
905 return 0;
906 tab->hist_cur = h;
907 do_load_url(tab, h->h, NULL);
908 return 1;
911 int
912 load_next_page(struct tab *tab)
914 struct hist *h;
916 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
917 return 0;
918 tab->hist_cur = h;
919 do_load_url(tab, h->h, NULL);
920 return 1;
923 void
924 add_to_bookmarks(const char *str)
926 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
927 str, strlen(str)+1);
930 static pid_t
931 start_child(enum telescope_process p, const char *argv0, int fd)
933 const char *argv[4];
934 int argc = 0;
935 pid_t pid;
937 switch (pid = fork()) {
938 case -1:
939 die();
940 case 0:
941 break;
942 default:
943 close(fd);
944 return pid;
947 if (dup2(fd, 3) == -1)
948 err(1, "cannot setup imsg fd");
950 argv[argc++] = argv0;
951 switch (p) {
952 case PROC_UI:
953 errx(1, "Can't start ui process");
954 case PROC_FS:
955 argv[argc++] = "-Tf";
956 break;
957 case PROC_NET:
958 argv[argc++] = "-Tn";
959 break;
962 argv[argc++] = NULL;
963 execvp(argv0, (char *const *)argv);
964 err(1, "execvp(%s)", argv0);
967 int
968 ui_send_net(int type, uint32_t peerid, const void *data,
969 uint16_t datalen)
971 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
972 datalen);
975 int
976 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
978 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
979 datalen);
982 static void __attribute__((noreturn))
983 usage(int r)
985 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
986 getprogname());
987 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
988 exit(r);
991 int
992 main(int argc, char * const *argv)
994 struct imsgev net_ibuf, fs_ibuf;
995 int pipe2net[2], pipe2fs[2];
996 int ch, configtest = 0, fail = 0;
997 int has_url = 0;
998 int proc = -1;
999 int sessionfd;
1000 char path[PATH_MAX];
1001 const char *url = NEW_TAB_URL;
1002 const char *argv0;
1004 argv0 = argv[0];
1006 signal(SIGCHLD, SIG_IGN);
1007 signal(SIGPIPE, SIG_IGN);
1009 if (getenv("NO_COLOR") != NULL)
1010 enable_colors = 0;
1012 strlcpy(path, getenv("HOME"), sizeof(path));
1013 strlcat(path, "/.telescope/config", sizeof(path));
1015 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1016 switch (ch) {
1017 case 'C':
1018 exit(ui_print_colors());
1019 case 'c':
1020 fail = 1;
1021 strlcpy(path, optarg, sizeof(path));
1022 break;
1023 case 'n':
1024 configtest = 1;
1025 break;
1026 case 'h':
1027 usage(0);
1028 case 'T':
1029 switch (*optarg) {
1030 case 'f':
1031 proc = PROC_FS;
1032 break;
1033 case 'n':
1034 proc = PROC_NET;
1035 break;
1036 default:
1037 errx(1, "invalid process spec %c",
1038 *optarg);
1040 break;
1041 case 'v':
1042 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1043 exit(0);
1044 break;
1045 default:
1046 usage(1);
1050 argc -= optind;
1051 argv += optind;
1053 if (proc != -1) {
1054 if (argc > 0)
1055 usage(1);
1056 else if (proc == PROC_FS)
1057 return fs_main();
1058 else if (proc == PROC_NET)
1059 return net_main();
1060 else
1061 usage(1);
1064 if (argc != 0) {
1065 has_url = 1;
1066 url = argv[0];
1069 /* setup keys before reading the config */
1070 TAILQ_INIT(&global_map.m);
1071 global_map.unhandled_input = global_key_unbound;
1072 TAILQ_INIT(&minibuffer_map.m);
1074 config_init();
1075 parseconfig(path, fail);
1076 if (configtest){
1077 puts("config OK");
1078 exit(0);
1081 fs_init();
1082 if ((sessionfd = lock_session()) == -1)
1083 errx(1, "can't lock session, is another instance of "
1084 "telescope already running?");
1086 /* Start children. */
1087 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1088 err(1, "socketpair");
1089 start_child(PROC_FS, argv0, pipe2fs[1]);
1090 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1091 iev_fs = &fs_ibuf;
1092 iev_fs->handler = handle_dispatch_imsg;
1094 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1095 err(1, "socketpair");
1096 start_child(PROC_NET, argv0, pipe2net[1]);
1097 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1098 iev_net = &net_ibuf;
1099 iev_net->handler = handle_dispatch_imsg;
1101 setproctitle("ui");
1103 /* initialize tofu & load certificates */
1104 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1105 load_certs(&certs);
1107 event_init();
1109 /* Setup event handler for the autosave */
1110 autosave_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, NULL);
1128 sandbox_ui_process();
1129 operating = 1;
1130 ui_main_loop();
1131 ui_end();
1134 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1135 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1136 imsg_flush(&iev_fs->ibuf);
1137 imsg_flush(&iev_net->ibuf);
1139 close(sessionfd);
1141 return 0;