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/un.h>
21 #include <sys/wait.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <getopt.h>
26 #include <limits.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
33 #include "control.h"
34 #include "defaults.h"
35 #include "fs.h"
36 #include "mcache.h"
37 #include "minibuffer.h"
38 #include "parser.h"
39 #include "session.h"
40 #include "telescope.h"
41 #include "ui.h"
42 #include "utils.h"
44 static const struct option longopts[] = {
45 {"colors", no_argument, NULL, 'C'},
46 {"colours", no_argument, NULL, 'C'},
47 {"help", no_argument, NULL, 'h'},
48 {"safe", no_argument, NULL, 'S'},
49 {"version", no_argument, NULL, 'v'},
50 {NULL, 0, NULL, 0},
51 };
53 static const char *opts = "Cc:hnST:v";
55 static int has_url;
56 static char url[GEMINI_URL_LEN];
58 /*
59 * Used to know when we're finished loading.
60 */
61 int operating;
63 /*
64 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
65 * anything to the filesystem or execute external programs.
66 */
67 int safe_mode;
69 static struct imsgev *iev_net;
71 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
72 struct tabshead ktabshead = TAILQ_HEAD_INITIALIZER(ktabshead);
73 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
75 enum telescope_process {
76 PROC_UI,
77 PROC_NET,
78 };
80 #define CANNOT_FETCH 0
81 #define TOO_MUCH_REDIRECTS 1
82 #define MALFORMED_RESPONSE 2
83 #define UNKNOWN_TYPE_OR_CSET 3
84 #define UNKNOWN_PROTOCOL 4
86 /* XXX: keep in sync with normalize_code */
87 const char *err_pages[70] = {
88 [CANNOT_FETCH] = "# Couldn't load the page\n",
89 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
90 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
91 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
92 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
94 [10] = "# Input required\n",
95 [11] = "# Input required\n",
96 [40] = "# Temporary failure\n",
97 [41] = "# Server unavailable\n",
98 [42] = "# CGI error\n",
99 [43] = "# Proxy error\n",
100 [44] = "# Slow down\n",
101 [50] = "# Permanent failure\n",
102 [51] = "# Not found\n",
103 [52] = "# Gone\n",
104 [53] = "# Proxy request refused\n",
105 [59] = "# Bad request\n",
106 [60] = "# Client certificate required\n",
107 [61] = "# Certificate not authorised\n",
108 [62] = "# Certificate not valid\n"
109 };
111 static void die(void) __attribute__((__noreturn__));
112 static struct tab *tab_by_id(uint32_t);
113 static void handle_imsg_err(struct imsg *, size_t);
114 static void handle_imsg_check_cert(struct imsg *, size_t);
115 static void handle_check_cert_user_choice(int, struct tab *);
116 static void handle_maybe_save_new_cert(int, struct tab *);
117 static void handle_imsg_got_code(struct imsg *, size_t);
118 static void handle_imsg_got_meta(struct imsg *, size_t);
119 static void handle_maybe_save_page(int, struct tab *);
120 static void handle_save_page_path(const char *, struct tab *);
121 static void handle_imsg_buf(struct imsg *, size_t);
122 static void handle_imsg_eof(struct imsg *, size_t);
123 static void handle_dispatch_imsg(int, short, void *);
124 static int load_about_url(struct tab *, const char *);
125 static int load_file_url(struct tab *, const char *);
126 static int load_finger_url(struct tab *, const char *);
127 static int load_gemini_url(struct tab *, const char *);
128 static int load_gopher_url(struct tab *, const char *);
129 static int load_via_proxy(struct tab *, const char *,
130 struct proxy *);
131 static int make_request(struct tab *, struct get_req *, int,
132 const char *);
133 static int do_load_url(struct tab *, const char *, const char *, int);
134 static pid_t start_child(enum telescope_process, const char *, int);
135 static void send_url(const char *);
137 static const struct proto {
138 const char *schema;
139 const char *port;
140 int (*loadfn)(struct tab *, const char *);
141 } protos[] = {
142 {"about", NULL, load_about_url},
143 {"file", NULL, load_file_url},
144 {"finger", "79", load_finger_url},
145 {"gemini", "1965", load_gemini_url},
146 {"gopher", "70", load_gopher_url},
147 {NULL, NULL, NULL},
148 };
150 static imsg_handlerfn *handlers[] = {
151 [IMSG_ERR] = handle_imsg_err,
152 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
153 [IMSG_GOT_CODE] = handle_imsg_got_code,
154 [IMSG_GOT_META] = handle_imsg_got_meta,
155 [IMSG_BUF] = handle_imsg_buf,
156 [IMSG_EOF] = handle_imsg_eof,
157 };
159 static struct ohash certs;
161 static void __attribute__((__noreturn__))
162 die(void)
164 abort(); /* TODO */
167 static struct tab *
168 tab_by_id(uint32_t id)
170 struct tab *t;
172 TAILQ_FOREACH(t, &tabshead, tabs) {
173 if (t->id == id)
174 return t;
177 return NULL;
180 static void
181 handle_imsg_err(struct imsg *imsg, size_t datalen)
183 struct tab *tab;
184 char *page;
186 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
187 return;
189 page = imsg->data;
190 page[datalen-1] = '\0';
192 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
193 tab->hist_cur->h, page) == -1)
194 die();
195 load_page_from_str(tab, page);
196 free(page);
199 static void
200 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
202 const char *hash, *host, *port;
203 int tofu_res;
204 struct tofu_entry *e;
205 struct tab *tab;
207 hash = imsg->data;
208 if (hash[datalen-1] != '\0')
209 abort();
211 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
212 return;
214 if (tab->proxy != NULL) {
215 host = tab->proxy->host;
216 port = tab->proxy->port;
217 } else {
218 host = tab->uri.host;
219 port = tab->uri.port;
222 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
223 /* TODO: an update in libressl/libretls changed
224 * significantly. Find a better approach at storing
225 * the certs! */
226 if (datalen > sizeof(e->hash))
227 abort();
229 tofu_res = 1; /* trust on first use */
230 if ((e = calloc(1, sizeof(*e))) == NULL)
231 abort();
232 strlcpy(e->domain, host, sizeof(e->domain));
233 if (*port != '\0' && strcmp(port, "1965")) {
234 strlcat(e->domain, ":", sizeof(e->domain));
235 strlcat(e->domain, port, sizeof(e->domain));
237 strlcpy(e->hash, hash, sizeof(e->hash));
238 tofu_save(&certs, e);
239 } else
240 tofu_res = !strcmp(hash, e->hash);
242 if (tofu_res) {
243 if (e->verified == -1)
244 tab->trust = TS_TEMP_TRUSTED;
245 else if (e->verified == 1)
246 tab->trust = TS_VERIFIED;
247 else
248 tab->trust = TS_TRUSTED;
250 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
251 &tofu_res, sizeof(tofu_res));
252 } else {
253 tab->trust = TS_UNTRUSTED;
254 load_page_from_str(tab, "# Certificate mismatch\n");
255 if ((tab->cert = strdup(hash)) == NULL)
256 die();
257 ui_yornp("Certificate mismatch. Proceed?",
258 handle_check_cert_user_choice, tab);
262 static void
263 handle_check_cert_user_choice(int accept, struct tab *tab)
265 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
266 sizeof(accept));
268 if (accept) {
269 /*
270 * trust the certificate for this session only. If
271 * the page results in a redirect while we're asking
272 * the user to save, we'll end up with an invalid
273 * tabid (one request == one tab id). It also makes
274 * sense to save it for the current session if the
275 * user accepted it.
276 */
277 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
278 tab->cert);
280 if (!safe_mode)
281 ui_yornp("Save the new certificate?",
282 handle_maybe_save_new_cert, tab);
283 else
284 message("Certificate temporarly trusted");
285 } else {
286 free(tab->cert);
287 tab->cert = NULL;
291 static void
292 handle_maybe_save_new_cert(int accept, struct tab *tab)
294 struct tofu_entry *e;
295 const char *host, *port;
297 if (tab->proxy != NULL) {
298 host = tab->proxy->host;
299 port = tab->proxy->port;
300 } else {
301 host = tab->uri.host;
302 port = tab->uri.port;
305 if (!accept)
306 goto end;
308 if ((e = calloc(1, sizeof(*e))) == NULL)
309 die();
311 strlcpy(e->domain, host, sizeof(e->domain));
312 if (*port != '\0' && strcmp(port, "1965")) {
313 strlcat(e->domain, ":", sizeof(e->domain));
314 strlcat(e->domain, port, sizeof(e->domain));
316 strlcpy(e->hash, tab->cert, sizeof(e->hash));
318 tofu_update_persist(&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;
377 char buf[128];
379 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
380 return;
382 if (sizeof(tab->meta) <= datalen)
383 die();
385 memcpy(tab->meta, imsg->data, datalen);
387 if (tab->code < 10) { /* internal errors */
388 load_page_from_str(tab, err_pages[tab->code]);
389 } else if (tab->code < 20) { /* 1x */
390 free(tab->last_input_url);
391 tab->last_input_url = strdup(tab->hist_cur->h);
392 if (tab->last_input_url == NULL)
393 die();
395 load_page_from_str(tab, err_pages[tab->code]);
396 ui_require_input(tab, tab->code == 11, ir_select_gemini);
397 } else if (tab->code == 20) {
398 history_add(tab->hist_cur->h);
399 if (setup_parser_for(tab)) {
400 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
401 } else if (safe_mode) {
402 load_page_from_str(tab,
403 err_pages[UNKNOWN_TYPE_OR_CSET]);
404 } else {
405 struct hist *h;
407 if ((h = hist_pop(&tab->hist)) != NULL)
408 tab->hist_cur = h;
409 snprintf(buf, sizeof(buf),
410 "Can't display \"%s\", save it?", tab->meta);
411 ui_yornp(buf, handle_maybe_save_page, tab);
413 } else if (tab->code < 40) { /* 3x */
414 tab->redirect_count++;
416 /* TODO: make customizable? */
417 if (tab->redirect_count > 5) {
418 load_page_from_str(tab,
419 err_pages[TOO_MUCH_REDIRECTS]);
420 } else
421 do_load_url(tab, tab->meta, NULL, LU_MODE_NOCACHE);
422 } else { /* 4x, 5x & 6x */
423 load_page_from_str(tab, err_pages[tab->code]);
427 static void
428 handle_maybe_save_page(int dosave, struct tab *tab)
430 const char *f;
431 char input[PATH_MAX];
433 /* XXX: this print a message that is confusing */
434 ui_on_tab_loaded(tab);
436 if (!dosave) {
437 stop_tab(tab);
438 return;
441 if ((f = strrchr(tab->uri.path, '/')) == NULL)
442 f = "";
443 else
444 f++;
446 strlcpy(input, download_path, sizeof(input));
447 strlcat(input, f, sizeof(input));
449 ui_read("Save to path", handle_save_page_path, tab, input);
452 static void
453 handle_save_page_path(const char *path, struct tab *tab)
455 struct download *d;
456 int fd;
458 if (path == NULL) {
459 stop_tab(tab);
460 return;
463 if ((fd = open(path, O_WRONLY|O_TRUNC|O_CREAT, 0644)) == -1) {
464 message("Can't open file %s: %s", path, strerror(errno));
465 stop_tab(tab);
466 return;
469 ui_show_downloads_pane();
470 d = enqueue_download(tab->id, path);
471 d->fd = fd;
472 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
474 /*
475 * Change this tab id, the old one is associated with the
476 * download now.
477 */
478 tab->id = tab_new_id();
481 static void
482 handle_imsg_buf(struct imsg *imsg, size_t datalen)
484 struct tab *tab = NULL;
485 struct download *d = NULL;
487 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
488 (d = download_by_id(imsg->hdr.peerid)) == NULL)
489 return;
491 if (tab != NULL) {
492 if (!parser_parse(tab, imsg->data, datalen))
493 die();
494 ui_on_tab_refresh(tab);
495 } else {
496 d->bytes += datalen;
497 write(d->fd, imsg->data, datalen);
498 ui_on_download_refresh();
502 static void
503 handle_imsg_eof(struct imsg *imsg, size_t datalen)
505 struct tab *tab = NULL;
506 struct download *d = NULL;
508 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
509 (d = download_by_id(imsg->hdr.peerid)) == NULL)
510 return;
512 if (tab != NULL) {
513 if (!parser_free(tab))
514 die();
515 if (!strncmp(tab->hist_cur->h, "gemini://", 9) ||
516 !strncmp(tab->hist_cur->h, "gopher://", 9))
517 mcache_tab(tab);
518 ui_on_tab_refresh(tab);
519 ui_on_tab_loaded(tab);
520 } else {
521 close(d->fd);
522 d->fd = -1;
523 ui_on_download_refresh();
527 static void
528 handle_dispatch_imsg(int fd, short ev, void *d)
530 struct imsgev *iev = d;
532 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
533 err(1, "connection closed");
536 static int
537 load_about_url(struct tab *tab, const char *url)
539 tab->trust = TS_TRUSTED;
540 fs_load_url(tab, url);
541 ui_on_tab_refresh(tab);
542 ui_on_tab_loaded(tab);
543 return 0;
546 static int
547 load_file_url(struct tab *tab, const char *url)
549 tab->trust = TS_TRUSTED;
550 fs_load_url(tab, url);
551 ui_on_tab_refresh(tab);
552 ui_on_tab_loaded(tab);
553 return 0;
556 static int
557 load_finger_url(struct tab *tab, const char *url)
559 struct get_req req;
560 size_t len;
561 char *at;
563 memset(&req, 0, sizeof(req));
564 strlcpy(req.port, tab->uri.port, sizeof(req.port));
566 /*
567 * Sometimes the finger url have the user as path component
568 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
569 * userinfo (e.g. finger://cobradile@finger.farm).
570 */
571 if ((at = strchr(tab->uri.host, '@')) != NULL) {
572 len = at - tab->uri.host;
573 memcpy(req.req, tab->uri.host, len);
575 if (len >= sizeof(req.req))
576 die();
577 req.req[len] = '\0';
579 strlcpy(req.host, at+1, sizeof(req.host));
580 } else {
581 strlcpy(req.host, tab->uri.host, sizeof(req.host));
583 /* +1 to skip the initial `/' */
584 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
586 strlcat(req.req, "\r\n", sizeof(req.req));
588 parser_init(tab, textplain_initparser);
589 return make_request(tab, &req, PROTO_FINGER, NULL);
592 static int
593 load_gemini_url(struct tab *tab, const char *url)
595 struct get_req req;
597 memset(&req, 0, sizeof(req));
598 strlcpy(req.host, tab->uri.host, sizeof(req.host));
599 strlcpy(req.port, tab->uri.port, sizeof(req.port));
601 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
604 static inline const char *
605 gopher_skip_selector(const char *path, int *ret_type)
607 *ret_type = 0;
609 if (!strcmp(path, "/") || *path == '\0') {
610 *ret_type = '1';
611 return path;
614 if (*path != '/')
615 return path;
616 path++;
618 switch (*ret_type = *path) {
619 case '0':
620 case '1':
621 case '7':
622 break;
624 default:
625 *ret_type = 0;
626 path -= 1;
627 return path;
630 return ++path;
633 static int
634 load_gopher_url(struct tab *tab, const char *url)
636 struct get_req req;
637 int type;
638 const char *path;
640 memset(&req, 0, sizeof(req));
641 strlcpy(req.host, tab->uri.host, sizeof(req.host));
642 strlcpy(req.port, tab->uri.port, sizeof(req.port));
644 path = gopher_skip_selector(tab->uri.path, &type);
645 switch (type) {
646 case '0':
647 parser_init(tab, textplain_initparser);
648 break;
649 case '1':
650 parser_init(tab, gophermap_initparser);
651 break;
652 case '7':
653 free(tab->last_input_url);
654 tab->last_input_url = strdup(url);
655 if (tab->last_input_url == NULL)
656 die();
657 ui_require_input(tab, 0, ir_select_gopher);
658 return load_page_from_str(tab, err_pages[10]);
659 default:
660 return load_page_from_str(tab, "Unknown gopher selector");
663 strlcpy(req.req, path, sizeof(req.req));
664 if (*tab->uri.query != '\0') {
665 strlcat(req.req, "?", sizeof(req.req));
666 strlcat(req.req, tab->uri.query, sizeof(req.req));
668 strlcat(req.req, "\r\n", sizeof(req.req));
670 return make_request(tab, &req, PROTO_GOPHER, NULL);
673 static int
674 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
676 struct get_req req;
678 memset(&req, 0, sizeof(req));
679 strlcpy(req.host, p->host, sizeof(req.host));
680 strlcpy(req.port, p->port, sizeof(req.port));
682 tab->proxy = p;
684 return make_request(tab, &req, p->proto, tab->hist_cur->h);
687 static int
688 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
690 stop_tab(tab);
691 tab->id = tab_new_id();
692 req->proto = proto;
694 if (r != NULL) {
695 strlcpy(req->req, r, sizeof(req->req));
696 strlcat(req->req, "\r\n", sizeof(req->req));
699 start_loading_anim(tab);
700 ui_send_net(IMSG_GET, tab->id, req, sizeof(*req));
702 /*
703 * So the various load_*_url can `return make_request` and
704 * do_load_url is happy.
705 */
706 return 1;
709 void
710 gopher_send_search_req(struct tab *tab, const char *text)
712 struct get_req req;
714 memset(&req, 0, sizeof(req));
715 strlcpy(req.host, tab->uri.host, sizeof(req.host));
716 strlcpy(req.port, tab->uri.port, sizeof(req.port));
718 /* +2 to skip /7 */
719 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
720 if (*tab->uri.query != '\0') {
721 strlcat(req.req, "?", sizeof(req.req));
722 strlcat(req.req, tab->uri.query, sizeof(req.req));
725 strlcat(req.req, "\t", sizeof(req.req));
726 strlcat(req.req, text, sizeof(req.req));
727 strlcat(req.req, "\r\n", sizeof(req.req));
729 erase_buffer(&tab->buffer);
730 parser_init(tab, gophermap_initparser);
732 make_request(tab, &req, PROTO_GOPHER, NULL);
735 int
736 load_page_from_str(struct tab *tab, const char *page)
738 parser_init(tab, gemtext_initparser);
739 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
740 abort();
741 if (!tab->buffer.page.free(&tab->buffer.page))
742 abort();
743 ui_on_tab_refresh(tab);
744 ui_on_tab_loaded(tab);
745 return 0;
748 /*
749 * Effectively load the given url in the given tab. Return 1 when
750 * loading the page asynchronously, and thus when an erase_buffer can
751 * be done right after this function return, or 0 when loading the
752 * page synchronously.
753 */
754 static int
755 do_load_url(struct tab *tab, const char *url, const char *base, int mode)
757 const struct proto *p;
758 struct phos_uri uri;
759 struct proxy *proxy;
760 int nocache = mode & LU_MODE_NOCACHE;
761 char *t;
763 tab->proxy = NULL;
764 tab->trust = TS_UNKNOWN;
766 if (base == NULL)
767 memcpy(&uri, &tab->uri, sizeof(tab->uri));
768 else
769 phos_parse_absolute_uri(base, &uri);
771 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
772 if (asprintf(&t, "#error loading %s\n>%s\n",
773 url, "Can't parse the URI") == -1)
774 die();
775 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
776 load_page_from_str(tab, t);
777 free(t);
778 return 0;
781 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
782 sizeof(tab->hist_cur->h));
784 if (!nocache && mcache_lookup(tab->hist_cur->h, tab)) {
785 ui_on_tab_refresh(tab);
786 ui_on_tab_loaded(tab);
787 return 0;
790 for (p = protos; p->schema != NULL; ++p) {
791 if (!strcmp(tab->uri.scheme, p->schema)) {
792 /* patch the port */
793 if (*tab->uri.port == '\0' && p->port != NULL)
794 strlcpy(tab->uri.port, p->port,
795 sizeof(tab->uri.port));
797 return p->loadfn(tab, tab->hist_cur->h);
801 TAILQ_FOREACH(proxy, &proxies, proxies) {
802 if (!strcmp(tab->uri.scheme, proxy->match_proto))
803 return load_via_proxy(tab, url, proxy);
806 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
809 /*
810 * Load url in tab and handle history. If a tab is marked as lazy, only
811 * prepare the url but don't load it.
812 */
813 void
814 load_url(struct tab *tab, const char *url, const char *base, int mode)
816 int lazy = tab->flags & TAB_LAZY;
817 int nohist = mode & LU_MODE_NOHIST;
819 if (operating && lazy) {
820 tab->flags ^= TAB_LAZY;
821 lazy = 0;
822 } else if (tab->hist_cur != NULL)
823 get_scroll_position(tab, &tab->hist_cur->line_off,
824 &tab->hist_cur->current_off);
826 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
827 if (tab->hist_cur != NULL)
828 hist_clear_forward(&tab->hist,
829 TAILQ_NEXT(tab->hist_cur, entries));
831 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
832 == NULL) {
833 event_loopbreak();
834 return;
837 strlcpy(tab->buffer.page.title, url,
838 sizeof(tab->buffer.page.title));
839 hist_push(&tab->hist, tab->hist_cur);
841 if (lazy)
842 strlcpy(tab->hist_cur->h, url,
843 sizeof(tab->hist_cur->h));
846 if (!lazy)
847 do_load_url(tab, url, base, mode);
850 void
851 load_url_in_tab(struct tab *tab, const char *url, const char *base, int mode)
853 if (operating) {
854 autosave_hook();
855 message("Loading %s...", url);
858 load_url(tab, url, base, mode);
861 int
862 load_previous_page(struct tab *tab)
864 struct hist *h;
866 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
867 return 0;
868 tab->hist_cur = h;
869 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
870 return 1;
873 int
874 load_next_page(struct tab *tab)
876 struct hist *h;
878 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
879 return 0;
880 tab->hist_cur = h;
881 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
882 return 1;
885 void
886 write_buffer(const char *path, struct tab *tab)
888 FILE *fp;
890 if (path == NULL)
891 return;
893 if ((fp = fopen(path, "w")) == NULL)
894 return;
895 if (!parser_serialize(tab, fp))
896 message("Failed to save the page.");
897 fclose(fp);
900 /*
901 * Given a user-entered URL, apply some heuristics to use it:
903 * - if it's a proper url use it
904 * - if it starts with a `./' or a `/' assume its a file:// url
905 * - assume it's a gemini:// url
907 * `ret' (of which len is the size) will be filled with the resulting
908 * url.
909 */
910 void
911 humanify_url(const char *raw, char *ret, size_t len)
913 struct phos_uri uri;
914 char buf[PATH_MAX];
916 if (phos_parse_absolute_uri(raw, &uri)) {
917 strlcpy(ret, raw, len);
918 return;
921 if (!strncmp(raw, "./", 2)) {
922 strlcpy(ret, "file://", len);
923 getcwd(buf, sizeof(buf));
924 strlcat(ret, buf, len);
925 strlcat(ret, "/", len);
926 strlcat(ret, raw+2, len);
927 return;
930 if (*raw == '/') {
931 strlcpy(ret, "file://", len);
932 strlcat(ret, raw, len);
933 return;
936 strlcpy(ret, "gemini://", len);
937 strlcat(ret, raw, len);
940 int
941 bookmark_page(const char *url)
943 FILE *fp;
945 if ((fp = fopen(bookmark_file, "a")) == NULL)
946 return -1;
947 fprintf(fp, "=> %s\n", url);
948 fclose(fp);
949 return 0;
952 static pid_t
953 start_child(enum telescope_process p, const char *argv0, int fd)
955 const char *argv[5];
956 int argc = 0;
957 pid_t pid;
959 switch (pid = fork()) {
960 case -1:
961 die();
962 case 0:
963 break;
964 default:
965 close(fd);
966 return pid;
969 if (dup2(fd, 3) == -1)
970 err(1, "cannot setup imsg fd");
972 argv[argc++] = argv0;
973 switch (p) {
974 case PROC_UI:
975 errx(1, "Can't start ui process");
976 case PROC_NET:
977 argv[argc++] = "-Tn";
978 break;
981 if (safe_mode)
982 argv[argc++] = "-S";
984 argv[argc++] = NULL;
985 execvp(argv0, (char *const *)argv);
986 err(1, "execvp(%s)", argv0);
989 static void
990 send_url(const char *url)
992 struct sockaddr_un sun;
993 struct imsgbuf ibuf;
994 int ctl_sock;
996 if ((ctl_sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
997 err(1, "socket");
999 memset(&sun, 0, sizeof(sun));
1000 sun.sun_family = AF_UNIX;
1001 strlcpy(sun.sun_path, ctlsock_path, sizeof(sun.sun_path));
1003 if (connect(ctl_sock, (struct sockaddr *)&sun, sizeof(sun)) == -1)
1004 err(1, "connect: %s", ctlsock_path);
1006 imsg_init(&ibuf, ctl_sock);
1007 imsg_compose(&ibuf, IMSG_CTL_OPEN_URL, 0, 0, -1, url,
1008 strlen(url) + 1);
1009 imsg_flush(&ibuf);
1010 close(ctl_sock);
1013 int
1014 ui_send_net(int type, uint32_t peerid, const void *data,
1015 uint16_t datalen)
1017 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1018 datalen);
1021 static void __attribute__((noreturn))
1022 usage(int r)
1024 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1025 getprogname());
1026 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1027 exit(r);
1030 int
1031 main(int argc, char * const *argv)
1033 struct imsgev net_ibuf;
1034 pid_t pid;
1035 int control_fd;
1036 int pipe2net[2];
1037 int ch, configtest = 0, fail = 0;
1038 int proc = -1;
1039 int sessionfd = -1;
1040 int status;
1041 const char *argv0;
1043 argv0 = argv[0];
1045 signal(SIGCHLD, SIG_IGN);
1046 signal(SIGPIPE, SIG_IGN);
1048 if (getenv("NO_COLOR") != NULL)
1049 enable_colors = 0;
1051 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1052 switch (ch) {
1053 case 'C':
1054 exit(ui_print_colors());
1055 case 'c':
1056 fail = 1;
1057 strlcpy(config_path, optarg, sizeof(config_path));
1058 break;
1059 case 'n':
1060 configtest = 1;
1061 break;
1062 case 'h':
1063 usage(0);
1064 case 'S':
1065 safe_mode = 1;
1066 break;
1067 case 'T':
1068 switch (*optarg) {
1069 case 'n':
1070 proc = PROC_NET;
1071 break;
1072 default:
1073 errx(1, "invalid process spec %c",
1074 *optarg);
1076 break;
1077 case 'v':
1078 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1079 exit(0);
1080 break;
1081 default:
1082 usage(1);
1086 argc -= optind;
1087 argv += optind;
1089 if (proc != -1) {
1090 if (argc > 0)
1091 usage(1);
1092 else if (proc == PROC_NET)
1093 return net_main();
1094 else
1095 usage(1);
1098 if (argc != 0) {
1099 has_url = 1;
1100 humanify_url(argv[0], url, sizeof(url));
1103 fs_init();
1105 /* setup keys before reading the config */
1106 TAILQ_INIT(&global_map.m);
1107 global_map.unhandled_input = global_key_unbound;
1108 TAILQ_INIT(&minibuffer_map.m);
1110 config_init();
1111 parseconfig(config_path, fail);
1112 if (configtest) {
1113 puts("config OK");
1114 exit(0);
1117 if (download_path == NULL &&
1118 (download_path = strdup("/tmp/")) == NULL)
1119 errx(1, "strdup");
1121 if (!safe_mode && (sessionfd = lock_session()) == -1) {
1122 if (has_url) {
1123 send_url(url);
1124 exit(0);
1127 errx(1, "can't lock session, is another instance of "
1128 "telescope already running?");
1131 /* Start children. */
1132 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1133 err(1, "socketpair");
1134 start_child(PROC_NET, argv0, pipe2net[1]);
1135 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1136 iev_net = &net_ibuf;
1137 iev_net->handler = handle_dispatch_imsg;
1139 setproctitle("ui");
1141 /* initialize tofu store */
1142 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1144 event_init();
1146 if (!safe_mode) {
1147 if ((control_fd = control_init(ctlsock_path)) == -1)
1148 err(1, "control_init %s", ctlsock_path);
1149 control_listen(control_fd);
1152 /* initialize the in-memory cache store */
1153 mcache_init();
1155 /* Setup event handler for the autosave */
1156 autosave_init();
1158 /* Setup event handlers for pipes to net */
1159 iev_net->events = EV_READ;
1160 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1161 iev_net->handler, iev_net);
1162 event_add(&iev_net->ev, NULL);
1164 if (ui_init()) {
1165 sandbox_ui_process();
1166 load_session(&certs);
1167 if (has_url)
1168 new_tab(url, NULL, NULL);
1169 operating = 1;
1170 switch_to_tab(current_tab);
1171 ui_main_loop();
1172 ui_end();
1175 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1176 imsg_flush(&iev_net->ibuf);
1178 /* wait for children to terminate */
1179 do {
1180 pid = wait(&status);
1181 if (pid == -1) {
1182 if (errno != EINTR && errno != ECHILD)
1183 err(1, "wait");
1184 } else if (WIFSIGNALED(status))
1185 warnx("child terminated; signal %d", WTERMSIG(status));
1186 } while (pid != -1 || (pid == -1 && errno == EINTR));
1188 if (!safe_mode)
1189 unlink(crashed_file);
1191 if (!safe_mode && close(sessionfd) == -1)
1192 err(1, "close(sessionfd = %d)", sessionfd);
1194 return 0;