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 "fs.h"
32 #include "minibuffer.h"
33 #include "parser.h"
34 #include "session.h"
35 #include "telescope.h"
36 #include "ui.h"
38 static struct option longopts[] = {
39 {"colors", no_argument, NULL, 'c'},
40 {"help", no_argument, NULL, 'h'},
41 {"safe", no_argument, NULL, 'S'},
42 {"version", no_argument, NULL, 'v'},
43 {NULL, 0, NULL, 0},
44 };
46 static const char *opts = "Cc:hnST:v";
48 /*
49 * Used to know when we're finished loading.
50 */
51 int operating;
53 /*
54 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
55 * anything to the filesystem or execute external programs.
56 */
57 int safe_mode;
59 static struct imsgev *iev_fs, *iev_net;
61 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
62 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
64 enum telescope_process {
65 PROC_UI,
66 PROC_FS,
67 PROC_NET,
68 };
70 #define CANNOT_FETCH 0
71 #define TOO_MUCH_REDIRECTS 1
72 #define MALFORMED_RESPONSE 2
73 #define UNKNOWN_TYPE_OR_CSET 3
74 #define UNKNOWN_PROTOCOL 4
76 /* XXX: keep in sync with normalize_code */
77 const char *err_pages[70] = {
78 [CANNOT_FETCH] = "# Couldn't load the page\n",
79 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
80 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
81 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
82 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
84 [10] = "# Input required\n",
85 [11] = "# Input required\n",
86 [40] = "# Temporary failure\n",
87 [41] = "# Server unavailable\n",
88 [42] = "# CGI error\n",
89 [43] = "# Proxy error\n",
90 [44] = "# Slow down\n",
91 [50] = "# Permanent failure\n",
92 [51] = "# Not found\n",
93 [52] = "# Gone\n",
94 [53] = "# Proxy request refused\n",
95 [59] = "# Bad request\n",
96 [60] = "# Client certificate required\n",
97 [61] = "# Certificate not authorised\n",
98 [62] = "# Certificate not valid\n"
99 };
101 static void die(void) __attribute__((__noreturn__));
102 static struct tab *tab_by_id(uint32_t);
103 static void handle_imsg_err(struct imsg *, size_t);
104 static void handle_imsg_check_cert(struct imsg *, size_t);
105 static void handle_check_cert_user_choice(int, struct tab *);
106 static void handle_maybe_save_new_cert(int, struct tab *);
107 static void handle_imsg_got_code(struct imsg *, size_t);
108 static void handle_imsg_got_meta(struct imsg *, size_t);
109 static void handle_maybe_save_page(int, struct tab *);
110 static void handle_save_page_path(const char *, struct tab *);
111 static void handle_imsg_file_opened(struct imsg *, size_t);
112 static void handle_imsg_buf(struct imsg *, size_t);
113 static void handle_imsg_eof(struct imsg *, size_t);
114 static void handle_imsg_bookmark_ok(struct imsg *, size_t);
115 static void handle_imsg_save_cert_ok(struct imsg *, size_t);
116 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
117 static void handle_dispatch_imsg(int, short, void *);
118 static int load_about_url(struct tab *, const char *);
119 static int load_file_url(struct tab *, const char *);
120 static int load_finger_url(struct tab *, const char *);
121 static int load_gemini_url(struct tab *, const char *);
122 static int load_gopher_url(struct tab *, const char *);
123 static int load_via_proxy(struct tab *, const char *,
124 struct proxy *);
125 static int make_request(struct tab *, struct get_req *, int,
126 const char *);
127 static int make_fs_request(struct tab *, int, const char *);
128 static int do_load_url(struct tab *, const char *, const char *);
129 static pid_t start_child(enum telescope_process, const char *, int);
131 static struct proto {
132 const char *schema;
133 const char *port;
134 int (*loadfn)(struct tab *, const char *);
135 } protos[] = {
136 {"about", NULL, load_about_url},
137 {"file", NULL, load_file_url},
138 {"finger", "79", load_finger_url},
139 {"gemini", "1965", load_gemini_url},
140 {"gopher", "70", load_gopher_url},
141 {NULL, NULL, NULL},
142 };
144 static imsg_handlerfn *handlers[] = {
145 [IMSG_ERR] = handle_imsg_err,
146 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
147 [IMSG_GOT_CODE] = handle_imsg_got_code,
148 [IMSG_GOT_META] = handle_imsg_got_meta,
149 [IMSG_BUF] = handle_imsg_buf,
150 [IMSG_EOF] = handle_imsg_eof,
151 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
152 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
153 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
154 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
155 };
157 static struct ohash certs;
159 static void __attribute__((__noreturn__))
160 die(void)
162 abort(); /* TODO */
165 static struct tab *
166 tab_by_id(uint32_t id)
168 struct tab *t;
170 TAILQ_FOREACH(t, &tabshead, tabs) {
171 if (t->id == id)
172 return t;
175 return NULL;
178 static void
179 handle_imsg_err(struct imsg *imsg, size_t datalen)
181 struct tab *tab;
182 char *page;
184 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
185 return;
187 page = imsg->data;
188 page[datalen-1] = '\0';
190 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
191 tab->hist_cur->h, page) == -1)
192 die();
193 load_page_from_str(tab, page);
194 free(page);
197 static void
198 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
200 const char *hash, *host, *port;
201 int tofu_res;
202 struct tofu_entry *e;
203 struct tab *tab;
205 hash = imsg->data;
206 if (hash[datalen-1] != '\0')
207 abort();
209 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
210 return;
212 if (tab->proxy != NULL) {
213 host = tab->proxy->host;
214 port = tab->proxy->port;
215 } else {
216 host = tab->uri.host;
217 port = tab->uri.port;
220 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
221 /* TODO: an update in libressl/libretls changed
222 * significantly. Find a better approach at storing
223 * the certs! */
224 if (datalen > sizeof(e->hash))
225 abort();
227 tofu_res = 1; /* trust on first use */
228 if ((e = calloc(1, sizeof(*e))) == NULL)
229 abort();
230 strlcpy(e->domain, host, sizeof(e->domain));
231 if (*port != '\0' && strcmp(port, "1965")) {
232 strlcat(e->domain, ":", sizeof(e->domain));
233 strlcat(e->domain, port, sizeof(e->domain));
235 strlcpy(e->hash, hash, sizeof(e->hash));
236 tofu_add(&certs, e);
237 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
238 } else
239 tofu_res = !strcmp(hash, e->hash);
241 if (tofu_res) {
242 if (e->verified == -1)
243 tab->trust = TS_TEMP_TRUSTED;
244 else if (e->verified == 1)
245 tab->trust = TS_VERIFIED;
246 else
247 tab->trust = TS_TRUSTED;
249 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
250 &tofu_res, sizeof(tofu_res));
251 } else {
252 tab->trust = TS_UNTRUSTED;
253 load_page_from_str(tab, "# Certificate mismatch\n");
254 if ((tab->cert = strdup(hash)) == NULL)
255 die();
256 ui_yornp("Certificate mismatch. Proceed?",
257 handle_check_cert_user_choice, tab);
261 static void
262 handle_check_cert_user_choice(int accept, struct tab *tab)
264 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
265 sizeof(accept));
267 if (accept) {
268 /*
269 * trust the certificate for this session only. If
270 * the page results in a redirect while we're asking
271 * the user to save, we'll end up with an invalid
272 * tabid (one request == one tab id). It also makes
273 * sense to save it for the current session if the
274 * user accepted it.
275 */
276 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
277 tab->cert);
279 if (!safe_mode)
280 ui_yornp("Save the new certificate?",
281 handle_maybe_save_new_cert, tab);
282 else
283 message("Certificate temporarly trusted");
284 } else {
285 free(tab->cert);
286 tab->cert = NULL;
290 static void
291 handle_maybe_save_new_cert(int accept, struct tab *tab)
293 struct tofu_entry *e;
294 const char *host, *port;
296 if (tab->proxy != NULL) {
297 host = tab->proxy->host;
298 port = tab->proxy->port;
299 } else {
300 host = tab->uri.host;
301 port = tab->uri.port;
304 if (!accept)
305 goto end;
307 if ((e = calloc(1, sizeof(*e))) == NULL)
308 die();
310 strlcpy(e->domain, host, sizeof(e->domain));
311 if (*port != '\0' && strcmp(port, "1965")) {
312 strlcat(e->domain, ":", sizeof(e->domain));
313 strlcat(e->domain, port, sizeof(e->domain));
315 strlcpy(e->hash, tab->cert, sizeof(e->hash));
316 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
318 tofu_update(&certs, e);
320 tab->trust = TS_TRUSTED;
322 end:
323 free(tab->cert);
324 tab->cert = NULL;
327 static inline int
328 normalize_code(int n)
330 if (n < 20) {
331 if (n == 10 || n == 11)
332 return n;
333 return 10;
334 } else if (n < 30) {
335 return 20;
336 } else if (n < 40) {
337 if (n == 30 || n == 31)
338 return n;
339 return 30;
340 } else if (n < 50) {
341 if (n <= 44)
342 return n;
343 return 40;
344 } else if (n < 60) {
345 if (n <= 53 || n == 59)
346 return n;
347 return 50;
348 } else if (n < 70) {
349 if (n <= 62)
350 return n;
351 return 60;
352 } else
353 return MALFORMED_RESPONSE;
356 static void
357 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
359 struct tab *tab;
361 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
362 return;
364 if (sizeof(tab->code) != datalen)
365 die();
367 memcpy(&tab->code, imsg->data, sizeof(tab->code));
368 tab->code = normalize_code(tab->code);
369 if (tab->code != 30 && tab->code != 31)
370 tab->redirect_count = 0;
373 static void
374 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
376 struct tab *tab;
378 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
379 return;
381 if (sizeof(tab->meta) <= datalen)
382 die();
384 memcpy(tab->meta, imsg->data, datalen);
386 if (tab->code < 10) { /* internal errors */
387 load_page_from_str(tab, err_pages[tab->code]);
388 } else if (tab->code < 20) { /* 1x */
389 load_page_from_str(tab, err_pages[tab->code]);
390 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
391 } else if (tab->code == 20) {
392 if (setup_parser_for(tab)) {
393 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
394 } else {
395 load_page_from_str(tab,
396 err_pages[UNKNOWN_TYPE_OR_CSET]);
397 if (!safe_mode)
398 ui_yornp("Can't display page, save it?",
399 handle_maybe_save_page, tab);
401 } else if (tab->code < 40) { /* 3x */
402 tab->redirect_count++;
404 /* TODO: make customizable? */
405 if (tab->redirect_count > 5) {
406 load_page_from_str(tab,
407 err_pages[TOO_MUCH_REDIRECTS]);
408 } else
409 do_load_url(tab, tab->meta, NULL);
410 } else { /* 4x, 5x & 6x */
411 load_page_from_str(tab, err_pages[tab->code]);
415 static void
416 handle_maybe_save_page(int dosave, struct tab *tab)
418 const char *f;
419 char input[PATH_MAX];
421 if (!dosave) {
422 stop_tab(tab);
423 return;
426 if ((f = strrchr(tab->uri.path, '/')) == NULL)
427 f = "";
428 else
429 f++;
431 strlcpy(input, download_path, sizeof(input));
432 strlcat(input, f, sizeof(input));
434 ui_read("Save to path", handle_save_page_path, tab, input);
437 static void
438 handle_save_page_path(const char *path, struct tab *tab)
440 if (path == NULL) {
441 stop_tab(tab);
442 return;
445 tab->path = strdup(path);
447 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
450 static void
451 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
453 struct tab *tab;
454 char *page;
455 const char *e;
456 int l;
458 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
459 if (imsg->fd != -1)
460 close(imsg->fd);
461 return;
464 if (imsg->fd == -1) {
465 stop_tab(tab);
467 e = imsg->data;
468 if (e[datalen-1] != '\0')
469 die();
470 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
471 tab->path, e);
472 if (l == -1)
473 die();
474 load_page_from_str(tab, page);
475 free(page);
476 } else {
477 tab->fd = imsg->fd;
478 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
482 static void
483 handle_imsg_buf(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 tab->bytes += datalen;
493 if (tab->fd == -1) {
494 if (!parser_parse(tab, imsg->data, datalen))
495 die();
496 } else {
497 write(tab->fd, imsg->data, datalen);
498 fmt_scaled(tab->bytes, buf);
499 l = asprintf(&page, "Saving 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);
508 ui_on_tab_refresh(tab);
511 static void
512 handle_imsg_eof(struct imsg *imsg, size_t datalen)
514 struct tab *tab;
515 int l;
516 char *page, buf[FMT_SCALED_STRSIZE] = {0};
518 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
519 return;
521 if (tab->fd == -1) {
522 if (!parser_free(tab))
523 die();
524 } else {
525 fmt_scaled(tab->bytes, buf);
526 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
527 tab->path,
528 buf);
529 if (l == -1)
530 die();
531 load_page_from_str(tab, page);
532 free(page);
534 close(tab->fd);
535 tab->fd = -1;
536 tab->bytes = 0;
537 free(tab->path);
538 tab->path = NULL;
541 ui_on_tab_refresh(tab);
542 ui_on_tab_loaded(tab);
545 static void
546 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
548 int res;
550 if (datalen != sizeof(res))
551 die();
553 memcpy(&res, imsg->data, sizeof(res));
554 if (res == 0)
555 message("Added to bookmarks!");
556 else
557 message("Failed to add to bookmarks: %s",
558 strerror(res));
561 static void
562 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
564 int res;
566 if (datalen != sizeof(res))
567 die();
568 memcpy(&res, imsg->data, datalen);
569 if (res != 0)
570 message("Failed to save the cert for: %s",
571 strerror(res));
574 static void
575 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
577 int res;
579 if (datalen != sizeof(res))
580 die();
581 memcpy(&res, imsg->data, datalen);
582 if (!res)
583 message("Failed to update the certificate");
586 static void
587 handle_dispatch_imsg(int fd, short ev, void *d)
589 struct imsgev *iev = d;
591 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
592 err(1, "connection closed");
595 static int
596 load_about_url(struct tab *tab, const char *url)
598 tab->trust = TS_UNKNOWN;
599 parser_init(tab, gemtext_initparser);
600 return make_fs_request(tab, IMSG_GET, url);
603 static int
604 load_file_url(struct tab *tab, const char *url)
606 tab->trust = TS_UNKNOWN;
607 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
610 static int
611 load_finger_url(struct tab *tab, const char *url)
613 struct get_req req;
614 size_t len;
615 char *at;
617 memset(&req, 0, sizeof(req));
618 strlcpy(req.port, tab->uri.port, sizeof(req.port));
620 /*
621 * Sometimes the finger url have the user as path component
622 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
623 * userinfo (e.g. finger://cobradile@finger.farm).
624 */
625 if ((at = strchr(tab->uri.host, '@')) != NULL) {
626 len = at - tab->uri.host;
627 memcpy(req.req, tab->uri.host, len);
629 if (len >= sizeof(req.req))
630 die();
631 req.req[len] = '\0';
633 strlcpy(req.host, at+1, sizeof(req.host));
634 } else {
635 strlcpy(req.host, tab->uri.host, sizeof(req.host));
637 /* +1 to skip the initial `/' */
638 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
640 strlcat(req.req, "\r\n", sizeof(req.req));
642 parser_init(tab, textplain_initparser);
643 return make_request(tab, &req, PROTO_FINGER, NULL);
646 static int
647 load_gemini_url(struct tab *tab, const char *url)
649 struct get_req req;
651 memset(&req, 0, sizeof(req));
652 strlcpy(req.host, tab->uri.host, sizeof(req.host));
653 strlcpy(req.port, tab->uri.port, sizeof(req.host));
655 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
658 static inline const char *
659 gopher_skip_selector(const char *path, int *ret_type)
661 *ret_type = 0;
663 if (!strcmp(path, "/") || *path == '\0') {
664 *ret_type = '1';
665 return path;
668 if (*path != '/')
669 return path;
670 path++;
672 switch (*ret_type = *path) {
673 case '0':
674 case '1':
675 case '7':
676 break;
678 default:
679 *ret_type = 0;
680 path -= 1;
681 return path;
684 return ++path;
687 static int
688 load_gopher_url(struct tab *tab, const char *url)
690 struct get_req req;
691 int type;
692 const char *path;
694 memset(&req, 0, sizeof(req));
695 strlcpy(req.host, tab->uri.host, sizeof(req.host));
696 strlcpy(req.port, tab->uri.port, sizeof(req.host));
698 path = gopher_skip_selector(tab->uri.path, &type);
699 switch (type) {
700 case '0':
701 parser_init(tab, textplain_initparser);
702 break;
703 case '1':
704 parser_init(tab, gophermap_initparser);
705 break;
706 case '7':
707 ui_require_input(tab, 0, PROTO_GOPHER);
708 return load_page_from_str(tab, err_pages[10]);
709 default:
710 return load_page_from_str(tab, "Unknown gopher selector");
713 strlcpy(req.req, path, sizeof(req.req));
714 if (*tab->uri.query != '\0') {
715 strlcat(req.req, "?", sizeof(req.req));
716 strlcat(req.req, tab->uri.query, sizeof(req.req));
718 strlcat(req.req, "\r\n", sizeof(req.req));
720 return make_request(tab, &req, PROTO_GOPHER, NULL);
723 static int
724 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
726 struct get_req req;
728 memset(&req, 0, sizeof(req));
729 strlcpy(req.host, p->host, sizeof(req.host));
730 strlcpy(req.port, p->port, sizeof(req.host));
732 tab->proxy = p;
734 return make_request(tab, &req, p->proto, tab->hist_cur->h);
737 static int
738 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
740 stop_tab(tab);
741 tab->id = tab_new_id();
742 req->proto = proto;
744 if (r != NULL) {
745 strlcpy(req->req, r, sizeof(req->req));
746 strlcat(req->req, "\r\n", sizeof(req->req));
749 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
751 /*
752 * So the various load_*_url can `return make_request` and
753 * do_load_url is happy.
754 */
755 return 1;
758 static int
759 make_fs_request(struct tab *tab, int type, const char *r)
761 stop_tab(tab);
762 tab->id = tab_new_id();
764 ui_send_fs(type, tab->id, r, strlen(r)+1);
766 /*
767 * So load_{about,file}_url can `return make_fs_request` and
768 * do_load_url is happy.
769 */
770 return 1;
773 void
774 gopher_send_search_req(struct tab *tab, const char *text)
776 struct get_req req;
778 start_loading_anim(tab);
780 memset(&req, 0, sizeof(req));
781 strlcpy(req.host, tab->uri.host, sizeof(req.host));
782 strlcpy(req.port, tab->uri.port, sizeof(req.host));
784 /* +2 to skip /7 */
785 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
786 if (*tab->uri.query != '\0') {
787 strlcat(req.req, "?", sizeof(req.req));
788 strlcat(req.req, tab->uri.query, sizeof(req.req));
791 strlcat(req.req, "\t", sizeof(req.req));
792 strlcat(req.req, text, sizeof(req.req));
793 strlcat(req.req, "\r\n", sizeof(req.req));
795 erase_buffer(&tab->buffer);
796 parser_init(tab, gophermap_initparser);
798 make_request(tab, &req, PROTO_GOPHER, NULL);
801 /*
802 * Effectively load the given url in the given tab. Return 1 when
803 * loading the page asynchronously, and thus when an erase_buffer can
804 * be done right after this function return, or 0 when loading the
805 * page synchronously. In this last case, erase_buffer *MUST* be
806 * called by the handling function (such as load_page_from_str).
807 */
808 static int
809 do_load_url(struct tab *tab, const char *url, const char *base)
811 struct phos_uri uri;
812 struct proto *p;
813 struct proxy *proxy;
814 char *t;
816 tab->proxy = NULL;
818 if (tab->fd != -1) {
819 close(tab->fd);
820 tab->fd = -1;
821 free(tab->path);
822 tab->path = NULL;
825 tab->trust = TS_UNKNOWN;
827 if (base == NULL)
828 memcpy(&uri, &tab->uri, sizeof(tab->uri));
829 else
830 phos_parse_absolute_uri(base, &uri);
832 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
833 if (asprintf(&t, "#error loading %s\n>%s\n",
834 url, "Can't parse the URI") == -1)
835 die();
836 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
837 load_page_from_str(tab, t);
838 free(t);
839 return 0;
842 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
843 sizeof(tab->hist_cur->h));
845 for (p = protos; p->schema != NULL; ++p) {
846 if (!strcmp(tab->uri.scheme, p->schema)) {
847 /* patch the port */
848 if (*tab->uri.port == '\0' && p->port != NULL)
849 strlcpy(tab->uri.port, p->port,
850 sizeof(tab->uri.port));
852 return p->loadfn(tab, url);
856 TAILQ_FOREACH(proxy, &proxies, proxies) {
857 if (!strcmp(tab->uri.scheme, proxy->match_proto))
858 return load_via_proxy(tab, url, proxy);
861 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
864 /*
865 * Load url in tab. If tab is marked as lazy, only prepare the url
866 * but don't load it. If tab is lazy and a url was already prepared,
867 * do load it!
868 */
869 void
870 load_url(struct tab *tab, const char *url, const char *base, int nohist)
872 int lazy;
874 lazy = tab->flags & TAB_LAZY;
876 if (lazy && tab->hist_cur != NULL) {
877 lazy = 0;
878 tab->flags &= ~TAB_LAZY;
881 /* can't have both nohist and lazy at the same time. */
882 if (nohist && lazy)
883 nohist = 0;
885 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
886 if (tab->hist_cur != NULL)
887 hist_clear_forward(&tab->hist,
888 TAILQ_NEXT(tab->hist_cur, entries));
890 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
891 == NULL) {
892 event_loopbreak();
893 return;
896 strlcpy(tab->buffer.page.title, url,
897 sizeof(tab->buffer.page.title));
898 hist_push(&tab->hist, tab->hist_cur);
900 if (lazy)
901 strlcpy(tab->hist_cur->h, url,
902 sizeof(tab->hist_cur->h));
905 if (!lazy && do_load_url(tab, url, base))
906 erase_buffer(&tab->buffer);
909 void
910 load_url_in_tab(struct tab *tab, const char *url, const char *base, int nohist)
912 if (!operating) {
913 load_url(tab, url, base, nohist);
914 return;
917 autosave_hook();
919 message("Loading %s...", url);
920 start_loading_anim(tab);
921 load_url(tab, url, base, nohist);
924 int
925 load_previous_page(struct tab *tab)
927 struct hist *h;
929 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
930 return 0;
931 tab->hist_cur = h;
932 do_load_url(tab, h->h, NULL);
933 return 1;
936 int
937 load_next_page(struct tab *tab)
939 struct hist *h;
941 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
942 return 0;
943 tab->hist_cur = h;
944 do_load_url(tab, h->h, NULL);
945 return 1;
948 void
949 add_to_bookmarks(const char *str)
951 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
952 str, strlen(str)+1);
955 /*
956 * Given a user-entered URL, apply some heuristics to use it:
958 * - if it's a proper url use it
959 * - if it starts with a `./' or a `/' assume its a file:// url
960 * - assume it's a gemini:// url
962 * `ret' (of which len is the size) will be filled with the resulting
963 * url.
964 */
965 void
966 humanify_url(const char *raw, char *ret, size_t len)
968 struct phos_uri uri;
969 char buf[PATH_MAX];
971 if (phos_parse_absolute_uri(raw, &uri)) {
972 strlcpy(ret, raw, len);
973 return;
976 if (has_prefix(raw, "./")) {
977 strlcpy(ret, "file://", len);
978 getcwd(buf, sizeof(buf));
979 strlcat(ret, buf, len);
980 strlcat(ret, "/", len);
981 strlcat(ret, raw+2, len);
982 return;
985 if (*raw == '/') {
986 strlcpy(ret, "file://", len);
987 strlcat(ret, raw, len);
988 return;
991 strlcpy(ret, "gemini://", len);
992 strlcat(ret, raw, len);
995 static pid_t
996 start_child(enum telescope_process p, const char *argv0, int fd)
998 const char *argv[5];
999 int argc = 0;
1000 pid_t pid;
1002 switch (pid = fork()) {
1003 case -1:
1004 die();
1005 case 0:
1006 break;
1007 default:
1008 close(fd);
1009 return pid;
1012 if (dup2(fd, 3) == -1)
1013 err(1, "cannot setup imsg fd");
1015 argv[argc++] = argv0;
1016 switch (p) {
1017 case PROC_UI:
1018 errx(1, "Can't start ui process");
1019 case PROC_FS:
1020 argv[argc++] = "-Tf";
1021 break;
1022 case PROC_NET:
1023 argv[argc++] = "-Tn";
1024 break;
1027 if (safe_mode)
1028 argv[argc++] = "-S";
1030 argv[argc++] = NULL;
1031 execvp(argv0, (char *const *)argv);
1032 err(1, "execvp(%s)", argv0);
1035 int
1036 ui_send_net(int type, uint32_t peerid, const void *data,
1037 uint16_t datalen)
1039 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1040 datalen);
1043 int
1044 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1046 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1047 datalen);
1050 static void __attribute__((noreturn))
1051 usage(int r)
1053 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1054 getprogname());
1055 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1056 exit(r);
1059 int
1060 main(int argc, char * const *argv)
1062 struct imsgev net_ibuf, fs_ibuf;
1063 pid_t pid;
1064 int pipe2net[2], pipe2fs[2];
1065 int ch, configtest = 0, fail = 0;
1066 int has_url = 0;
1067 int proc = -1;
1068 int sessionfd = -1;
1069 int status;
1070 char url[GEMINI_URL_LEN+1];
1071 const char *argv0;
1073 argv0 = argv[0];
1075 signal(SIGCHLD, SIG_IGN);
1076 signal(SIGPIPE, SIG_IGN);
1078 if (getenv("NO_COLOR") != NULL)
1079 enable_colors = 0;
1081 fs_init();
1083 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1084 switch (ch) {
1085 case 'C':
1086 exit(ui_print_colors());
1087 case 'c':
1088 fail = 1;
1089 strlcpy(config_path, optarg, sizeof(config_path));
1090 break;
1091 case 'n':
1092 configtest = 1;
1093 break;
1094 case 'h':
1095 usage(0);
1096 case 'S':
1097 safe_mode = 1;
1098 break;
1099 case 'T':
1100 switch (*optarg) {
1101 case 'f':
1102 proc = PROC_FS;
1103 break;
1104 case 'n':
1105 proc = PROC_NET;
1106 break;
1107 default:
1108 errx(1, "invalid process spec %c",
1109 *optarg);
1111 break;
1112 case 'v':
1113 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1114 exit(0);
1115 break;
1116 default:
1117 usage(1);
1121 argc -= optind;
1122 argv += optind;
1124 if (proc != -1) {
1125 if (argc > 0)
1126 usage(1);
1127 else if (proc == PROC_FS)
1128 return fs_main();
1129 else if (proc == PROC_NET)
1130 return net_main();
1131 else
1132 usage(1);
1135 if (argc != 0) {
1136 has_url = 1;
1137 humanify_url(argv[0], url, sizeof(url));
1140 /* setup keys before reading the config */
1141 TAILQ_INIT(&global_map.m);
1142 global_map.unhandled_input = global_key_unbound;
1143 TAILQ_INIT(&minibuffer_map.m);
1145 config_init();
1146 parseconfig(config_path, fail);
1147 if (configtest) {
1148 puts("config OK");
1149 exit(0);
1152 if (download_path == NULL &&
1153 (download_path = strdup("/tmp/")) == NULL)
1154 errx(1, "strdup");
1156 if (!safe_mode && (sessionfd = lock_session()) == -1)
1157 errx(1, "can't lock session, is another instance of "
1158 "telescope already running?");
1160 /* Start children. */
1161 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1162 err(1, "socketpair");
1163 start_child(PROC_FS, argv0, pipe2fs[1]);
1164 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1165 iev_fs = &fs_ibuf;
1166 iev_fs->handler = handle_dispatch_imsg;
1168 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1169 err(1, "socketpair");
1170 start_child(PROC_NET, argv0, pipe2net[1]);
1171 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1172 iev_net = &net_ibuf;
1173 iev_net->handler = handle_dispatch_imsg;
1175 setproctitle("ui");
1177 /* initialize tofu & load certificates */
1178 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1179 load_certs(&certs);
1181 event_init();
1183 /* Setup event handler for the autosave */
1184 autosave_init();
1186 /* Setup event handlers for pipes to fs/net */
1187 iev_fs->events = EV_READ;
1188 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1189 iev_fs->handler, iev_fs);
1190 event_add(&iev_fs->ev, NULL);
1192 iev_net->events = EV_READ;
1193 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1194 iev_net->handler, iev_net);
1195 event_add(&iev_net->ev, NULL);
1197 if (ui_init()) {
1198 load_last_session();
1199 if (has_url || TAILQ_EMPTY(&tabshead))
1200 new_tab(url, NULL, NULL);
1202 sandbox_ui_process();
1203 operating = 1;
1204 ui_main_loop();
1205 ui_end();
1208 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1209 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1210 imsg_flush(&iev_fs->ibuf);
1211 imsg_flush(&iev_net->ibuf);
1213 /* wait for children to terminate */
1214 do {
1215 pid = wait(&status);
1216 if (pid == -1) {
1217 if (errno != EINTR && errno != ECHILD)
1218 err(1, "wait");
1219 } else if (WIFSIGNALED(status))
1220 warnx("child terminated; signal %d", WTERMSIG(status));
1221 } while (pid != -1 || (pid == -1 && errno == EINTR));
1223 if (!safe_mode && close(sessionfd) == -1)
1224 err(1, "close(sessionfd = %d)", sessionfd);
1226 return 0;