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 update_cert(e);
319 tofu_update(&certs, e);
321 tab->trust = TS_TRUSTED;
323 end:
324 free(tab->cert);
325 tab->cert = NULL;
328 static inline int
329 normalize_code(int n)
331 if (n < 20) {
332 if (n == 10 || n == 11)
333 return n;
334 return 10;
335 } else if (n < 30) {
336 return 20;
337 } else if (n < 40) {
338 if (n == 30 || n == 31)
339 return n;
340 return 30;
341 } else if (n < 50) {
342 if (n <= 44)
343 return n;
344 return 40;
345 } else if (n < 60) {
346 if (n <= 53 || n == 59)
347 return n;
348 return 50;
349 } else if (n < 70) {
350 if (n <= 62)
351 return n;
352 return 60;
353 } else
354 return MALFORMED_RESPONSE;
357 static void
358 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
360 struct tab *tab;
362 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
363 return;
365 if (sizeof(tab->code) != datalen)
366 die();
368 memcpy(&tab->code, imsg->data, sizeof(tab->code));
369 tab->code = normalize_code(tab->code);
370 if (tab->code != 30 && tab->code != 31)
371 tab->redirect_count = 0;
374 static void
375 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
377 struct tab *tab;
378 char buf[128];
380 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
381 return;
383 if (sizeof(tab->meta) <= datalen)
384 die();
386 memcpy(tab->meta, imsg->data, datalen);
388 if (tab->code < 10) { /* internal errors */
389 load_page_from_str(tab, err_pages[tab->code]);
390 } else if (tab->code < 20) { /* 1x */
391 free(tab->last_input_url);
392 tab->last_input_url = strdup(tab->hist_cur->h);
393 if (tab->last_input_url == NULL)
394 die();
396 load_page_from_str(tab, err_pages[tab->code]);
397 ui_require_input(tab, tab->code == 11, ir_select_gemini);
398 } else if (tab->code == 20) {
399 history_add(tab->hist_cur->h);
400 if (setup_parser_for(tab)) {
401 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
402 } else if (safe_mode) {
403 load_page_from_str(tab,
404 err_pages[UNKNOWN_TYPE_OR_CSET]);
405 } else {
406 struct hist *h;
408 if ((h = hist_pop(&tab->hist)) != NULL)
409 tab->hist_cur = h;
410 snprintf(buf, sizeof(buf),
411 "Can't display \"%s\", save it?", tab->meta);
412 ui_yornp(buf, handle_maybe_save_page, tab);
414 } else if (tab->code < 40) { /* 3x */
415 tab->redirect_count++;
417 /* TODO: make customizable? */
418 if (tab->redirect_count > 5) {
419 load_page_from_str(tab,
420 err_pages[TOO_MUCH_REDIRECTS]);
421 } else
422 do_load_url(tab, tab->meta, NULL, LU_MODE_NOCACHE);
423 } else { /* 4x, 5x & 6x */
424 load_page_from_str(tab, err_pages[tab->code]);
428 static void
429 handle_maybe_save_page(int dosave, struct tab *tab)
431 const char *f;
432 char input[PATH_MAX];
434 /* XXX: this print a message that is confusing */
435 ui_on_tab_loaded(tab);
437 if (!dosave) {
438 stop_tab(tab);
439 return;
442 if ((f = strrchr(tab->uri.path, '/')) == NULL)
443 f = "";
444 else
445 f++;
447 strlcpy(input, download_path, sizeof(input));
448 strlcat(input, f, sizeof(input));
450 ui_read("Save to path", handle_save_page_path, tab, input);
453 static void
454 handle_save_page_path(const char *path, struct tab *tab)
456 struct download *d;
457 int fd;
459 if (path == NULL) {
460 stop_tab(tab);
461 return;
464 ui_show_downloads_pane();
466 d = enqueue_download(tab->id, path, 0);
468 /*
469 * Change this tab id, the old one is associated with the
470 * download now.
471 */
472 tab->id = tab_new_id();
474 if ((fd = open(path, O_WRONLY|O_TRUNC|O_CREAT, 0644)) == -1)
475 message("Can't open file %s: %s", d->path, strerror(errno));
476 else if (d->buffer) {
477 FILE *fp;
478 int r;
480 if ((fp = fdopen(fd, "w")) != NULL) {
481 r = parser_serialize(current_tab, fp);
482 if (!r)
483 message("Failed to save the page.");
484 fclose(fp);
487 dequeue_first_download();
488 } else {
489 d->fd = fd;
490 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
494 static void
495 handle_imsg_buf(struct imsg *imsg, size_t datalen)
497 struct tab *tab = NULL;
498 struct download *d = NULL;
500 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
501 (d = download_by_id(imsg->hdr.peerid)) == NULL)
502 return;
504 if (tab != NULL) {
505 if (!parser_parse(tab, imsg->data, datalen))
506 die();
507 ui_on_tab_refresh(tab);
508 } else {
509 d->bytes += datalen;
510 write(d->fd, imsg->data, datalen);
511 ui_on_download_refresh();
515 static void
516 handle_imsg_eof(struct imsg *imsg, size_t datalen)
518 struct tab *tab = NULL;
519 struct download *d = NULL;
521 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
522 (d = download_by_id(imsg->hdr.peerid)) == NULL)
523 return;
525 if (tab != NULL) {
526 if (!parser_free(tab))
527 die();
528 if (has_prefix(tab->hist_cur->h, "gemini://") ||
529 has_prefix(tab->hist_cur->h, "gopher://"))
530 mcache_tab(tab);
531 ui_on_tab_refresh(tab);
532 ui_on_tab_loaded(tab);
533 } else {
534 close(d->fd);
535 d->fd = -1;
536 ui_on_download_refresh();
540 static void
541 handle_dispatch_imsg(int fd, short ev, void *d)
543 struct imsgev *iev = d;
545 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
546 err(1, "connection closed");
549 static int
550 load_about_url(struct tab *tab, const char *url)
552 tab->trust = TS_TRUSTED;
553 fs_load_url(tab, url);
554 ui_on_tab_refresh(tab);
555 ui_on_tab_loaded(tab);
556 return 0;
559 static int
560 load_file_url(struct tab *tab, const char *url)
562 tab->trust = TS_TRUSTED;
563 fs_load_url(tab, url);
564 ui_on_tab_refresh(tab);
565 ui_on_tab_loaded(tab);
566 return 0;
569 static int
570 load_finger_url(struct tab *tab, const char *url)
572 struct get_req req;
573 size_t len;
574 char *at;
576 memset(&req, 0, sizeof(req));
577 strlcpy(req.port, tab->uri.port, sizeof(req.port));
579 /*
580 * Sometimes the finger url have the user as path component
581 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
582 * userinfo (e.g. finger://cobradile@finger.farm).
583 */
584 if ((at = strchr(tab->uri.host, '@')) != NULL) {
585 len = at - tab->uri.host;
586 memcpy(req.req, tab->uri.host, len);
588 if (len >= sizeof(req.req))
589 die();
590 req.req[len] = '\0';
592 strlcpy(req.host, at+1, sizeof(req.host));
593 } else {
594 strlcpy(req.host, tab->uri.host, sizeof(req.host));
596 /* +1 to skip the initial `/' */
597 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
599 strlcat(req.req, "\r\n", sizeof(req.req));
601 parser_init(tab, textplain_initparser);
602 return make_request(tab, &req, PROTO_FINGER, NULL);
605 static int
606 load_gemini_url(struct tab *tab, const char *url)
608 struct get_req req;
610 memset(&req, 0, sizeof(req));
611 strlcpy(req.host, tab->uri.host, sizeof(req.host));
612 strlcpy(req.port, tab->uri.port, sizeof(req.port));
614 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
617 static inline const char *
618 gopher_skip_selector(const char *path, int *ret_type)
620 *ret_type = 0;
622 if (!strcmp(path, "/") || *path == '\0') {
623 *ret_type = '1';
624 return path;
627 if (*path != '/')
628 return path;
629 path++;
631 switch (*ret_type = *path) {
632 case '0':
633 case '1':
634 case '7':
635 break;
637 default:
638 *ret_type = 0;
639 path -= 1;
640 return path;
643 return ++path;
646 static int
647 load_gopher_url(struct tab *tab, const char *url)
649 struct get_req req;
650 int type;
651 const char *path;
653 memset(&req, 0, sizeof(req));
654 strlcpy(req.host, tab->uri.host, sizeof(req.host));
655 strlcpy(req.port, tab->uri.port, sizeof(req.port));
657 path = gopher_skip_selector(tab->uri.path, &type);
658 switch (type) {
659 case '0':
660 parser_init(tab, textplain_initparser);
661 break;
662 case '1':
663 parser_init(tab, gophermap_initparser);
664 break;
665 case '7':
666 free(tab->last_input_url);
667 tab->last_input_url = strdup(url);
668 if (tab->last_input_url == NULL)
669 die();
670 ui_require_input(tab, 0, ir_select_gopher);
671 return load_page_from_str(tab, err_pages[10]);
672 default:
673 return load_page_from_str(tab, "Unknown gopher selector");
676 strlcpy(req.req, path, sizeof(req.req));
677 if (*tab->uri.query != '\0') {
678 strlcat(req.req, "?", sizeof(req.req));
679 strlcat(req.req, tab->uri.query, sizeof(req.req));
681 strlcat(req.req, "\r\n", sizeof(req.req));
683 return make_request(tab, &req, PROTO_GOPHER, NULL);
686 static int
687 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
689 struct get_req req;
691 memset(&req, 0, sizeof(req));
692 strlcpy(req.host, p->host, sizeof(req.host));
693 strlcpy(req.port, p->port, sizeof(req.port));
695 tab->proxy = p;
697 return make_request(tab, &req, p->proto, tab->hist_cur->h);
700 static int
701 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
703 stop_tab(tab);
704 tab->id = tab_new_id();
705 req->proto = proto;
707 if (r != NULL) {
708 strlcpy(req->req, r, sizeof(req->req));
709 strlcat(req->req, "\r\n", sizeof(req->req));
712 start_loading_anim(tab);
713 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
715 /*
716 * So the various load_*_url can `return make_request` and
717 * do_load_url is happy.
718 */
719 return 1;
722 void
723 gopher_send_search_req(struct tab *tab, const char *text)
725 struct get_req req;
727 memset(&req, 0, sizeof(req));
728 strlcpy(req.host, tab->uri.host, sizeof(req.host));
729 strlcpy(req.port, tab->uri.port, sizeof(req.port));
731 /* +2 to skip /7 */
732 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
733 if (*tab->uri.query != '\0') {
734 strlcat(req.req, "?", sizeof(req.req));
735 strlcat(req.req, tab->uri.query, sizeof(req.req));
738 strlcat(req.req, "\t", sizeof(req.req));
739 strlcat(req.req, text, sizeof(req.req));
740 strlcat(req.req, "\r\n", sizeof(req.req));
742 erase_buffer(&tab->buffer);
743 parser_init(tab, gophermap_initparser);
745 make_request(tab, &req, PROTO_GOPHER, NULL);
748 int
749 load_page_from_str(struct tab *tab, const char *page)
751 parser_init(tab, gemtext_initparser);
752 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
753 abort();
754 if (!tab->buffer.page.free(&tab->buffer.page))
755 abort();
756 ui_on_tab_refresh(tab);
757 ui_on_tab_loaded(tab);
758 return 0;
761 /*
762 * Effectively load the given url in the given tab. Return 1 when
763 * loading the page asynchronously, and thus when an erase_buffer can
764 * be done right after this function return, or 0 when loading the
765 * page synchronously.
766 */
767 static int
768 do_load_url(struct tab *tab, const char *url, const char *base, int mode)
770 const struct proto *p;
771 struct phos_uri uri;
772 struct proxy *proxy;
773 int nocache = mode & LU_MODE_NOCACHE;
774 char *t;
776 tab->proxy = NULL;
777 tab->trust = TS_UNKNOWN;
779 if (base == NULL)
780 memcpy(&uri, &tab->uri, sizeof(tab->uri));
781 else
782 phos_parse_absolute_uri(base, &uri);
784 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
785 if (asprintf(&t, "#error loading %s\n>%s\n",
786 url, "Can't parse the URI") == -1)
787 die();
788 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
789 load_page_from_str(tab, t);
790 free(t);
791 return 0;
794 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
795 sizeof(tab->hist_cur->h));
797 if (!nocache && mcache_lookup(tab->hist_cur->h, tab)) {
798 ui_on_tab_refresh(tab);
799 ui_on_tab_loaded(tab);
800 return 0;
803 for (p = protos; p->schema != NULL; ++p) {
804 if (!strcmp(tab->uri.scheme, p->schema)) {
805 /* patch the port */
806 if (*tab->uri.port == '\0' && p->port != NULL)
807 strlcpy(tab->uri.port, p->port,
808 sizeof(tab->uri.port));
810 return p->loadfn(tab, tab->hist_cur->h);
814 TAILQ_FOREACH(proxy, &proxies, proxies) {
815 if (!strcmp(tab->uri.scheme, proxy->match_proto))
816 return load_via_proxy(tab, url, proxy);
819 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
822 /*
823 * Load url in tab and handle history. If a tab is marked as lazy, only
824 * prepare the url but don't load it.
825 */
826 void
827 load_url(struct tab *tab, const char *url, const char *base, int mode)
829 int lazy = tab->flags & TAB_LAZY;
830 int nohist = mode & LU_MODE_NOHIST;
832 if (operating && lazy) {
833 tab->flags ^= TAB_LAZY;
834 lazy = 0;
835 } else if (tab->hist_cur != NULL)
836 get_scroll_position(tab, &tab->hist_cur->line_off,
837 &tab->hist_cur->current_off);
839 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
840 if (tab->hist_cur != NULL)
841 hist_clear_forward(&tab->hist,
842 TAILQ_NEXT(tab->hist_cur, entries));
844 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
845 == NULL) {
846 event_loopbreak();
847 return;
850 strlcpy(tab->buffer.page.title, url,
851 sizeof(tab->buffer.page.title));
852 hist_push(&tab->hist, tab->hist_cur);
854 if (lazy)
855 strlcpy(tab->hist_cur->h, url,
856 sizeof(tab->hist_cur->h));
859 if (!lazy)
860 do_load_url(tab, url, base, mode);
863 void
864 load_url_in_tab(struct tab *tab, const char *url, const char *base, int mode)
866 if (operating) {
867 autosave_hook();
868 message("Loading %s...", url);
871 load_url(tab, url, base, mode);
874 int
875 load_previous_page(struct tab *tab)
877 struct hist *h;
879 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
880 return 0;
881 tab->hist_cur = h;
882 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
883 return 1;
886 int
887 load_next_page(struct tab *tab)
889 struct hist *h;
891 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
892 return 0;
893 tab->hist_cur = h;
894 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
895 return 1;
898 void
899 write_buffer(const char *path, struct tab *tab)
901 FILE *fp;
903 if (path == NULL)
904 return;
906 if ((fp = fopen(path, "w")) == NULL)
907 return;
908 if (!parser_serialize(tab, fp))
909 message("Failed to save the page.");
910 fclose(fp);
913 /*
914 * Given a user-entered URL, apply some heuristics to use it:
916 * - if it's a proper url use it
917 * - if it starts with a `./' or a `/' assume its a file:// url
918 * - assume it's a gemini:// url
920 * `ret' (of which len is the size) will be filled with the resulting
921 * url.
922 */
923 void
924 humanify_url(const char *raw, char *ret, size_t len)
926 struct phos_uri uri;
927 char buf[PATH_MAX];
929 if (phos_parse_absolute_uri(raw, &uri)) {
930 strlcpy(ret, raw, len);
931 return;
934 if (has_prefix(raw, "./")) {
935 strlcpy(ret, "file://", len);
936 getcwd(buf, sizeof(buf));
937 strlcat(ret, buf, len);
938 strlcat(ret, "/", len);
939 strlcat(ret, raw+2, len);
940 return;
943 if (*raw == '/') {
944 strlcpy(ret, "file://", len);
945 strlcat(ret, raw, len);
946 return;
949 strlcpy(ret, "gemini://", len);
950 strlcat(ret, raw, len);
953 int
954 bookmark_page(const char *url)
956 FILE *fp;
958 if ((fp = fopen(bookmark_file, "a")) == NULL)
959 return -1;
960 fprintf(fp, "=> %s\n", url);
961 fclose(fp);
962 return 0;
965 static pid_t
966 start_child(enum telescope_process p, const char *argv0, int fd)
968 const char *argv[5];
969 int argc = 0;
970 pid_t pid;
972 switch (pid = fork()) {
973 case -1:
974 die();
975 case 0:
976 break;
977 default:
978 close(fd);
979 return pid;
982 if (dup2(fd, 3) == -1)
983 err(1, "cannot setup imsg fd");
985 argv[argc++] = argv0;
986 switch (p) {
987 case PROC_UI:
988 errx(1, "Can't start ui process");
989 case PROC_NET:
990 argv[argc++] = "-Tn";
991 break;
994 if (safe_mode)
995 argv[argc++] = "-S";
997 argv[argc++] = NULL;
998 execvp(argv0, (char *const *)argv);
999 err(1, "execvp(%s)", argv0);
1002 static void
1003 send_url(const char *url)
1005 struct sockaddr_un sun;
1006 struct imsgbuf ibuf;
1007 int ctl_sock;
1009 if ((ctl_sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
1010 err(1, "socket");
1012 memset(&sun, 0, sizeof(sun));
1013 sun.sun_family = AF_UNIX;
1014 strlcpy(sun.sun_path, ctlsock_path, sizeof(sun.sun_path));
1016 if (connect(ctl_sock, (struct sockaddr *)&sun, sizeof(sun)) == -1)
1017 err(1, "connect: %s", ctlsock_path);
1019 imsg_init(&ibuf, ctl_sock);
1020 imsg_compose(&ibuf, IMSG_CTL_OPEN_URL, 0, 0, -1, url,
1021 strlen(url) + 1);
1022 imsg_flush(&ibuf);
1023 close(ctl_sock);
1026 int
1027 ui_send_net(int type, uint32_t peerid, const void *data,
1028 uint16_t datalen)
1030 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1031 datalen);
1034 static void __attribute__((noreturn))
1035 usage(int r)
1037 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1038 getprogname());
1039 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1040 exit(r);
1043 int
1044 main(int argc, char * const *argv)
1046 struct imsgev net_ibuf;
1047 pid_t pid;
1048 int control_fd;
1049 int pipe2net[2];
1050 int ch, configtest = 0, fail = 0;
1051 int proc = -1;
1052 int sessionfd = -1;
1053 int status;
1054 const char *argv0;
1056 argv0 = argv[0];
1058 signal(SIGCHLD, SIG_IGN);
1059 signal(SIGPIPE, SIG_IGN);
1061 if (getenv("NO_COLOR") != NULL)
1062 enable_colors = 0;
1064 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1065 switch (ch) {
1066 case 'C':
1067 exit(ui_print_colors());
1068 case 'c':
1069 fail = 1;
1070 strlcpy(config_path, optarg, sizeof(config_path));
1071 break;
1072 case 'n':
1073 configtest = 1;
1074 break;
1075 case 'h':
1076 usage(0);
1077 case 'S':
1078 safe_mode = 1;
1079 break;
1080 case 'T':
1081 switch (*optarg) {
1082 case 'n':
1083 proc = PROC_NET;
1084 break;
1085 default:
1086 errx(1, "invalid process spec %c",
1087 *optarg);
1089 break;
1090 case 'v':
1091 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1092 exit(0);
1093 break;
1094 default:
1095 usage(1);
1099 argc -= optind;
1100 argv += optind;
1102 if (proc != -1) {
1103 if (argc > 0)
1104 usage(1);
1105 else if (proc == PROC_NET)
1106 return net_main();
1107 else
1108 usage(1);
1111 if (argc != 0) {
1112 has_url = 1;
1113 humanify_url(argv[0], url, sizeof(url));
1116 fs_init();
1118 /* setup keys before reading the config */
1119 TAILQ_INIT(&global_map.m);
1120 global_map.unhandled_input = global_key_unbound;
1121 TAILQ_INIT(&minibuffer_map.m);
1123 config_init();
1124 parseconfig(config_path, fail);
1125 if (configtest) {
1126 puts("config OK");
1127 exit(0);
1130 if (download_path == NULL &&
1131 (download_path = strdup("/tmp/")) == NULL)
1132 errx(1, "strdup");
1134 if (!safe_mode && (sessionfd = lock_session()) == -1) {
1135 if (has_url) {
1136 send_url(url);
1137 exit(0);
1140 errx(1, "can't lock session, is another instance of "
1141 "telescope already running?");
1144 /* Start children. */
1145 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1146 err(1, "socketpair");
1147 start_child(PROC_NET, argv0, pipe2net[1]);
1148 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1149 iev_net = &net_ibuf;
1150 iev_net->handler = handle_dispatch_imsg;
1152 setproctitle("ui");
1154 /* initialize tofu store */
1155 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1157 event_init();
1159 if (!safe_mode) {
1160 if ((control_fd = control_init(ctlsock_path)) == -1)
1161 err(1, "control_init %s", ctlsock_path);
1162 control_listen(control_fd);
1165 /* initialize the in-memory cache store */
1166 mcache_init();
1168 /* Setup event handler for the autosave */
1169 autosave_init();
1171 /* Setup event handlers for pipes to net */
1172 iev_net->events = EV_READ;
1173 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1174 iev_net->handler, iev_net);
1175 event_add(&iev_net->ev, NULL);
1177 if (ui_init()) {
1178 sandbox_ui_process();
1179 fs_load_state(&certs);
1180 operating = 1;
1181 switch_to_tab(current_tab);
1182 ui_main_loop();
1183 ui_end();
1186 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1187 imsg_flush(&iev_net->ibuf);
1189 /* wait for children to terminate */
1190 do {
1191 pid = wait(&status);
1192 if (pid == -1) {
1193 if (errno != EINTR && errno != ECHILD)
1194 err(1, "wait");
1195 } else if (WIFSIGNALED(status))
1196 warnx("child terminated; signal %d", WTERMSIG(status));
1197 } while (pid != -1 || (pid == -1 && errno == EINTR));
1199 if (!safe_mode)
1200 unlink(crashed_file);
1202 if (!safe_mode && close(sessionfd) == -1)
1203 err(1, "close(sessionfd = %d)", sessionfd);
1205 return 0;