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>
20 #include <sys/wait.h>
22 #include <errno.h>
23 #include <getopt.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 {"safe", no_argument, NULL, 'S'},
41 {"version", no_argument, NULL, 'v'},
42 {NULL, 0, NULL, 0},
43 };
45 static const char *opts = "Cc:hnST:v";
47 /*
48 * Used to know when we're finished loading.
49 */
50 int operating;
52 /*
53 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
54 * anything to the filesystem or execute external programs.
55 */
56 int safe_mode;
58 static struct imsgev *iev_fs, *iev_net;
60 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
61 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
63 enum telescope_process {
64 PROC_UI,
65 PROC_FS,
66 PROC_NET,
67 };
69 #define CANNOT_FETCH 0
70 #define TOO_MUCH_REDIRECTS 1
71 #define MALFORMED_RESPONSE 2
72 #define UNKNOWN_TYPE_OR_CSET 3
73 #define UNKNOWN_PROTOCOL 4
75 /* XXX: keep in sync with normalize_code */
76 const char *err_pages[70] = {
77 [CANNOT_FETCH] = "# Couldn't load the page\n",
78 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
79 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
80 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
81 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
83 [10] = "# Input required\n",
84 [11] = "# Input required\n",
85 [40] = "# Temporary failure\n",
86 [41] = "# Server unavailable\n",
87 [42] = "# CGI error\n",
88 [43] = "# Proxy error\n",
89 [44] = "# Slow down\n",
90 [50] = "# Permanent failure\n",
91 [51] = "# Not found\n",
92 [52] = "# Gone\n",
93 [53] = "# Proxy request refused\n",
94 [59] = "# Bad request\n",
95 [60] = "# Client certificate required\n",
96 [61] = "# Certificate not authorised\n",
97 [62] = "# Certificate not valid\n"
98 };
100 static void die(void) __attribute__((__noreturn__));
101 static struct tab *tab_by_id(uint32_t);
102 static void handle_imsg_err(struct imsg *, size_t);
103 static void handle_imsg_check_cert(struct imsg *, size_t);
104 static void handle_check_cert_user_choice(int, struct tab *);
105 static void handle_maybe_save_new_cert(int, struct tab *);
106 static void handle_imsg_got_code(struct imsg *, size_t);
107 static void handle_imsg_got_meta(struct imsg *, size_t);
108 static void handle_maybe_save_page(int, struct tab *);
109 static void handle_save_page_path(const char *, struct tab *);
110 static void handle_imsg_file_opened(struct imsg *, size_t);
111 static void handle_imsg_buf(struct imsg *, size_t);
112 static void handle_imsg_eof(struct imsg *, size_t);
113 static void handle_imsg_bookmark_ok(struct imsg *, size_t);
114 static void handle_imsg_save_cert_ok(struct imsg *, size_t);
115 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
116 static void handle_dispatch_imsg(int, short, void *);
117 static int load_about_url(struct tab *, const char *);
118 static int load_file_url(struct tab *, const char *);
119 static int load_finger_url(struct tab *, const char *);
120 static int load_gemini_url(struct tab *, const char *);
121 static int load_gopher_url(struct tab *, const char *);
122 static int load_via_proxy(struct tab *, const char *,
123 struct proxy *);
124 static int make_request(struct tab *, struct get_req *, int,
125 const char *);
126 static int make_fs_request(struct tab *, int, const char *);
127 static int do_load_url(struct tab *, const char *, const char *);
128 static pid_t start_child(enum telescope_process, const char *, int);
130 static struct proto {
131 const char *schema;
132 const char *port;
133 int (*loadfn)(struct tab *, const char *);
134 } protos[] = {
135 {"about", NULL, load_about_url},
136 {"file", NULL, load_file_url},
137 {"finger", "79", load_finger_url},
138 {"gemini", "1965", load_gemini_url},
139 {"gopher", "70", load_gopher_url},
140 {NULL, NULL, NULL},
141 };
143 static imsg_handlerfn *handlers[] = {
144 [IMSG_ERR] = handle_imsg_err,
145 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
146 [IMSG_GOT_CODE] = handle_imsg_got_code,
147 [IMSG_GOT_META] = handle_imsg_got_meta,
148 [IMSG_BUF] = handle_imsg_buf,
149 [IMSG_EOF] = handle_imsg_eof,
150 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
151 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
152 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
153 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
154 };
156 static struct ohash certs;
158 static void __attribute__((__noreturn__))
159 die(void)
161 abort(); /* TODO */
164 static struct tab *
165 tab_by_id(uint32_t id)
167 struct tab *t;
169 TAILQ_FOREACH(t, &tabshead, tabs) {
170 if (t->id == id)
171 return t;
174 return NULL;
177 static void
178 handle_imsg_err(struct imsg *imsg, size_t datalen)
180 struct tab *tab;
181 char *page;
183 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
184 return;
186 page = imsg->data;
187 page[datalen-1] = '\0';
189 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
190 tab->hist_cur->h, page) == -1)
191 die();
192 load_page_from_str(tab, page);
193 free(page);
196 static void
197 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
199 const char *hash, *host, *port;
200 int tofu_res;
201 struct tofu_entry *e;
202 struct tab *tab;
204 hash = imsg->data;
205 if (hash[datalen-1] != '\0')
206 abort();
208 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
209 return;
211 if (tab->proxy != NULL) {
212 host = tab->proxy->host;
213 port = tab->proxy->port;
214 } else {
215 host = tab->uri.host;
216 port = tab->uri.port;
219 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
220 /* TODO: an update in libressl/libretls changed
221 * significantly. Find a better approach at storing
222 * the certs! */
223 if (datalen > sizeof(e->hash))
224 abort();
226 tofu_res = 1; /* trust on first use */
227 if ((e = calloc(1, sizeof(*e))) == NULL)
228 abort();
229 strlcpy(e->domain, host, sizeof(e->domain));
230 if (*port != '\0' && strcmp(port, "1965")) {
231 strlcat(e->domain, ":", sizeof(e->domain));
232 strlcat(e->domain, port, sizeof(e->domain));
234 strlcpy(e->hash, hash, sizeof(e->hash));
235 tofu_add(&certs, e);
236 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
237 } else
238 tofu_res = !strcmp(hash, e->hash);
240 if (tofu_res) {
241 if (e->verified == -1)
242 tab->trust = TS_TEMP_TRUSTED;
243 else if (e->verified == 1)
244 tab->trust = TS_VERIFIED;
245 else
246 tab->trust = TS_TRUSTED;
248 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
249 &tofu_res, sizeof(tofu_res));
250 } else {
251 tab->trust = TS_UNTRUSTED;
252 load_page_from_str(tab, "# Certificate mismatch\n");
253 if ((tab->cert = strdup(hash)) == NULL)
254 die();
255 ui_yornp("Certificate mismatch. Proceed?",
256 handle_check_cert_user_choice, tab);
260 static void
261 handle_check_cert_user_choice(int accept, struct tab *tab)
263 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
264 sizeof(accept));
266 if (accept) {
267 /*
268 * trust the certificate for this session only. If
269 * the page results in a redirect while we're asking
270 * the user to save, we'll end up with an invalid
271 * tabid (one request == one tab id). It also makes
272 * sense to save it for the current session if the
273 * user accepted it.
274 */
275 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
276 tab->cert);
278 if (!safe_mode)
279 ui_yornp("Save the new certificate?",
280 handle_maybe_save_new_cert, tab);
281 else
282 message("Certificate temporarly trusted");
283 } else {
284 free(tab->cert);
285 tab->cert = NULL;
289 static void
290 handle_maybe_save_new_cert(int accept, struct tab *tab)
292 struct tofu_entry *e;
293 const char *host, *port;
295 if (tab->proxy != NULL) {
296 host = tab->proxy->host;
297 port = tab->proxy->port;
298 } else {
299 host = tab->uri.host;
300 port = tab->uri.port;
303 if (!accept)
304 goto end;
306 if ((e = calloc(1, sizeof(*e))) == NULL)
307 die();
309 strlcpy(e->domain, host, sizeof(e->domain));
310 if (*port != '\0' && strcmp(port, "1965")) {
311 strlcat(e->domain, ":", sizeof(e->domain));
312 strlcat(e->domain, port, sizeof(e->domain));
314 strlcpy(e->hash, tab->cert, sizeof(e->hash));
315 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
317 tofu_update(&certs, e);
319 tab->trust = TS_TRUSTED;
321 end:
322 free(tab->cert);
323 tab->cert = NULL;
326 static inline int
327 normalize_code(int n)
329 if (n < 20) {
330 if (n == 10 || n == 11)
331 return n;
332 return 10;
333 } else if (n < 30) {
334 return 20;
335 } else if (n < 40) {
336 if (n == 30 || n == 31)
337 return n;
338 return 30;
339 } else if (n < 50) {
340 if (n <= 44)
341 return n;
342 return 40;
343 } else if (n < 60) {
344 if (n <= 53 || n == 59)
345 return n;
346 return 50;
347 } else if (n < 70) {
348 if (n <= 62)
349 return n;
350 return 60;
351 } else
352 return MALFORMED_RESPONSE;
355 static void
356 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
358 struct tab *tab;
360 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
361 return;
363 if (sizeof(tab->code) != datalen)
364 die();
366 memcpy(&tab->code, imsg->data, sizeof(tab->code));
367 tab->code = normalize_code(tab->code);
368 if (tab->code != 30 && tab->code != 31)
369 tab->redirect_count = 0;
372 static void
373 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
375 struct tab *tab;
377 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
378 return;
380 if (sizeof(tab->meta) <= datalen)
381 die();
383 memcpy(tab->meta, imsg->data, datalen);
385 if (tab->code < 10) { /* internal errors */
386 load_page_from_str(tab, err_pages[tab->code]);
387 } else if (tab->code < 20) { /* 1x */
388 load_page_from_str(tab, err_pages[tab->code]);
389 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
390 } else if (tab->code == 20) {
391 if (setup_parser_for(tab)) {
392 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
393 } else {
394 load_page_from_str(tab,
395 err_pages[UNKNOWN_TYPE_OR_CSET]);
396 if (!safe_mode)
397 ui_yornp("Can't display page, save it?",
398 handle_maybe_save_page, tab);
400 } else if (tab->code < 40) { /* 3x */
401 tab->redirect_count++;
403 /* TODO: make customizable? */
404 if (tab->redirect_count > 5) {
405 load_page_from_str(tab,
406 err_pages[TOO_MUCH_REDIRECTS]);
407 } else
408 do_load_url(tab, tab->meta, NULL);
409 } else { /* 4x, 5x & 6x */
410 load_page_from_str(tab, err_pages[tab->code]);
414 static void
415 handle_maybe_save_page(int dosave, struct tab *tab)
417 const char *f;
418 char input[PATH_MAX];
420 if (!dosave) {
421 stop_tab(tab);
422 return;
425 if ((f = strrchr(tab->uri.path, '/')) == NULL)
426 f = "";
427 else
428 f++;
430 strlcpy(input, download_path, sizeof(input));
431 strlcat(input, f, sizeof(input));
433 ui_read("Save to path", handle_save_page_path, tab, input);
436 static void
437 handle_save_page_path(const char *path, struct tab *tab)
439 if (path == NULL) {
440 stop_tab(tab);
441 return;
444 tab->path = strdup(path);
446 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
449 static void
450 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
452 struct tab *tab;
453 char *page;
454 const char *e;
455 int l;
457 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
458 if (imsg->fd != -1)
459 close(imsg->fd);
460 return;
463 if (imsg->fd == -1) {
464 stop_tab(tab);
466 e = imsg->data;
467 if (e[datalen-1] != '\0')
468 die();
469 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
470 tab->path, e);
471 if (l == -1)
472 die();
473 load_page_from_str(tab, page);
474 free(page);
475 } else {
476 tab->fd = imsg->fd;
477 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
481 static void
482 handle_imsg_buf(struct imsg *imsg, size_t datalen)
484 struct tab *tab;
485 int l;
486 char *page, buf[FMT_SCALED_STRSIZE] = {0};
488 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
489 return;
491 tab->bytes += datalen;
492 if (tab->fd == -1) {
493 if (!parser_parse(tab, imsg->data, datalen))
494 die();
495 } else {
496 write(tab->fd, imsg->data, datalen);
497 fmt_scaled(tab->bytes, buf);
498 l = asprintf(&page, "Saving 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);
507 ui_on_tab_refresh(tab);
510 static void
511 handle_imsg_eof(struct imsg *imsg, size_t datalen)
513 struct tab *tab;
514 int l;
515 char *page, buf[FMT_SCALED_STRSIZE] = {0};
517 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
518 return;
520 if (tab->fd == -1) {
521 if (!parser_free(tab))
522 die();
523 } else {
524 fmt_scaled(tab->bytes, buf);
525 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
526 tab->path,
527 buf);
528 if (l == -1)
529 die();
530 load_page_from_str(tab, page);
531 free(page);
533 close(tab->fd);
534 tab->fd = -1;
535 tab->bytes = 0;
536 free(tab->path);
537 tab->path = NULL;
540 ui_on_tab_refresh(tab);
541 ui_on_tab_loaded(tab);
544 static void
545 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
547 int res;
549 if (datalen != sizeof(res))
550 die();
552 memcpy(&res, imsg->data, sizeof(res));
553 if (res == 0)
554 message("Added to bookmarks!");
555 else
556 message("Failed to add to bookmarks: %s",
557 strerror(res));
560 static void
561 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
563 int res;
565 if (datalen != sizeof(res))
566 die();
567 memcpy(&res, imsg->data, datalen);
568 if (res != 0)
569 message("Failed to save the cert for: %s",
570 strerror(res));
573 static void
574 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
576 int res;
578 if (datalen != sizeof(res))
579 die();
580 memcpy(&res, imsg->data, datalen);
581 if (!res)
582 message("Failed to update the certificate");
585 static void
586 handle_dispatch_imsg(int fd, short ev, void *d)
588 struct imsgev *iev = d;
590 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
591 err(1, "connection closed");
594 static int
595 load_about_url(struct tab *tab, const char *url)
597 tab->trust = TS_UNKNOWN;
598 parser_init(tab, gemtext_initparser);
599 return make_fs_request(tab, IMSG_GET, url);
602 static int
603 load_file_url(struct tab *tab, const char *url)
605 tab->trust = TS_UNKNOWN;
606 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
609 static int
610 load_finger_url(struct tab *tab, const char *url)
612 struct get_req req;
613 size_t len;
614 char *at;
616 memset(&req, 0, sizeof(req));
617 strlcpy(req.port, tab->uri.port, sizeof(req.port));
619 /*
620 * Sometimes the finger url have the user as path component
621 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
622 * userinfo (e.g. finger://cobradile@finger.farm).
623 */
624 if ((at = strchr(tab->uri.host, '@')) != NULL) {
625 len = at - tab->uri.host;
626 memcpy(req.req, tab->uri.host, len);
628 if (len >= sizeof(req.req))
629 die();
630 req.req[len] = '\0';
632 strlcpy(req.host, at+1, sizeof(req.host));
633 } else {
634 strlcpy(req.host, tab->uri.host, sizeof(req.host));
636 /* +1 to skip the initial `/' */
637 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
639 strlcat(req.req, "\r\n", sizeof(req.req));
641 parser_init(tab, textplain_initparser);
642 return make_request(tab, &req, PROTO_FINGER, NULL);
645 static int
646 load_gemini_url(struct tab *tab, const char *url)
648 struct get_req req;
650 memset(&req, 0, sizeof(req));
651 strlcpy(req.host, tab->uri.host, sizeof(req.host));
652 strlcpy(req.port, tab->uri.port, sizeof(req.host));
654 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
657 static inline const char *
658 gopher_skip_selector(const char *path, int *ret_type)
660 *ret_type = 0;
662 if (!strcmp(path, "/") || *path == '\0') {
663 *ret_type = '1';
664 return path;
667 if (*path != '/')
668 return path;
669 path++;
671 switch (*ret_type = *path) {
672 case '0':
673 case '1':
674 case '7':
675 break;
677 default:
678 *ret_type = 0;
679 path -= 1;
680 return path;
683 return ++path;
686 static int
687 load_gopher_url(struct tab *tab, const char *url)
689 struct get_req req;
690 int type;
691 const char *path;
693 memset(&req, 0, sizeof(req));
694 strlcpy(req.host, tab->uri.host, sizeof(req.host));
695 strlcpy(req.port, tab->uri.port, sizeof(req.host));
697 path = gopher_skip_selector(tab->uri.path, &type);
698 switch (type) {
699 case '0':
700 parser_init(tab, textplain_initparser);
701 break;
702 case '1':
703 parser_init(tab, gophermap_initparser);
704 break;
705 case '7':
706 ui_require_input(tab, 0, PROTO_GOPHER);
707 return load_page_from_str(tab, err_pages[10]);
708 default:
709 return load_page_from_str(tab, "Unknown gopher selector");
712 strlcpy(req.req, path, sizeof(req.req));
713 if (*tab->uri.query != '\0') {
714 strlcat(req.req, "?", sizeof(req.req));
715 strlcat(req.req, tab->uri.query, sizeof(req.req));
717 strlcat(req.req, "\r\n", sizeof(req.req));
719 return make_request(tab, &req, PROTO_GOPHER, NULL);
722 static int
723 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
725 struct get_req req;
727 memset(&req, 0, sizeof(req));
728 strlcpy(req.host, p->host, sizeof(req.host));
729 strlcpy(req.port, p->port, sizeof(req.host));
731 tab->proxy = p;
733 return make_request(tab, &req, p->proto, tab->hist_cur->h);
736 static int
737 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
739 stop_tab(tab);
740 tab->id = tab_new_id();
741 req->proto = proto;
743 if (r != NULL) {
744 strlcpy(req->req, r, sizeof(req->req));
745 strlcat(req->req, "\r\n", sizeof(req->req));
748 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
750 /*
751 * So the various load_*_url can `return make_request` and
752 * do_load_url is happy.
753 */
754 return 1;
757 static int
758 make_fs_request(struct tab *tab, int type, const char *r)
760 stop_tab(tab);
761 tab->id = tab_new_id();
763 ui_send_fs(type, tab->id, r, strlen(r)+1);
765 /*
766 * So load_{about,file}_url can `return make_fs_request` and
767 * do_load_url is happy.
768 */
769 return 1;
772 void
773 gopher_send_search_req(struct tab *tab, const char *text)
775 struct get_req req;
777 start_loading_anim(tab);
779 memset(&req, 0, sizeof(req));
780 strlcpy(req.host, tab->uri.host, sizeof(req.host));
781 strlcpy(req.port, tab->uri.port, sizeof(req.host));
783 /* +2 to skip /7 */
784 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
785 if (*tab->uri.query != '\0') {
786 strlcat(req.req, "?", sizeof(req.req));
787 strlcat(req.req, tab->uri.query, sizeof(req.req));
790 strlcat(req.req, "\t", sizeof(req.req));
791 strlcat(req.req, text, sizeof(req.req));
792 strlcat(req.req, "\r\n", sizeof(req.req));
794 erase_buffer(&tab->buffer);
795 parser_init(tab, gophermap_initparser);
797 make_request(tab, &req, PROTO_GOPHER, NULL);
800 /*
801 * Effectively load the given url in the given tab. Return 1 when
802 * loading the page asynchronously, and thus when an erase_buffer can
803 * be done right after this function return, or 0 when loading the
804 * page synchronously. In this last case, erase_buffer *MUST* be
805 * called by the handling function (such as load_page_from_str).
806 */
807 static int
808 do_load_url(struct tab *tab, const char *url, const char *base)
810 struct phos_uri uri;
811 struct proto *p;
812 struct proxy *proxy;
813 char *t;
815 tab->proxy = NULL;
817 if (tab->fd != -1) {
818 close(tab->fd);
819 tab->fd = -1;
820 free(tab->path);
821 tab->path = NULL;
824 tab->trust = TS_UNKNOWN;
826 if (base == NULL)
827 memcpy(&uri, &tab->uri, sizeof(tab->uri));
828 else
829 phos_parse_absolute_uri(base, &uri);
831 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
832 if (asprintf(&t, "#error loading %s\n>%s\n",
833 url, "Can't parse the URI") == -1)
834 die();
835 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
836 load_page_from_str(tab, t);
837 free(t);
838 return 0;
841 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
842 sizeof(tab->hist_cur->h));
844 for (p = protos; p->schema != NULL; ++p) {
845 if (!strcmp(tab->uri.scheme, p->schema)) {
846 /* patch the port */
847 if (*tab->uri.port == '\0' && p->port != NULL)
848 strlcpy(tab->uri.port, p->port,
849 sizeof(tab->uri.port));
851 return p->loadfn(tab, url);
855 TAILQ_FOREACH(proxy, &proxies, proxies) {
856 if (!strcmp(tab->uri.scheme, proxy->match_proto))
857 return load_via_proxy(tab, url, proxy);
860 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
863 /*
864 * Load url in tab. If tab is marked as lazy, only prepare the url
865 * but don't load it. If tab is lazy and a url was already prepared,
866 * do load it!
867 */
868 void
869 load_url(struct tab *tab, const char *url, const char *base, int nohist)
871 int lazy;
873 lazy = tab->flags & TAB_LAZY;
875 if (lazy && tab->hist_cur != NULL) {
876 lazy = 0;
877 tab->flags &= ~TAB_LAZY;
880 /* can't have both nohist and lazy at the same time. */
881 if (nohist && lazy)
882 nohist = 0;
884 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
885 if (tab->hist_cur != NULL)
886 hist_clear_forward(&tab->hist,
887 TAILQ_NEXT(tab->hist_cur, entries));
889 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
890 == NULL) {
891 event_loopbreak();
892 return;
895 strlcpy(tab->buffer.page.title, url,
896 sizeof(tab->buffer.page.title));
897 hist_push(&tab->hist, tab->hist_cur);
899 if (lazy)
900 strlcpy(tab->hist_cur->h, url,
901 sizeof(tab->hist_cur->h));
904 if (!lazy && do_load_url(tab, url, base))
905 erase_buffer(&tab->buffer);
908 void
909 load_url_in_tab(struct tab *tab, const char *url, const char *base, int nohist)
911 if (!operating) {
912 load_url(tab, url, base, nohist);
913 return;
916 autosave_hook();
918 message("Loading %s...", url);
919 start_loading_anim(tab);
920 load_url(tab, url, base, nohist);
923 int
924 load_previous_page(struct tab *tab)
926 struct hist *h;
928 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
929 return 0;
930 tab->hist_cur = h;
931 do_load_url(tab, h->h, NULL);
932 return 1;
935 int
936 load_next_page(struct tab *tab)
938 struct hist *h;
940 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
941 return 0;
942 tab->hist_cur = h;
943 do_load_url(tab, h->h, NULL);
944 return 1;
947 void
948 add_to_bookmarks(const char *str)
950 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
951 str, strlen(str)+1);
954 /*
955 * Given a user-entered URL, apply some heuristics to use it:
957 * - if it's a proper url use it
958 * - if it starts with a `./' or a `/' assume its a file:// url
959 * - assume it's a gemini:// url
961 * `ret' (of which len is the size) will be filled with the resulting
962 * url.
963 */
964 void
965 humanify_url(const char *raw, char *ret, size_t len)
967 struct phos_uri uri;
968 char buf[PATH_MAX];
970 if (phos_parse_absolute_uri(raw, &uri)) {
971 strlcpy(ret, raw, len);
972 return;
975 if (has_prefix(raw, "./")) {
976 strlcpy(ret, "file://", len);
977 getcwd(buf, sizeof(buf));
978 strlcat(ret, buf, len);
979 strlcat(ret, "/", len);
980 strlcat(ret, raw+2, len);
981 return;
984 if (*raw == '/') {
985 strlcpy(ret, "file://", len);
986 strlcat(ret, raw, len);
987 return;
990 strlcpy(ret, "gemini://", len);
991 strlcat(ret, raw, len);
994 static pid_t
995 start_child(enum telescope_process p, const char *argv0, int fd)
997 const char *argv[4];
998 int argc = 0;
999 pid_t pid;
1001 switch (pid = fork()) {
1002 case -1:
1003 die();
1004 case 0:
1005 break;
1006 default:
1007 close(fd);
1008 return pid;
1011 if (dup2(fd, 3) == -1)
1012 err(1, "cannot setup imsg fd");
1014 argv[argc++] = argv0;
1015 switch (p) {
1016 case PROC_UI:
1017 errx(1, "Can't start ui process");
1018 case PROC_FS:
1019 argv[argc++] = "-Tf";
1020 break;
1021 case PROC_NET:
1022 argv[argc++] = "-Tn";
1023 break;
1026 argv[argc++] = NULL;
1027 execvp(argv0, (char *const *)argv);
1028 err(1, "execvp(%s)", argv0);
1031 int
1032 ui_send_net(int type, uint32_t peerid, const void *data,
1033 uint16_t datalen)
1035 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1036 datalen);
1039 int
1040 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1042 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1043 datalen);
1046 static void __attribute__((noreturn))
1047 usage(int r)
1049 fprintf(stderr, "USAGE: %s [-hnSv] [-c config] [url]\n",
1050 getprogname());
1051 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1052 exit(r);
1055 int
1056 main(int argc, char * const *argv)
1058 struct imsgev net_ibuf, fs_ibuf;
1059 pid_t pid;
1060 int pipe2net[2], pipe2fs[2];
1061 int ch, configtest = 0, fail = 0;
1062 int has_url = 0;
1063 int proc = -1;
1064 int sessionfd;
1065 int status;
1066 char path[PATH_MAX], url[GEMINI_URL_LEN+1];
1067 const char *argv0;
1069 argv0 = argv[0];
1071 signal(SIGCHLD, SIG_IGN);
1072 signal(SIGPIPE, SIG_IGN);
1074 if (getenv("NO_COLOR") != NULL)
1075 enable_colors = 0;
1077 strlcpy(path, getenv("HOME"), sizeof(path));
1078 strlcat(path, "/.telescope/config", sizeof(path));
1080 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1081 switch (ch) {
1082 case 'C':
1083 exit(ui_print_colors());
1084 case 'c':
1085 fail = 1;
1086 strlcpy(path, optarg, sizeof(path));
1087 break;
1088 case 'n':
1089 configtest = 1;
1090 break;
1091 case 'h':
1092 usage(0);
1093 case 'S':
1094 safe_mode = 1;
1095 break;
1096 case 'T':
1097 switch (*optarg) {
1098 case 'f':
1099 proc = PROC_FS;
1100 break;
1101 case 'n':
1102 proc = PROC_NET;
1103 break;
1104 default:
1105 errx(1, "invalid process spec %c",
1106 *optarg);
1108 break;
1109 case 'v':
1110 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1111 exit(0);
1112 break;
1113 default:
1114 usage(1);
1118 argc -= optind;
1119 argv += optind;
1121 if (proc != -1) {
1122 if (argc > 0)
1123 usage(1);
1124 else if (proc == PROC_FS)
1125 return fs_main();
1126 else if (proc == PROC_NET)
1127 return net_main();
1128 else
1129 usage(1);
1132 if (argc != 0) {
1133 has_url = 1;
1134 humanify_url(argv[0], url, sizeof(url));
1137 /* setup keys before reading the config */
1138 TAILQ_INIT(&global_map.m);
1139 global_map.unhandled_input = global_key_unbound;
1140 TAILQ_INIT(&minibuffer_map.m);
1142 config_init();
1143 parseconfig(path, fail);
1144 if (configtest) {
1145 puts("config OK");
1146 exit(0);
1149 if (download_path == NULL &&
1150 (download_path = strdup("/tmp/")) == NULL)
1151 errx(1, "strdup");
1153 fs_init();
1154 if ((sessionfd = lock_session()) == -1)
1155 errx(1, "can't lock session, is another instance of "
1156 "telescope already running?");
1158 /* Start children. */
1159 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1160 err(1, "socketpair");
1161 start_child(PROC_FS, argv0, pipe2fs[1]);
1162 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1163 iev_fs = &fs_ibuf;
1164 iev_fs->handler = handle_dispatch_imsg;
1166 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1167 err(1, "socketpair");
1168 start_child(PROC_NET, argv0, pipe2net[1]);
1169 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1170 iev_net = &net_ibuf;
1171 iev_net->handler = handle_dispatch_imsg;
1173 setproctitle("ui");
1175 /* initialize tofu & load certificates */
1176 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1177 load_certs(&certs);
1179 event_init();
1181 /* Setup event handler for the autosave */
1182 autosave_init();
1184 /* Setup event handlers for pipes to fs/net */
1185 iev_fs->events = EV_READ;
1186 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1187 iev_fs->handler, iev_fs);
1188 event_add(&iev_fs->ev, NULL);
1190 iev_net->events = EV_READ;
1191 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1192 iev_net->handler, iev_net);
1193 event_add(&iev_net->ev, NULL);
1195 if (ui_init()) {
1196 load_last_session();
1197 if (has_url || TAILQ_EMPTY(&tabshead))
1198 new_tab(url, NULL, NULL);
1200 sandbox_ui_process();
1201 operating = 1;
1202 ui_main_loop();
1203 ui_end();
1206 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1207 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1208 imsg_flush(&iev_fs->ibuf);
1209 imsg_flush(&iev_net->ibuf);
1211 /* wait for children to terminate */
1212 do {
1213 pid = wait(&status);
1214 if (pid == -1) {
1215 if (errno != EINTR && errno != ECHILD)
1216 err(1, "wait");
1217 } else if (WIFSIGNALED(status))
1218 warnx("child terminated; signal %d", WTERMSIG(status));
1219 } while (pid != -1 || (pid == -1 && errno == EINTR));
1221 close(sessionfd);
1223 return 0;