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 <getopt.h>
22 #include <signal.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
28 #include "defaults.h"
29 #include "minibuffer.h"
30 #include "parser.h"
31 #include "session.h"
32 #include "telescope.h"
33 #include "ui.h"
35 static struct option longopts[] = {
36 {"colors", no_argument, NULL, 'c'},
37 {"help", no_argument, NULL, 'h'},
38 {"version", no_argument, NULL, 'v'},
39 {NULL, 0, NULL, 0},
40 };
42 static const char *opts = "Cc:hnT:v";
44 /*
45 * Used to know when we're finished loading.
46 */
47 int operating;
49 static struct imsgev *iev_fs, *iev_net;
51 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
52 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
54 enum telescope_process {
55 PROC_UI,
56 PROC_FS,
57 PROC_NET,
58 };
60 #define CANNOT_FETCH 0
61 #define TOO_MUCH_REDIRECTS 1
62 #define MALFORMED_RESPONSE 2
63 #define UNKNOWN_TYPE_OR_CSET 3
64 #define UNKNOWN_PROTOCOL 4
66 /* XXX: keep in sync with normalize_code */
67 const char *err_pages[70] = {
68 [CANNOT_FETCH] = "# Couldn't load the page\n",
69 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
70 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
71 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
72 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
74 [10] = "# Input required\n",
75 [11] = "# Input required\n",
76 [40] = "# Temporary failure\n",
77 [41] = "# Server unavailable\n",
78 [42] = "# CGI error\n",
79 [43] = "# Proxy error\n",
80 [44] = "# Slow down\n",
81 [50] = "# Permanent failure\n",
82 [51] = "# Not found\n",
83 [52] = "# Gone\n",
84 [53] = "# Proxy request refused\n",
85 [59] = "# Bad request\n",
86 [60] = "# Client certificate required\n",
87 [61] = "# Certificate not authorised\n",
88 [62] = "# Certificate not valid\n"
89 };
91 static void die(void) __attribute__((__noreturn__));
92 static struct tab *tab_by_id(uint32_t);
93 static void handle_imsg_err(struct imsg*, size_t);
94 static void handle_imsg_check_cert(struct imsg*, size_t);
95 static void handle_check_cert_user_choice(int, struct tab *);
96 static void handle_maybe_save_new_cert(int, struct tab *);
97 static void handle_imsg_got_code(struct imsg*, size_t);
98 static void handle_imsg_got_meta(struct imsg*, size_t);
99 static void handle_maybe_save_page(int, struct tab *);
100 static void handle_save_page_path(const char *, struct tab *);
101 static void handle_imsg_file_opened(struct imsg*, size_t);
102 static void handle_imsg_buf(struct imsg*, size_t);
103 static void handle_imsg_eof(struct imsg*, size_t);
104 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
105 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
106 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
107 static void handle_dispatch_imsg(int, short, void*);
108 static int load_about_url(struct tab*, const char*);
109 static int load_file_url(struct tab *, const char *);
110 static int load_finger_url(struct tab *, const char *);
111 static int load_gemini_url(struct tab*, const char*);
112 static int load_gopher_url(struct tab *, const char *);
113 static int load_via_proxy(struct tab *, const char *,
114 struct proxy *);
115 static int make_request(struct tab *, struct get_req *, int,
116 const char *);
117 static int make_fs_request(struct tab *, int, const char *);
118 static int do_load_url(struct tab*, const char *, const char *);
119 static pid_t start_child(enum telescope_process, const char *, int);
121 static struct proto {
122 const char *schema;
123 const char *port;
124 int (*loadfn)(struct tab*, const char*);
125 } protos[] = {
126 {"about", NULL, load_about_url},
127 {"file", NULL, load_file_url},
128 {"finger", "79", load_finger_url},
129 {"gemini", "1965", load_gemini_url},
130 {"gopher", "70", load_gopher_url},
131 {NULL, NULL, NULL},
132 };
134 static imsg_handlerfn *handlers[] = {
135 [IMSG_ERR] = handle_imsg_err,
136 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
137 [IMSG_GOT_CODE] = handle_imsg_got_code,
138 [IMSG_GOT_META] = handle_imsg_got_meta,
139 [IMSG_BUF] = handle_imsg_buf,
140 [IMSG_EOF] = handle_imsg_eof,
141 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
142 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
143 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
144 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
145 };
147 static struct ohash certs;
149 static void __attribute__((__noreturn__))
150 die(void)
152 abort(); /* TODO */
155 static struct tab *
156 tab_by_id(uint32_t id)
158 struct tab *t;
160 TAILQ_FOREACH(t, &tabshead, tabs) {
161 if (t->id == id)
162 return t;
165 return NULL;
168 static void
169 handle_imsg_err(struct imsg *imsg, size_t datalen)
171 struct tab *tab;
172 char *page;
174 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
175 return;
177 page = imsg->data;
178 page[datalen-1] = '\0';
180 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
181 tab->hist_cur->h, page) == -1)
182 die();
183 load_page_from_str(tab, page);
184 free(page);
187 static void
188 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
190 const char *hash, *host, *port;
191 int tofu_res;
192 struct tofu_entry *e;
193 struct tab *tab;
195 hash = imsg->data;
196 if (hash[datalen-1] != '\0')
197 abort();
199 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
200 return;
202 if (tab->proxy != NULL) {
203 host = tab->proxy->host;
204 port = tab->proxy->port;
205 } else {
206 host = tab->uri.host;
207 port = tab->uri.port;
210 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
211 /* TODO: an update in libressl/libretls changed
212 * significantly. Find a better approach at storing
213 * the certs! */
214 if (datalen > sizeof(e->hash))
215 abort();
217 tofu_res = 1; /* trust on first use */
218 if ((e = calloc(1, sizeof(*e))) == NULL)
219 abort();
220 strlcpy(e->domain, host, sizeof(e->domain));
221 if (*port != '\0' && strcmp(port, "1965")) {
222 strlcat(e->domain, ":", sizeof(e->domain));
223 strlcat(e->domain, port, sizeof(e->domain));
225 strlcpy(e->hash, hash, sizeof(e->hash));
226 tofu_add(&certs, e);
227 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
228 } else
229 tofu_res = !strcmp(hash, e->hash);
231 if (tofu_res) {
232 if (e->verified == -1)
233 tab->trust = TS_TEMP_TRUSTED;
234 else if (e->verified == 1)
235 tab->trust = TS_VERIFIED;
236 else
237 tab->trust = TS_TRUSTED;
239 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
240 &tofu_res, sizeof(tofu_res));
241 } else {
242 tab->trust = TS_UNTRUSTED;
243 load_page_from_str(tab, "# Certificate mismatch\n");
244 if ((tab->cert = strdup(hash)) == NULL)
245 die();
246 ui_yornp("Certificate mismatch. Proceed?",
247 handle_check_cert_user_choice, tab);
251 static void
252 handle_check_cert_user_choice(int accept, struct tab *tab)
254 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
255 sizeof(accept));
257 if (accept) {
258 /*
259 * trust the certificate for this session only. If
260 * the page results in a redirect while we're asking
261 * the user to save, we'll end up with an invalid
262 * tabid (one request == one tab id) and crash. It
263 * also makes sense to save it for the current session
264 * if the user accepted it.
265 */
266 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
268 ui_yornp("Save the new certificate?",
269 handle_maybe_save_new_cert, tab);
270 } else {
271 free(tab->cert);
272 tab->cert = NULL;
276 static void
277 handle_maybe_save_new_cert(int accept, struct tab *tab)
279 struct tofu_entry *e;
280 const char *host, *port;
282 if (tab->proxy != NULL) {
283 host = tab->proxy->host;
284 port = tab->proxy->port;
285 } else {
286 host = tab->uri.host;
287 port = tab->uri.port;
290 if (!accept)
291 goto end;
293 if ((e = calloc(1, sizeof(*e))) == NULL)
294 die();
296 strlcpy(e->domain, host, sizeof(e->domain));
297 if (*port != '\0' && strcmp(port, "1965")) {
298 strlcat(e->domain, ":", sizeof(e->domain));
299 strlcat(e->domain, port, sizeof(e->domain));
301 strlcpy(e->hash, tab->cert, sizeof(e->hash));
302 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
304 tofu_update(&certs, e);
306 tab->trust = TS_TRUSTED;
308 end:
309 free(tab->cert);
310 tab->cert = NULL;
313 static inline int
314 normalize_code(int n)
316 if (n < 20) {
317 if (n == 10 || n == 11)
318 return n;
319 return 10;
320 } else if (n < 30) {
321 return 20;
322 } else if (n < 40) {
323 if (n == 30 || n == 31)
324 return n;
325 return 30;
326 } else if (n < 50) {
327 if (n <= 44)
328 return n;
329 return 40;
330 } else if (n < 60) {
331 if (n <= 53 || n == 59)
332 return n;
333 return 50;
334 } else if (n < 70) {
335 if (n <= 62)
336 return n;
337 return 60;
338 } else
339 return MALFORMED_RESPONSE;
342 static void
343 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
345 struct tab *tab;
347 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
348 return;
350 if (sizeof(tab->code) != datalen)
351 die();
353 memcpy(&tab->code, imsg->data, sizeof(tab->code));
354 tab->code = normalize_code(tab->code);
355 if (tab->code != 30 && tab->code != 31)
356 tab->redirect_count = 0;
359 static void
360 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
362 struct tab *tab;
364 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
365 return;
367 if (sizeof(tab->meta) <= datalen)
368 die();
370 memcpy(tab->meta, imsg->data, datalen);
372 if (tab->code < 10) { /* internal errors */
373 load_page_from_str(tab, err_pages[tab->code]);
374 } else if (tab->code < 20) { /* 1x */
375 load_page_from_str(tab, err_pages[tab->code]);
376 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
377 } else if (tab->code == 20) {
378 if (setup_parser_for(tab)) {
379 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
380 } else {
381 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
382 ui_yornp("Can't display page, wanna save?",
383 handle_maybe_save_page, tab);
385 } else if (tab->code < 40) { /* 3x */
386 tab->redirect_count++;
388 /* TODO: make customizable? */
389 if (tab->redirect_count > 5) {
390 load_page_from_str(tab,
391 err_pages[TOO_MUCH_REDIRECTS]);
392 } else
393 do_load_url(tab, tab->meta, NULL);
394 } else { /* 4x, 5x & 6x */
395 load_page_from_str(tab, err_pages[tab->code]);
399 static void
400 handle_maybe_save_page(int dosave, struct tab *tab)
402 if (dosave)
403 ui_read("Save to path", handle_save_page_path, tab);
404 else
405 stop_tab(tab);
408 static void
409 handle_save_page_path(const char *path, struct tab *tab)
411 if (path == NULL) {
412 stop_tab(tab);
413 return;
416 tab->path = strdup(path);
418 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
421 static void
422 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
424 struct tab *tab;
425 char *page;
426 const char *e;
427 int l;
429 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
430 if (imsg->fd != -1)
431 close(imsg->fd);
432 return;
435 if (imsg->fd == -1) {
436 stop_tab(tab);
438 e = imsg->data;
439 if (e[datalen-1] != '\0')
440 die();
441 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
442 tab->path, e);
443 if (l == -1)
444 die();
445 load_page_from_str(tab, page);
446 free(page);
447 } else {
448 tab->fd = imsg->fd;
449 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
453 static void
454 handle_imsg_buf(struct imsg *imsg, size_t datalen)
456 struct tab *tab;
457 int l;
458 char *page, buf[FMT_SCALED_STRSIZE] = {0};
460 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
461 return;
463 tab->bytes += datalen;
464 if (tab->fd == -1) {
465 if (!parser_parse(tab, imsg->data, datalen))
466 die();
467 } else {
468 write(tab->fd, imsg->data, datalen);
469 fmt_scaled(tab->bytes, buf);
470 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
471 tab->path,
472 buf);
473 if (l == -1)
474 die();
475 load_page_from_str(tab, page);
476 free(page);
479 ui_on_tab_refresh(tab);
482 static void
483 handle_imsg_eof(struct imsg *imsg, size_t datalen)
485 struct tab *tab;
486 int l;
487 char *page, buf[FMT_SCALED_STRSIZE] = {0};
489 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
490 return;
492 if (tab->fd == -1) {
493 if (!parser_free(tab))
494 die();
495 } else {
496 fmt_scaled(tab->bytes, buf);
497 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
498 tab->path,
499 buf);
500 if (l == -1)
501 die();
502 load_page_from_str(tab, page);
503 free(page);
505 close(tab->fd);
506 tab->fd = -1;
507 free(tab->path);
508 tab->path = NULL;
511 ui_on_tab_refresh(tab);
512 ui_on_tab_loaded(tab);
515 static void
516 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
518 int res;
520 if (datalen != sizeof(res))
521 die();
523 memcpy(&res, imsg->data, sizeof(res));
524 if (res == 0)
525 message("Added to bookmarks!");
526 else
527 message("Failed to add to bookmarks: %s",
528 strerror(res));
531 static void
532 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
534 int res;
536 if (datalen != sizeof(res))
537 die();
538 memcpy(&res, imsg->data, datalen);
539 if (res != 0)
540 message("Failed to save the cert for: %s",
541 strerror(res));
544 static void
545 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
547 int res;
549 if (datalen != sizeof(res))
550 die();
551 memcpy(&res, imsg->data, datalen);
552 if (!res)
553 message("Failed to update the certificate");
556 static void
557 handle_dispatch_imsg(int fd, short ev, void *d)
559 struct imsgev *iev = d;
561 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
562 err(1, "connection closed");
565 static int
566 load_about_url(struct tab *tab, const char *url)
568 tab->trust = TS_UNKNOWN;
569 parser_init(tab, gemtext_initparser);
570 return make_fs_request(tab, IMSG_GET, url);
573 static int
574 load_file_url(struct tab *tab, const char *url)
576 tab->trust = TS_UNKNOWN;
577 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
580 static int
581 load_finger_url(struct tab *tab, const char *url)
583 struct get_req req;
584 size_t len;
585 char *at;
587 memset(&req, 0, sizeof(req));
588 strlcpy(req.port, tab->uri.port, sizeof(req.port));
590 /*
591 * Sometimes the finger url have the user as path component
592 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
593 * userinfo (e.g. finger://cobradile@finger.farm).
594 */
595 if ((at = strchr(tab->uri.host, '@')) != NULL) {
596 len = at - tab->uri.host;
597 memcpy(req.req, tab->uri.host, len);
599 if (len >= sizeof(req.req))
600 die();
601 req.req[len] = '\0';
603 strlcpy(req.host, at+1, sizeof(req.host));
604 } else {
605 strlcpy(req.host, tab->uri.host, sizeof(req.host));
607 /* +1 to skip the initial `/' */
608 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
610 strlcat(req.req, "\r\n", sizeof(req.req));
612 parser_init(tab, textplain_initparser);
613 return make_request(tab, &req, PROTO_FINGER, NULL);
616 static int
617 load_gemini_url(struct tab *tab, const char *url)
619 struct get_req req;
621 memset(&req, 0, sizeof(req));
622 strlcpy(req.host, tab->uri.host, sizeof(req.host));
623 strlcpy(req.port, tab->uri.port, sizeof(req.host));
625 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
628 static inline const char *
629 gopher_skip_selector(const char *path, int *ret_type)
631 *ret_type = 0;
633 if (!strcmp(path, "/") || *path == '\0') {
634 *ret_type = '1';
635 return path;
638 if (*path != '/')
639 return path;
640 path++;
642 switch (*ret_type = *path) {
643 case '0':
644 case '1':
645 case '7':
646 break;
648 default:
649 *ret_type = 0;
650 path -= 1;
651 return path;
654 path++;
655 if (*path == '/')
656 path++;
658 return path;
661 static int
662 load_gopher_url(struct tab *tab, const char *url)
664 struct get_req req;
665 int type;
666 const char *path;
668 memset(&req, 0, sizeof(req));
669 strlcpy(req.host, tab->uri.host, sizeof(req.host));
670 strlcpy(req.port, tab->uri.port, sizeof(req.host));
672 path = gopher_skip_selector(tab->uri.path, &type);
673 switch (type) {
674 case '0':
675 parser_init(tab, textplain_initparser);
676 break;
677 case '1':
678 parser_init(tab, gophermap_initparser);
679 break;
680 case '7':
681 ui_require_input(tab, 0, PROTO_GOPHER);
682 return load_page_from_str(tab, err_pages[10]);
683 default:
684 return load_page_from_str(tab, "Unknown gopher selector");
687 strlcpy(req.req, path, sizeof(req.req));
688 if (*tab->uri.query != '\0') {
689 strlcat(req.req, "?", sizeof(req.req));
690 strlcat(req.req, tab->uri.query, sizeof(req.req));
692 strlcat(req.req, "\r\n", sizeof(req.req));
694 return make_request(tab, &req, PROTO_GOPHER, NULL);
697 static int
698 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
700 struct get_req req;
702 memset(&req, 0, sizeof(req));
703 strlcpy(req.host, p->host, sizeof(req.host));
704 strlcpy(req.port, p->port, sizeof(req.host));
706 tab->proxy = p;
708 return make_request(tab, &req, p->proto, tab->hist_cur->h);
711 static int
712 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
714 stop_tab(tab);
715 tab->id = tab_new_id();
716 req->proto = proto;
718 if (r != NULL) {
719 strlcpy(req->req, r, sizeof(req->req));
720 strlcat(req->req, "\r\n", sizeof(req->req));
723 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
725 /*
726 * So the various load_*_url can `return make_request` and
727 * do_load_url is happy.
728 */
729 return 1;
732 static int
733 make_fs_request(struct tab *tab, int type, const char *r)
735 stop_tab(tab);
736 tab->id = tab_new_id();
738 ui_send_fs(type, tab->id, r, strlen(r)+1);
740 /*
741 * So load_{about,file}_url can `return make_fs_request` and
742 * do_load_url is happy.
743 */
744 return 1;
747 void
748 gopher_send_search_req(struct tab *tab, const char *text)
750 struct get_req req;
752 start_loading_anim(tab);
754 memset(&req, 0, sizeof(req));
755 strlcpy(req.host, tab->uri.host, sizeof(req.host));
756 strlcpy(req.port, tab->uri.port, sizeof(req.host));
758 /* +2 to skip /7 */
759 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
760 if (*tab->uri.query != '\0') {
761 strlcat(req.req, "?", sizeof(req.req));
762 strlcat(req.req, tab->uri.query, sizeof(req.req));
765 strlcat(req.req, "\t", sizeof(req.req));
766 strlcat(req.req, text, sizeof(req.req));
767 strlcat(req.req, "\r\n", sizeof(req.req));
769 erase_buffer(&tab->buffer);
770 parser_init(tab, gophermap_initparser);
772 make_request(tab, &req, PROTO_GOPHER, NULL);
775 /*
776 * Effectively load the given url in the given tab. Return 1 when
777 * loading the page asynchronously, and thus when an erase_buffer can
778 * be done right after this function return, or 0 when loading the
779 * page synchronously. In this last case, erase_buffer *MUST* be
780 * called by the handling function (such as load_page_from_str).
781 */
782 static int
783 do_load_url(struct tab *tab, const char *url, const char *base)
785 struct phos_uri uri;
786 struct proto *p;
787 struct proxy *proxy;
788 char *t;
790 tab->proxy = NULL;
792 if (tab->fd != -1) {
793 close(tab->fd);
794 tab->fd = -1;
795 free(tab->path);
796 tab->path = NULL;
799 tab->trust = TS_UNKNOWN;
801 if (base == NULL)
802 memcpy(&uri, &tab->uri, sizeof(tab->uri));
803 else
804 phos_parse_absolute_uri(base, &uri);
806 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
807 if (asprintf(&t, "#error loading %s\n>%s\n",
808 url, "Can't parse the URI") == -1)
809 die();
810 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
811 load_page_from_str(tab, t);
812 free(t);
813 return 0;
816 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
817 sizeof(tab->hist_cur->h));
819 for (p = protos; p->schema != NULL; ++p) {
820 if (!strcmp(tab->uri.scheme, p->schema)) {
821 /* patch the port */
822 if (*tab->uri.port == '\0' && p->port != NULL)
823 strlcpy(tab->uri.port, p->port,
824 sizeof(tab->uri.port));
826 return p->loadfn(tab, url);
830 TAILQ_FOREACH(proxy, &proxies, proxies) {
831 if (!strcmp(tab->uri.scheme, proxy->match_proto))
832 return load_via_proxy(tab, url, proxy);
835 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
838 /*
839 * Load url in tab. If tab is marked as lazy, only prepare the url
840 * but don't load it. If tab is lazy and a url was already prepared,
841 * do load it!
842 */
843 void
844 load_url(struct tab *tab, const char *url, const char *base, int nohist)
846 int lazy;
848 lazy = tab->flags & TAB_LAZY;
850 if (lazy && tab->hist_cur != NULL) {
851 lazy = 0;
852 tab->flags &= ~TAB_LAZY;
855 /* can't have both nohist and lazy at the same time. */
856 if (nohist && lazy)
857 nohist = 0;
859 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
860 if (tab->hist_cur != NULL)
861 hist_clear_forward(&tab->hist,
862 TAILQ_NEXT(tab->hist_cur, entries));
864 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
865 event_loopbreak();
866 return;
869 strlcpy(tab->buffer.page.title, url,
870 sizeof(tab->buffer.page.title));
871 hist_push(&tab->hist, tab->hist_cur);
873 if (lazy)
874 strlcpy(tab->hist_cur->h, url,
875 sizeof(tab->hist_cur->h));
878 if (!lazy && do_load_url(tab, url, base))
879 erase_buffer(&tab->buffer);
882 void
883 load_url_in_tab(struct tab *tab, const char *url, const char *base, int nohist)
885 if (!operating) {
886 load_url(tab, url, base, nohist);
887 return;
890 autosave_hook();
892 message("Loading %s...", url);
893 start_loading_anim(tab);
894 load_url(tab, url, base, nohist);
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 void
922 add_to_bookmarks(const char *str)
924 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
925 str, strlen(str)+1);
928 static pid_t
929 start_child(enum telescope_process p, const char *argv0, int fd)
931 const char *argv[4];
932 int argc = 0;
933 pid_t pid;
935 switch (pid = fork()) {
936 case -1:
937 die();
938 case 0:
939 break;
940 default:
941 close(fd);
942 return pid;
945 if (dup2(fd, 3) == -1)
946 err(1, "cannot setup imsg fd");
948 argv[argc++] = argv0;
949 switch (p) {
950 case PROC_UI:
951 errx(1, "Can't start ui process");
952 case PROC_FS:
953 argv[argc++] = "-Tf";
954 break;
955 case PROC_NET:
956 argv[argc++] = "-Tn";
957 break;
960 argv[argc++] = NULL;
961 execvp(argv0, (char *const *)argv);
962 err(1, "execvp(%s)", argv0);
965 int
966 ui_send_net(int type, uint32_t peerid, const void *data,
967 uint16_t datalen)
969 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
970 datalen);
973 int
974 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
976 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
977 datalen);
980 static void __attribute__((noreturn))
981 usage(int r)
983 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
984 getprogname());
985 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
986 exit(r);
989 int
990 main(int argc, char * const *argv)
992 struct imsgev net_ibuf, fs_ibuf;
993 int pipe2net[2], pipe2fs[2];
994 int ch, configtest = 0, fail = 0;
995 int has_url = 0;
996 int proc = -1;
997 int sessionfd;
998 char path[PATH_MAX];
999 const char *url = NEW_TAB_URL;
1000 const char *argv0;
1002 argv0 = argv[0];
1004 signal(SIGCHLD, SIG_IGN);
1005 signal(SIGPIPE, SIG_IGN);
1007 if (getenv("NO_COLOR") != NULL)
1008 enable_colors = 0;
1010 strlcpy(path, getenv("HOME"), sizeof(path));
1011 strlcat(path, "/.telescope/config", sizeof(path));
1013 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1014 switch (ch) {
1015 case 'C':
1016 exit(ui_print_colors());
1017 case 'c':
1018 fail = 1;
1019 strlcpy(path, optarg, sizeof(path));
1020 break;
1021 case 'n':
1022 configtest = 1;
1023 break;
1024 case 'h':
1025 usage(0);
1026 case 'T':
1027 switch (*optarg) {
1028 case 'f':
1029 proc = PROC_FS;
1030 break;
1031 case 'n':
1032 proc = PROC_NET;
1033 break;
1034 default:
1035 errx(1, "invalid process spec %c",
1036 *optarg);
1038 break;
1039 case 'v':
1040 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1041 exit(0);
1042 break;
1043 default:
1044 usage(1);
1048 argc -= optind;
1049 argv += optind;
1051 if (proc != -1) {
1052 if (argc > 0)
1053 usage(1);
1054 else if (proc == PROC_FS)
1055 return fs_main();
1056 else if (proc == PROC_NET)
1057 return net_main();
1058 else
1059 usage(1);
1062 if (argc != 0) {
1063 has_url = 1;
1064 url = argv[0];
1067 /* setup keys before reading the config */
1068 TAILQ_INIT(&global_map.m);
1069 global_map.unhandled_input = global_key_unbound;
1070 TAILQ_INIT(&minibuffer_map.m);
1072 config_init();
1073 parseconfig(path, fail);
1074 if (configtest){
1075 puts("config OK");
1076 exit(0);
1079 fs_init();
1080 if ((sessionfd = lock_session()) == -1)
1081 errx(1, "can't lock session, is another instance of "
1082 "telescope already running?");
1084 /* Start children. */
1085 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1086 err(1, "socketpair");
1087 start_child(PROC_FS, argv0, pipe2fs[1]);
1088 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1089 iev_fs = &fs_ibuf;
1090 iev_fs->handler = handle_dispatch_imsg;
1092 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1093 err(1, "socketpair");
1094 start_child(PROC_NET, argv0, pipe2net[1]);
1095 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1096 iev_net = &net_ibuf;
1097 iev_net->handler = handle_dispatch_imsg;
1099 setproctitle("ui");
1101 /* initialize tofu & load certificates */
1102 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1103 load_certs(&certs);
1105 event_init();
1107 /* Setup event handler for the autosave */
1108 autosave_init();
1110 /* Setup event handlers for pipes to fs/net */
1111 iev_fs->events = EV_READ;
1112 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1113 iev_fs->handler, iev_fs);
1114 event_add(&iev_fs->ev, NULL);
1116 iev_net->events = EV_READ;
1117 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1118 iev_net->handler, iev_net);
1119 event_add(&iev_net->ev, NULL);
1121 if (ui_init()) {
1122 load_last_session();
1123 if (has_url || TAILQ_EMPTY(&tabshead))
1124 new_tab(url, NULL, NULL);
1126 sandbox_ui_process();
1127 operating = 1;
1128 ui_main_loop();
1129 ui_end();
1132 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1133 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1134 imsg_flush(&iev_fs->ibuf);
1135 imsg_flush(&iev_net->ibuf);
1137 close(sessionfd);
1139 return 0;