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_add(&certs, e);
239 save_cert(e);
240 } else
241 tofu_res = !strcmp(hash, e->hash);
243 if (tofu_res) {
244 if (e->verified == -1)
245 tab->trust = TS_TEMP_TRUSTED;
246 else if (e->verified == 1)
247 tab->trust = TS_VERIFIED;
248 else
249 tab->trust = TS_TRUSTED;
251 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
252 &tofu_res, sizeof(tofu_res));
253 } else {
254 tab->trust = TS_UNTRUSTED;
255 load_page_from_str(tab, "# Certificate mismatch\n");
256 if ((tab->cert = strdup(hash)) == NULL)
257 die();
258 ui_yornp("Certificate mismatch. Proceed?",
259 handle_check_cert_user_choice, tab);
263 static void
264 handle_check_cert_user_choice(int accept, struct tab *tab)
266 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
267 sizeof(accept));
269 if (accept) {
270 /*
271 * trust the certificate for this session only. If
272 * the page results in a redirect while we're asking
273 * the user to save, we'll end up with an invalid
274 * tabid (one request == one tab id). It also makes
275 * sense to save it for the current session if the
276 * user accepted it.
277 */
278 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
279 tab->cert);
281 if (!safe_mode)
282 ui_yornp("Save the new certificate?",
283 handle_maybe_save_new_cert, tab);
284 else
285 message("Certificate temporarly trusted");
286 } else {
287 free(tab->cert);
288 tab->cert = NULL;
292 static void
293 handle_maybe_save_new_cert(int accept, struct tab *tab)
295 struct tofu_entry *e;
296 const char *host, *port;
298 if (tab->proxy != NULL) {
299 host = tab->proxy->host;
300 port = tab->proxy->port;
301 } else {
302 host = tab->uri.host;
303 port = tab->uri.port;
306 if (!accept)
307 goto end;
309 if ((e = calloc(1, sizeof(*e))) == NULL)
310 die();
312 strlcpy(e->domain, host, sizeof(e->domain));
313 if (*port != '\0' && strcmp(port, "1965")) {
314 strlcat(e->domain, ":", sizeof(e->domain));
315 strlcat(e->domain, port, sizeof(e->domain));
317 strlcpy(e->hash, tab->cert, sizeof(e->hash));
319 update_cert(e);
320 tofu_update(&certs, e);
322 tab->trust = TS_TRUSTED;
324 end:
325 free(tab->cert);
326 tab->cert = NULL;
329 static inline int
330 normalize_code(int n)
332 if (n < 20) {
333 if (n == 10 || n == 11)
334 return n;
335 return 10;
336 } else if (n < 30) {
337 return 20;
338 } else if (n < 40) {
339 if (n == 30 || n == 31)
340 return n;
341 return 30;
342 } else if (n < 50) {
343 if (n <= 44)
344 return n;
345 return 40;
346 } else if (n < 60) {
347 if (n <= 53 || n == 59)
348 return n;
349 return 50;
350 } else if (n < 70) {
351 if (n <= 62)
352 return n;
353 return 60;
354 } else
355 return MALFORMED_RESPONSE;
358 static void
359 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
361 struct tab *tab;
363 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
364 return;
366 if (sizeof(tab->code) != datalen)
367 die();
369 memcpy(&tab->code, imsg->data, sizeof(tab->code));
370 tab->code = normalize_code(tab->code);
371 if (tab->code != 30 && tab->code != 31)
372 tab->redirect_count = 0;
375 static void
376 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
378 struct tab *tab;
379 char buf[128];
381 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
382 return;
384 if (sizeof(tab->meta) <= datalen)
385 die();
387 memcpy(tab->meta, imsg->data, datalen);
389 if (tab->code < 10) { /* internal errors */
390 load_page_from_str(tab, err_pages[tab->code]);
391 } else if (tab->code < 20) { /* 1x */
392 free(tab->last_input_url);
393 tab->last_input_url = strdup(tab->hist_cur->h);
394 if (tab->last_input_url == NULL)
395 die();
397 load_page_from_str(tab, err_pages[tab->code]);
398 ui_require_input(tab, tab->code == 11, ir_select_gemini);
399 } else if (tab->code == 20) {
400 history_add(tab->hist_cur->h);
401 if (setup_parser_for(tab)) {
402 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
403 } else if (safe_mode) {
404 load_page_from_str(tab,
405 err_pages[UNKNOWN_TYPE_OR_CSET]);
406 } else {
407 struct hist *h;
409 if ((h = hist_pop(&tab->hist)) != NULL)
410 tab->hist_cur = h;
411 snprintf(buf, sizeof(buf),
412 "Can't display \"%s\", save it?", tab->meta);
413 ui_yornp(buf, handle_maybe_save_page, tab);
415 } else if (tab->code < 40) { /* 3x */
416 tab->redirect_count++;
418 /* TODO: make customizable? */
419 if (tab->redirect_count > 5) {
420 load_page_from_str(tab,
421 err_pages[TOO_MUCH_REDIRECTS]);
422 } else
423 do_load_url(tab, tab->meta, NULL, LU_MODE_NOCACHE);
424 } else { /* 4x, 5x & 6x */
425 load_page_from_str(tab, err_pages[tab->code]);
429 static void
430 handle_maybe_save_page(int dosave, struct tab *tab)
432 const char *f;
433 char input[PATH_MAX];
435 /* XXX: this print a message that is confusing */
436 ui_on_tab_loaded(tab);
438 if (!dosave) {
439 stop_tab(tab);
440 return;
443 if ((f = strrchr(tab->uri.path, '/')) == NULL)
444 f = "";
445 else
446 f++;
448 strlcpy(input, download_path, sizeof(input));
449 strlcat(input, f, sizeof(input));
451 ui_read("Save to path", handle_save_page_path, tab, input);
454 static void
455 handle_save_page_path(const char *path, struct tab *tab)
457 struct download *d;
458 int fd;
460 if (path == NULL) {
461 stop_tab(tab);
462 return;
465 ui_show_downloads_pane();
467 d = enqueue_download(tab->id, path, 0);
469 /*
470 * Change this tab id, the old one is associated with the
471 * download now.
472 */
473 tab->id = tab_new_id();
475 if ((fd = open(path, O_WRONLY|O_TRUNC|O_CREAT, 0644)) == -1)
476 message("Can't open file %s: %s", d->path, strerror(errno));
477 else if (d->buffer) {
478 FILE *fp;
479 int r;
481 if ((fp = fdopen(fd, "w")) != NULL) {
482 r = parser_serialize(current_tab, fp);
483 if (!r)
484 message("Failed to save the page.");
485 fclose(fp);
488 dequeue_first_download();
489 } else {
490 d->fd = fd;
491 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
495 static void
496 handle_imsg_buf(struct imsg *imsg, size_t datalen)
498 struct tab *tab = NULL;
499 struct download *d = NULL;
501 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
502 (d = download_by_id(imsg->hdr.peerid)) == NULL)
503 return;
505 if (tab != NULL) {
506 if (!parser_parse(tab, imsg->data, datalen))
507 die();
508 ui_on_tab_refresh(tab);
509 } else {
510 d->bytes += datalen;
511 write(d->fd, imsg->data, datalen);
512 ui_on_download_refresh();
516 static void
517 handle_imsg_eof(struct imsg *imsg, size_t datalen)
519 struct tab *tab = NULL;
520 struct download *d = NULL;
522 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
523 (d = download_by_id(imsg->hdr.peerid)) == NULL)
524 return;
526 if (tab != NULL) {
527 if (!parser_free(tab))
528 die();
529 if (has_prefix(tab->hist_cur->h, "gemini://") ||
530 has_prefix(tab->hist_cur->h, "gopher://"))
531 mcache_tab(tab);
532 ui_on_tab_refresh(tab);
533 ui_on_tab_loaded(tab);
534 } else {
535 close(d->fd);
536 d->fd = -1;
537 ui_on_download_refresh();
541 static void
542 handle_dispatch_imsg(int fd, short ev, void *d)
544 struct imsgev *iev = d;
546 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
547 err(1, "connection closed");
550 static int
551 load_about_url(struct tab *tab, const char *url)
553 tab->trust = TS_TRUSTED;
554 fs_load_url(tab, url);
555 ui_on_tab_refresh(tab);
556 ui_on_tab_loaded(tab);
557 return 0;
560 static int
561 load_file_url(struct tab *tab, const char *url)
563 tab->trust = TS_TRUSTED;
564 fs_load_url(tab, url);
565 ui_on_tab_refresh(tab);
566 ui_on_tab_loaded(tab);
567 return 0;
570 static int
571 load_finger_url(struct tab *tab, const char *url)
573 struct get_req req;
574 size_t len;
575 char *at;
577 memset(&req, 0, sizeof(req));
578 strlcpy(req.port, tab->uri.port, sizeof(req.port));
580 /*
581 * Sometimes the finger url have the user as path component
582 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
583 * userinfo (e.g. finger://cobradile@finger.farm).
584 */
585 if ((at = strchr(tab->uri.host, '@')) != NULL) {
586 len = at - tab->uri.host;
587 memcpy(req.req, tab->uri.host, len);
589 if (len >= sizeof(req.req))
590 die();
591 req.req[len] = '\0';
593 strlcpy(req.host, at+1, sizeof(req.host));
594 } else {
595 strlcpy(req.host, tab->uri.host, sizeof(req.host));
597 /* +1 to skip the initial `/' */
598 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
600 strlcat(req.req, "\r\n", sizeof(req.req));
602 parser_init(tab, textplain_initparser);
603 return make_request(tab, &req, PROTO_FINGER, NULL);
606 static int
607 load_gemini_url(struct tab *tab, const char *url)
609 struct get_req req;
611 memset(&req, 0, sizeof(req));
612 strlcpy(req.host, tab->uri.host, sizeof(req.host));
613 strlcpy(req.port, tab->uri.port, sizeof(req.port));
615 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
618 static inline const char *
619 gopher_skip_selector(const char *path, int *ret_type)
621 *ret_type = 0;
623 if (!strcmp(path, "/") || *path == '\0') {
624 *ret_type = '1';
625 return path;
628 if (*path != '/')
629 return path;
630 path++;
632 switch (*ret_type = *path) {
633 case '0':
634 case '1':
635 case '7':
636 break;
638 default:
639 *ret_type = 0;
640 path -= 1;
641 return path;
644 return ++path;
647 static int
648 load_gopher_url(struct tab *tab, const char *url)
650 struct get_req req;
651 int type;
652 const char *path;
654 memset(&req, 0, sizeof(req));
655 strlcpy(req.host, tab->uri.host, sizeof(req.host));
656 strlcpy(req.port, tab->uri.port, sizeof(req.port));
658 path = gopher_skip_selector(tab->uri.path, &type);
659 switch (type) {
660 case '0':
661 parser_init(tab, textplain_initparser);
662 break;
663 case '1':
664 parser_init(tab, gophermap_initparser);
665 break;
666 case '7':
667 free(tab->last_input_url);
668 tab->last_input_url = strdup(url);
669 if (tab->last_input_url == NULL)
670 die();
671 ui_require_input(tab, 0, ir_select_gopher);
672 return load_page_from_str(tab, err_pages[10]);
673 default:
674 return load_page_from_str(tab, "Unknown gopher selector");
677 strlcpy(req.req, path, sizeof(req.req));
678 if (*tab->uri.query != '\0') {
679 strlcat(req.req, "?", sizeof(req.req));
680 strlcat(req.req, tab->uri.query, sizeof(req.req));
682 strlcat(req.req, "\r\n", sizeof(req.req));
684 return make_request(tab, &req, PROTO_GOPHER, NULL);
687 static int
688 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
690 struct get_req req;
692 memset(&req, 0, sizeof(req));
693 strlcpy(req.host, p->host, sizeof(req.host));
694 strlcpy(req.port, p->port, sizeof(req.port));
696 tab->proxy = p;
698 return make_request(tab, &req, p->proto, tab->hist_cur->h);
701 static int
702 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
704 stop_tab(tab);
705 tab->id = tab_new_id();
706 req->proto = proto;
708 if (r != NULL) {
709 strlcpy(req->req, r, sizeof(req->req));
710 strlcat(req->req, "\r\n", sizeof(req->req));
713 start_loading_anim(tab);
714 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
716 /*
717 * So the various load_*_url can `return make_request` and
718 * do_load_url is happy.
719 */
720 return 1;
723 void
724 gopher_send_search_req(struct tab *tab, const char *text)
726 struct get_req req;
728 memset(&req, 0, sizeof(req));
729 strlcpy(req.host, tab->uri.host, sizeof(req.host));
730 strlcpy(req.port, tab->uri.port, sizeof(req.port));
732 /* +2 to skip /7 */
733 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
734 if (*tab->uri.query != '\0') {
735 strlcat(req.req, "?", sizeof(req.req));
736 strlcat(req.req, tab->uri.query, sizeof(req.req));
739 strlcat(req.req, "\t", sizeof(req.req));
740 strlcat(req.req, text, sizeof(req.req));
741 strlcat(req.req, "\r\n", sizeof(req.req));
743 erase_buffer(&tab->buffer);
744 parser_init(tab, gophermap_initparser);
746 make_request(tab, &req, PROTO_GOPHER, NULL);
749 int
750 load_page_from_str(struct tab *tab, const char *page)
752 parser_init(tab, gemtext_initparser);
753 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
754 abort();
755 if (!tab->buffer.page.free(&tab->buffer.page))
756 abort();
757 ui_on_tab_refresh(tab);
758 ui_on_tab_loaded(tab);
759 return 0;
762 /*
763 * Effectively load the given url in the given tab. Return 1 when
764 * loading the page asynchronously, and thus when an erase_buffer can
765 * be done right after this function return, or 0 when loading the
766 * page synchronously.
767 */
768 static int
769 do_load_url(struct tab *tab, const char *url, const char *base, int mode)
771 const struct proto *p;
772 struct phos_uri uri;
773 struct proxy *proxy;
774 int nocache = mode & LU_MODE_NOCACHE;
775 char *t;
777 tab->proxy = NULL;
778 tab->trust = TS_UNKNOWN;
780 if (base == NULL)
781 memcpy(&uri, &tab->uri, sizeof(tab->uri));
782 else
783 phos_parse_absolute_uri(base, &uri);
785 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
786 if (asprintf(&t, "#error loading %s\n>%s\n",
787 url, "Can't parse the URI") == -1)
788 die();
789 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
790 load_page_from_str(tab, t);
791 free(t);
792 return 0;
795 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
796 sizeof(tab->hist_cur->h));
798 if (!nocache && mcache_lookup(tab->hist_cur->h, tab)) {
799 ui_on_tab_refresh(tab);
800 ui_on_tab_loaded(tab);
801 return 0;
804 for (p = protos; p->schema != NULL; ++p) {
805 if (!strcmp(tab->uri.scheme, p->schema)) {
806 /* patch the port */
807 if (*tab->uri.port == '\0' && p->port != NULL)
808 strlcpy(tab->uri.port, p->port,
809 sizeof(tab->uri.port));
811 return p->loadfn(tab, tab->hist_cur->h);
815 TAILQ_FOREACH(proxy, &proxies, proxies) {
816 if (!strcmp(tab->uri.scheme, proxy->match_proto))
817 return load_via_proxy(tab, url, proxy);
820 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
823 /*
824 * Load url in tab and handle history. If a tab is marked as lazy, only
825 * prepare the url but don't load it.
826 */
827 void
828 load_url(struct tab *tab, const char *url, const char *base, int mode)
830 int lazy = tab->flags & TAB_LAZY;
831 int nohist = mode & LU_MODE_NOHIST;
833 if (operating && lazy) {
834 tab->flags ^= TAB_LAZY;
835 lazy = 0;
836 } else if (tab->hist_cur != NULL)
837 get_scroll_position(tab, &tab->hist_cur->line_off,
838 &tab->hist_cur->current_off);
840 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
841 if (tab->hist_cur != NULL)
842 hist_clear_forward(&tab->hist,
843 TAILQ_NEXT(tab->hist_cur, entries));
845 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
846 == NULL) {
847 event_loopbreak();
848 return;
851 strlcpy(tab->buffer.page.title, url,
852 sizeof(tab->buffer.page.title));
853 hist_push(&tab->hist, tab->hist_cur);
855 if (lazy)
856 strlcpy(tab->hist_cur->h, url,
857 sizeof(tab->hist_cur->h));
860 if (!lazy)
861 do_load_url(tab, url, base, mode);
864 void
865 load_url_in_tab(struct tab *tab, const char *url, const char *base, int mode)
867 if (operating) {
868 autosave_hook();
869 message("Loading %s...", url);
872 load_url(tab, url, base, mode);
875 int
876 load_previous_page(struct tab *tab)
878 struct hist *h;
880 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
881 return 0;
882 tab->hist_cur = h;
883 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
884 return 1;
887 int
888 load_next_page(struct tab *tab)
890 struct hist *h;
892 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
893 return 0;
894 tab->hist_cur = h;
895 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
896 return 1;
899 void
900 write_buffer(const char *path, struct tab *tab)
902 FILE *fp;
904 if (path == NULL)
905 return;
907 if ((fp = fopen(path, "w")) == NULL)
908 return;
909 if (!parser_serialize(tab, fp))
910 message("Failed to save the page.");
911 fclose(fp);
914 /*
915 * Given a user-entered URL, apply some heuristics to use it:
917 * - if it's a proper url use it
918 * - if it starts with a `./' or a `/' assume its a file:// url
919 * - assume it's a gemini:// url
921 * `ret' (of which len is the size) will be filled with the resulting
922 * url.
923 */
924 void
925 humanify_url(const char *raw, char *ret, size_t len)
927 struct phos_uri uri;
928 char buf[PATH_MAX];
930 if (phos_parse_absolute_uri(raw, &uri)) {
931 strlcpy(ret, raw, len);
932 return;
935 if (has_prefix(raw, "./")) {
936 strlcpy(ret, "file://", len);
937 getcwd(buf, sizeof(buf));
938 strlcat(ret, buf, len);
939 strlcat(ret, "/", len);
940 strlcat(ret, raw+2, len);
941 return;
944 if (*raw == '/') {
945 strlcpy(ret, "file://", len);
946 strlcat(ret, raw, len);
947 return;
950 strlcpy(ret, "gemini://", len);
951 strlcat(ret, raw, len);
954 static pid_t
955 start_child(enum telescope_process p, const char *argv0, int fd)
957 const char *argv[5];
958 int argc = 0;
959 pid_t pid;
961 switch (pid = fork()) {
962 case -1:
963 die();
964 case 0:
965 break;
966 default:
967 close(fd);
968 return pid;
971 if (dup2(fd, 3) == -1)
972 err(1, "cannot setup imsg fd");
974 argv[argc++] = argv0;
975 switch (p) {
976 case PROC_UI:
977 errx(1, "Can't start ui process");
978 case PROC_NET:
979 argv[argc++] = "-Tn";
980 break;
983 if (safe_mode)
984 argv[argc++] = "-S";
986 argv[argc++] = NULL;
987 execvp(argv0, (char *const *)argv);
988 err(1, "execvp(%s)", argv0);
991 static void
992 send_url(const char *url)
994 struct sockaddr_un sun;
995 struct imsgbuf ibuf;
996 int ctl_sock;
998 if ((ctl_sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
999 err(1, "socket");
1001 memset(&sun, 0, sizeof(sun));
1002 sun.sun_family = AF_UNIX;
1003 strlcpy(sun.sun_path, ctlsock_path, sizeof(sun.sun_path));
1005 if (connect(ctl_sock, (struct sockaddr *)&sun, sizeof(sun)) == -1)
1006 err(1, "connect: %s", ctlsock_path);
1008 imsg_init(&ibuf, ctl_sock);
1009 imsg_compose(&ibuf, IMSG_CTL_OPEN_URL, 0, 0, -1, url,
1010 strlen(url) + 1);
1011 imsg_flush(&ibuf);
1012 close(ctl_sock);
1015 int
1016 ui_send_net(int type, uint32_t peerid, const void *data,
1017 uint16_t datalen)
1019 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1020 datalen);
1023 static void __attribute__((noreturn))
1024 usage(int r)
1026 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1027 getprogname());
1028 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1029 exit(r);
1032 int
1033 main(int argc, char * const *argv)
1035 struct imsgev net_ibuf;
1036 pid_t pid;
1037 int control_fd;
1038 int pipe2net[2];
1039 int ch, configtest = 0, fail = 0;
1040 int proc = -1;
1041 int sessionfd = -1;
1042 int status;
1043 const char *argv0;
1045 argv0 = argv[0];
1047 signal(SIGCHLD, SIG_IGN);
1048 signal(SIGPIPE, SIG_IGN);
1050 if (getenv("NO_COLOR") != NULL)
1051 enable_colors = 0;
1053 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1054 switch (ch) {
1055 case 'C':
1056 exit(ui_print_colors());
1057 case 'c':
1058 fail = 1;
1059 strlcpy(config_path, optarg, sizeof(config_path));
1060 break;
1061 case 'n':
1062 configtest = 1;
1063 break;
1064 case 'h':
1065 usage(0);
1066 case 'S':
1067 safe_mode = 1;
1068 break;
1069 case 'T':
1070 switch (*optarg) {
1071 case 'n':
1072 proc = PROC_NET;
1073 break;
1074 default:
1075 errx(1, "invalid process spec %c",
1076 *optarg);
1078 break;
1079 case 'v':
1080 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1081 exit(0);
1082 break;
1083 default:
1084 usage(1);
1088 argc -= optind;
1089 argv += optind;
1091 if (proc != -1) {
1092 if (argc > 0)
1093 usage(1);
1094 else if (proc == PROC_NET)
1095 return net_main();
1096 else
1097 usage(1);
1100 if (argc != 0) {
1101 has_url = 1;
1102 humanify_url(argv[0], url, sizeof(url));
1105 fs_init();
1107 /* setup keys before reading the config */
1108 TAILQ_INIT(&global_map.m);
1109 global_map.unhandled_input = global_key_unbound;
1110 TAILQ_INIT(&minibuffer_map.m);
1112 config_init();
1113 parseconfig(config_path, fail);
1114 if (configtest) {
1115 puts("config OK");
1116 exit(0);
1119 if (download_path == NULL &&
1120 (download_path = strdup("/tmp/")) == NULL)
1121 errx(1, "strdup");
1123 if (!safe_mode && (sessionfd = lock_session()) == -1) {
1124 if (has_url) {
1125 send_url(url);
1126 exit(0);
1129 errx(1, "can't lock session, is another instance of "
1130 "telescope already running?");
1133 /* Start children. */
1134 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1135 err(1, "socketpair");
1136 start_child(PROC_NET, argv0, pipe2net[1]);
1137 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1138 iev_net = &net_ibuf;
1139 iev_net->handler = handle_dispatch_imsg;
1141 setproctitle("ui");
1143 /* initialize tofu store */
1144 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1146 event_init();
1148 if (!safe_mode) {
1149 if ((control_fd = control_init(ctlsock_path)) == -1)
1150 err(1, "control_init %s", ctlsock_path);
1151 control_listen(control_fd);
1154 /* initialize the in-memory cache store */
1155 mcache_init();
1157 /* Setup event handler for the autosave */
1158 autosave_init();
1160 /* Setup event handlers for pipes to net */
1161 iev_net->events = EV_READ;
1162 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1163 iev_net->handler, iev_net);
1164 event_add(&iev_net->ev, NULL);
1166 if (ui_init()) {
1167 sandbox_ui_process();
1168 fs_load_state(&certs);
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;