Blob


1 /*
2 * Copyright (c) 2021, 2024 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/time.h>
21 #include <sys/un.h>
22 #include <sys/wait.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <getopt.h>
27 #include <limits.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
34 #include "certs.h"
35 #include "cmd.h"
36 #include "control.h"
37 #include "defaults.h"
38 #include "ev.h"
39 #include "fs.h"
40 #include "hist.h"
41 #include "imsgev.h"
42 #include "iri.h"
43 #include "keymap.h"
44 #include "mcache.h"
45 #include "minibuffer.h"
46 #include "parser.h"
47 #include "session.h"
48 #include "telescope.h"
49 #include "tofu.h"
50 #include "ui.h"
51 #include "utils.h"
53 static const struct option longopts[] = {
54 {"help", no_argument, NULL, 'h'},
55 {"safe", no_argument, NULL, 'S'},
56 {"version", no_argument, NULL, 'v'},
57 {NULL, 0, NULL, 0},
58 };
60 static const char *opts = "c:hnST:v";
62 static int has_url;
63 static char url[GEMINI_URL_LEN];
65 /*
66 * Used to know when we're finished loading.
67 */
68 int operating;
70 /*
71 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
72 * anything to the filesystem or execute external programs.
73 */
74 int safe_mode;
76 static struct imsgev *iev_net;
78 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
79 struct tabshead ktabshead = TAILQ_HEAD_INITIALIZER(ktabshead);
80 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
82 enum telescope_process {
83 PROC_UI,
84 PROC_NET,
85 };
87 #define CANNOT_FETCH 0
88 #define TOO_MANY_REDIRECTS 1
89 #define MALFORMED_RESPONSE 2
90 #define UNKNOWN_TYPE_OR_CSET 3
91 #define UNKNOWN_PROTOCOL 4
93 /* XXX: keep in sync with normalize_code */
94 const char *err_pages[70] = {
95 [CANNOT_FETCH] = "# Couldn't load the page\n",
96 [TOO_MANY_REDIRECTS] = "# Too many redirects\n",
97 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
98 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported document format or charset\n",
99 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
101 [10] = "# Input required\n",
102 [11] = "# Input required\n",
103 [40] = "# Temporary failure\n",
104 [41] = "# Server unavailable\n",
105 [42] = "# CGI error\n",
106 [43] = "# Proxy error\n",
107 [44] = "# Slow down\n",
108 [50] = "# Permanent failure\n",
109 [51] = "# Not found\n",
110 [52] = "# Gone\n",
111 [53] = "# Proxy request refused\n",
112 [59] = "# Bad request\n",
113 [60] = "# Client certificate required\n",
114 [61] = "# Certificate not authorised\n",
115 [62] = "# Certificate not valid\n"
116 };
118 static void die(void) __attribute__((__noreturn__));
119 static struct tab *tab_by_id(uint32_t);
120 static void handle_imsg_check_cert(struct imsg *);
121 static void handle_check_cert_user_choice(int, struct tab *);
122 static void handle_maybe_save_new_cert(int, struct tab *);
123 static void handle_maybe_save_page(int, struct tab *);
124 static void handle_save_page_path(const char *, struct tab *);
125 static void handle_dispatch_imsg(int, int, void *);
126 static void load_about_url(struct tab *, const char *);
127 static void load_file_url(struct tab *, const char *);
128 static void load_finger_url(struct tab *, const char *);
129 static void load_gemini_url(struct tab *, const char *);
130 static void load_gopher_url(struct tab *, const char *);
131 static void load_via_proxy(struct tab *, const char *,
132 struct proxy *);
133 static void make_request(struct tab *, struct get_req *, int,
134 const char *);
135 static void do_load_url(struct tab *, const char *, const char *, int);
136 static pid_t start_child(enum telescope_process, const char *, int);
137 static void send_url(const char *);
139 static const struct proto {
140 const char *schema;
141 const char *port;
142 void (*loadfn)(struct tab *, const char *);
143 } protos[] = {
144 {"about", NULL, load_about_url},
145 {"file", NULL, load_file_url},
146 {"finger", "79", load_finger_url},
147 {"gemini", "1965", load_gemini_url},
148 {"gopher", "70", load_gopher_url},
149 {NULL, NULL, NULL},
150 };
152 static struct ohash certs;
154 static void __attribute__((__noreturn__))
155 die(void)
157 abort(); /* TODO */
160 static struct tab *
161 tab_by_id(uint32_t id)
163 struct tab *t;
165 TAILQ_FOREACH(t, &tabshead, tabs) {
166 if (t->id == id)
167 return t;
170 return NULL;
173 static void
174 handle_imsg_check_cert(struct imsg *imsg)
176 char *hash;
177 const char *host, *port;
178 int tofu_res;
179 struct ibuf ibuf;
180 struct tofu_entry *e;
181 struct tab *tab;
182 size_t datalen;
184 if (imsg_get_ibuf(imsg, &ibuf) == -1 ||
185 ibuf_borrow_str(&ibuf, &hash) == -1)
186 abort();
187 datalen = strlen(hash);
189 if ((tab = tab_by_id(imsg_get_id(imsg))) == NULL)
190 return;
192 if (tab->proxy != NULL) {
193 host = tab->proxy->host;
194 port = tab->proxy->port;
195 } else {
196 host = tab->iri.iri_host;
197 port = tab->iri.iri_portstr;
200 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
201 /* TODO: an update in libressl/libretls changed
202 * significantly. Find a better approach at storing
203 * the certs! */
204 if (datalen > sizeof(e->hash))
205 abort();
207 tofu_res = 1; /* trust on first use */
208 if ((e = calloc(1, sizeof(*e))) == NULL)
209 abort();
210 strlcpy(e->domain, host, sizeof(e->domain));
211 if (*port != '\0' && strcmp(port, "1965")) {
212 strlcat(e->domain, ":", sizeof(e->domain));
213 strlcat(e->domain, port, sizeof(e->domain));
215 strlcpy(e->hash, hash, sizeof(e->hash));
216 tofu_save(&certs, e);
217 } else
218 tofu_res = !strcmp(hash, e->hash);
220 if (tofu_res) {
221 if (e->verified == -1)
222 tab->trust = TS_TEMP_TRUSTED;
223 else if (e->verified == 1)
224 tab->trust = TS_VERIFIED;
225 else
226 tab->trust = TS_TRUSTED;
228 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid, -1,
229 &tofu_res, sizeof(tofu_res));
230 } else {
231 tab->trust = TS_UNTRUSTED;
232 load_page_from_str(tab, "# Certificate mismatch\n");
233 if ((tab->cert = strdup(hash)) == NULL)
234 die();
235 ui_yornp("Certificate mismatch. Proceed?",
236 handle_check_cert_user_choice, tab);
240 static void
241 handle_check_cert_user_choice(int accept, struct tab *tab)
243 ui_send_net(IMSG_CERT_STATUS, tab->id, -1, &accept,
244 sizeof(accept));
246 if (accept) {
247 const char *host, *port;
249 host = tab->iri.iri_host;
250 port = tab->iri.iri_portstr;
252 /*
253 * trust the certificate for this session only. If
254 * the page results in a redirect while we're asking
255 * the user to save, we'll end up with an invalid
256 * tabid (one request == one tab id). It also makes
257 * sense to save it for the current session if the
258 * user accepted it.
259 */
260 tofu_temp_trust(&certs, host, port, tab->cert);
262 if (!safe_mode)
263 ui_yornp("Save the new certificate?",
264 handle_maybe_save_new_cert, tab);
265 else
266 message("Certificate temporarly trusted");
267 } else {
268 free(tab->cert);
269 tab->cert = NULL;
273 static void
274 handle_maybe_save_new_cert(int accept, struct tab *tab)
276 struct tofu_entry *e;
277 const char *host, *port;
279 if (tab->proxy != NULL) {
280 host = tab->proxy->host;
281 port = tab->proxy->port;
282 } else {
283 host = tab->iri.iri_host;
284 port = tab->iri.iri_portstr;
287 if (!accept)
288 goto end;
290 if ((e = calloc(1, sizeof(*e))) == NULL)
291 die();
293 strlcpy(e->domain, host, sizeof(e->domain));
294 if (*port != '\0' && strcmp(port, "1965")) {
295 strlcat(e->domain, ":", sizeof(e->domain));
296 strlcat(e->domain, port, sizeof(e->domain));
298 strlcpy(e->hash, tab->cert, sizeof(e->hash));
300 tofu_update_persist(&certs, e);
302 tab->trust = TS_TRUSTED;
304 end:
305 free(tab->cert);
306 tab->cert = NULL;
309 static inline int
310 normalize_code(int n)
312 if (n < 20) {
313 if (n == 10 || n == 11)
314 return n;
315 return 10;
316 } else if (n < 30) {
317 return 20;
318 } else if (n < 40) {
319 if (n == 30 || n == 31)
320 return n;
321 return 30;
322 } else if (n < 50) {
323 if (n <= 44)
324 return n;
325 return 40;
326 } else if (n < 60) {
327 if (n <= 53 || n == 59)
328 return n;
329 return 50;
330 } else if (n < 70) {
331 if (n <= 62)
332 return n;
333 return 60;
334 } else
335 return MALFORMED_RESPONSE;
338 static void
339 handle_request_response(struct tab *tab)
341 char buf[128];
343 if (tab->code != 30 && tab->code != 31)
344 tab->redirect_count = 0;
346 if (tab->code < 10) { /* internal errors */
347 load_page_from_str(tab, err_pages[tab->code]);
348 } else if (tab->code < 20) { /* 1x */
349 free(tab->last_input_url);
350 tab->last_input_url = strdup(hist_cur(tab->hist));
351 if (tab->last_input_url == NULL)
352 die();
354 load_page_from_str(tab, err_pages[tab->code]);
355 ui_require_input(tab, tab->code == 11, ir_select_gemini);
356 } else if (tab->code == 20) {
357 history_add(hist_cur(tab->hist));
358 if (setup_parser_for(tab)) {
359 ui_send_net(IMSG_PROCEED, tab->id, -1, NULL, 0);
360 } else if (safe_mode) {
361 load_page_from_str(tab,
362 err_pages[UNKNOWN_TYPE_OR_CSET]);
363 } else {
364 hist_prev(tab->hist);
365 snprintf(buf, sizeof(buf),
366 "Can't display \"%s\", save it?", tab->meta);
367 ui_yornp(buf, handle_maybe_save_page, tab);
369 } else if (tab->code < 40) { /* 3x */
370 tab->redirect_count++;
372 /* TODO: make customizable? */
373 if (tab->redirect_count > 5) {
374 load_page_from_str(tab,
375 err_pages[TOO_MANY_REDIRECTS]);
376 } else
377 do_load_url(tab, tab->meta, hist_cur(tab->hist),
378 LU_MODE_NOCACHE);
379 } else { /* 4x, 5x & 6x */
380 load_page_from_str(tab, err_pages[tab->code]);
381 if (tab->code >= 60)
382 cmd_use_certificate(&tab->buffer);
386 static void
387 handle_maybe_save_page(int dosave, struct tab *tab)
389 const char *f;
390 char input[PATH_MAX];
392 /* XXX: this print a message that is confusing */
393 ui_on_tab_loaded(tab);
395 if (!dosave) {
396 stop_tab(tab);
397 return;
400 if ((f = strrchr(tab->iri.iri_path, '/')) == NULL)
401 f = "";
402 else
403 f++;
405 strlcpy(input, download_path, sizeof(input));
406 strlcat(input, f, sizeof(input));
408 ui_read("Save to path", handle_save_page_path, tab, input);
411 static void
412 handle_save_page_path(const char *path, struct tab *tab)
414 struct download *d;
415 int fd;
417 if (path == NULL) {
418 stop_tab(tab);
419 return;
422 if ((fd = open(path, O_WRONLY|O_TRUNC|O_CREAT, 0644)) == -1) {
423 message("Can't open file %s: %s", path, strerror(errno));
424 stop_tab(tab);
425 return;
428 ui_show_downloads_pane();
429 d = enqueue_download(tab->id, path);
430 d->fd = fd;
431 ui_send_net(IMSG_PROCEED, d->id, -1, NULL, 0);
433 /*
434 * Change this tab id, the old one is associated with the
435 * download now.
436 */
437 tab->id = tab_new_id();
440 static void
441 handle_dispatch_imsg(int fd, int event, void *data)
443 struct imsgev *iev = data;
444 struct imsgbuf *imsgbuf = &iev->ibuf;
445 struct imsg imsg;
446 struct ibuf ibuf;
447 struct tab *tab;
448 struct download *d;
449 const char *h;
450 char *str, *page;
451 ssize_t n;
452 int code;
454 if (event & EV_READ) {
455 if ((n = imsg_read(imsgbuf)) == -1 && errno != EAGAIN)
456 err(1, "imsg_read");
457 if (n == 0)
458 err(1, "connection closed");
460 if (event & EV_WRITE) {
461 if ((n = msgbuf_write(&imsgbuf->w)) == -1 && errno != EAGAIN)
462 err(1, "msgbuf_write");
463 if (n == 0)
464 err(1, "connection closed");
467 for (;;) {
468 if ((n = imsg_get(imsgbuf, &imsg)) == -1)
469 err(1, "imsg_get");
470 if (n == 0)
471 break;
473 switch (imsg_get_type(&imsg)) {
474 case IMSG_ERR:
475 if ((tab = tab_by_id(imsg_get_id(&imsg))) == NULL)
476 break;
477 if (imsg_get_ibuf(&imsg, &ibuf) == -1 ||
478 ibuf_borrow_str(&ibuf, &str) == -1)
479 die();
480 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
481 hist_cur(tab->hist), str) == -1)
482 die();
483 load_page_from_str(tab, page);
484 free(page);
485 break;
486 case IMSG_CHECK_CERT:
487 handle_imsg_check_cert(&imsg);
488 break;
489 case IMSG_REPLY:
490 if ((tab = tab_by_id(imsg_get_id(&imsg))) == NULL)
491 break;
492 if (imsg_get_ibuf(&imsg, &ibuf) == -1 ||
493 ibuf_get(&ibuf, &code, sizeof(code)) == -1 ||
494 ibuf_borrow_str(&ibuf, &str) == -1)
495 die();
496 if (strlcpy(tab->meta, str, sizeof(tab->meta)) >=
497 sizeof(tab->meta))
498 die();
499 tab->code = normalize_code(code);
500 handle_request_response(tab);
501 break;
502 case IMSG_BUF:
503 if ((tab = tab_by_id(imsg_get_id(&imsg))) == NULL &&
504 ((d = download_by_id(imsg_get_id(&imsg)))) == NULL)
505 return;
507 if (tab) {
508 if (!parser_parse(tab, imsg.data,
509 imsg_get_len(&imsg)))
510 die();
511 ui_on_tab_refresh(tab);
512 } else {
513 size_t datalen = imsg_get_len(&imsg);
515 d->bytes += datalen;
516 write(d->fd, imsg.data, datalen);
517 ui_on_download_refresh();
519 break;
520 case IMSG_EOF:
521 if ((tab = tab_by_id(imsg_get_id(&imsg))) == NULL &&
522 ((d = download_by_id(imsg_get_id(&imsg)))) == NULL)
523 return;
525 if (tab != NULL) {
526 if (!parser_free(tab))
527 die();
528 h = hist_cur(tab->hist);
529 if (!strncmp(h, "gemini://", 9) ||
530 !strncmp(h, "gopher://", 9) ||
531 !strncmp(h, "finger://", 9))
532 mcache_tab(tab);
534 /*
535 * Gemini is handled as soon as a 2x
536 * reply is got.
537 */
538 if (!strncmp(h, "finger://", 9) ||
539 !strncmp(h, "gopher://", 9))
540 history_add(h);
542 ui_on_tab_refresh(tab);
543 ui_on_tab_loaded(tab);
544 } else {
545 close(d->fd);
546 d->fd = -1;
547 ui_on_download_refresh();
549 break;
550 default:
551 errx(1, "got unknown imsg %d", imsg_get_type(&imsg));
554 imsg_free(&imsg);
557 imsg_event_add(iev);
560 static void
561 load_about_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);
569 static void
570 load_file_url(struct tab *tab, const char *url)
572 tab->trust = TS_TRUSTED;
573 fs_load_url(tab, url);
574 ui_on_tab_refresh(tab);
575 ui_on_tab_loaded(tab);
578 static void
579 load_finger_url(struct tab *tab, const char *url)
581 struct get_req req;
582 const char *path;
584 memset(&req, 0, sizeof(req));
585 strlcpy(req.host, tab->iri.iri_host, sizeof(req.host));
586 strlcpy(req.port, tab->iri.iri_portstr, sizeof(req.port));
588 /*
589 * Sometimes the finger url have the user as path component
590 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
591 * userinfo (e.g. finger://cobradile@finger.farm).
592 */
593 if (tab->iri.iri_flags & IH_UINFO) {
594 strlcpy(req.req, tab->iri.iri_uinfo, sizeof(req.req));
595 } else {
596 path = tab->iri.iri_path;
597 while (*path == '/')
598 ++path;
599 strlcpy(req.req, path, sizeof(req.req));
601 strlcat(req.req, "\r\n", sizeof(req.req));
603 parser_init(tab, textplain_initparser);
604 make_request(tab, &req, PROTO_FINGER, NULL);
607 static void
608 load_gemini_url(struct tab *tab, const char *url)
610 struct get_req req;
612 memset(&req, 0, sizeof(req));
613 strlcpy(req.host, tab->iri.iri_host, sizeof(req.host));
614 strlcpy(req.port, tab->iri.iri_portstr, sizeof(req.port));
616 make_request(tab, &req, PROTO_GEMINI, hist_cur(tab->hist));
619 static inline const char *
620 gopher_skip_selector(const char *path, int *ret_type)
622 *ret_type = 0;
624 if (!strcmp(path, "/") || *path == '\0') {
625 *ret_type = '1';
626 return path;
629 if (*path != '/')
630 return path;
631 path++;
633 switch (*ret_type = *path) {
634 case '0':
635 case '1':
636 case '7':
637 break;
639 default:
640 *ret_type = 0;
641 path -= 1;
642 return path;
645 return ++path;
648 static void
649 load_gopher_url(struct tab *tab, const char *url)
651 struct get_req req;
652 int type;
653 const char *path;
655 memset(&req, 0, sizeof(req));
656 strlcpy(req.host, tab->iri.iri_host, sizeof(req.host));
657 strlcpy(req.port, tab->iri.iri_portstr, sizeof(req.port));
659 path = gopher_skip_selector(tab->iri.iri_path, &type);
660 switch (type) {
661 case '0':
662 parser_init(tab, textplain_initparser);
663 break;
664 case '1':
665 parser_init(tab, gophermap_initparser);
666 break;
667 case '7':
668 free(tab->last_input_url);
669 tab->last_input_url = strdup(url);
670 if (tab->last_input_url == NULL)
671 die();
672 ui_require_input(tab, 0, ir_select_gopher);
673 load_page_from_str(tab, err_pages[10]);
674 return;
675 default:
676 load_page_from_str(tab, "Unknown gopher selector");
677 return;
680 if (iri_urlunescape(path, req.req, sizeof(req.req)) == -1)
681 strlcpy(req.req, path, sizeof(req.req));
682 if (tab->iri.iri_flags & IH_QUERY) {
683 strlcat(req.req, "?", sizeof(req.req));
684 strlcat(req.req, tab->iri.iri_query, sizeof(req.req));
686 strlcat(req.req, "\r\n", sizeof(req.req));
688 make_request(tab, &req, PROTO_GOPHER, NULL);
691 static void
692 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
694 struct get_req req;
696 memset(&req, 0, sizeof(req));
697 strlcpy(req.host, p->host, sizeof(req.host));
698 strlcpy(req.port, p->port, sizeof(req.port));
700 tab->proxy = p;
702 make_request(tab, &req, p->proto, hist_cur(tab->hist));
705 static void
706 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
708 int use_cert = 0, fd = -1;
710 if (proto == PROTO_GEMINI) {
711 tab->client_cert = cert_for(&tab->iri, &tab->client_cert_temp);
712 use_cert = (tab->client_cert != NULL);
715 stop_tab(tab);
716 tab->id = tab_new_id();
717 req->proto = proto;
719 if (r != NULL) {
720 strlcpy(req->req, r, sizeof(req->req));
721 strlcat(req->req, "\r\n", sizeof(req->req));
724 start_loading_anim(tab);
726 if (!use_cert)
727 tab->client_cert = NULL;
728 if (use_cert && (fd = cert_open(tab->client_cert)) == -1) {
729 tab->client_cert = NULL;
730 message("failed to open certificate: %s", strerror(errno));
733 ui_send_net(IMSG_GET, tab->id, fd, req, sizeof(*req));
736 void
737 gopher_send_search_req(struct tab *tab, const char *text)
739 struct get_req req;
741 memset(&req, 0, sizeof(req));
742 strlcpy(req.host, tab->iri.iri_host, sizeof(req.host));
743 strlcpy(req.port, tab->iri.iri_portstr, sizeof(req.port));
745 /* +2 to skip /7 */
746 strlcpy(req.req, tab->iri.iri_path+2, sizeof(req.req));
747 if (tab->iri.iri_flags & IH_QUERY) {
748 strlcat(req.req, "?", sizeof(req.req));
749 strlcat(req.req, tab->iri.iri_query, sizeof(req.req));
752 strlcat(req.req, "\t", sizeof(req.req));
753 strlcat(req.req, text, sizeof(req.req));
754 strlcat(req.req, "\r\n", sizeof(req.req));
756 erase_buffer(&tab->buffer);
757 parser_init(tab, gophermap_initparser);
759 make_request(tab, &req, PROTO_GOPHER, NULL);
762 void
763 load_page_from_str(struct tab *tab, const char *page)
765 parser_init(tab, gemtext_initparser);
766 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
767 abort();
768 if (!tab->buffer.page.free(&tab->buffer.page))
769 abort();
770 ui_on_tab_refresh(tab);
771 ui_on_tab_loaded(tab);
774 /*
775 * Effectively load the given url in the given tab.
776 */
777 static void
778 do_load_url(struct tab *tab, const char *url, const char *base, int mode)
780 const struct proto *p;
781 struct proxy *proxy;
782 int nocache = mode & LU_MODE_NOCACHE;
783 char *t;
784 char buf[1025];
786 tab->proxy = NULL;
787 tab->trust = TS_UNKNOWN;
789 if (iri_parse(base, url, &tab->iri) == -1) {
790 if (asprintf(&t, "# error loading %s\n>%s\n",
791 url, "Can't parse the IRI") == -1)
792 die();
793 hist_set_cur(tab->hist, url);
794 load_page_from_str(tab, t);
795 free(t);
796 return;
799 iri_unparse(&tab->iri, buf, sizeof(buf));
800 hist_set_cur(tab->hist, buf);
802 if (!nocache && mcache_lookup(buf, tab)) {
803 ui_on_tab_refresh(tab);
804 ui_on_tab_loaded(tab);
805 return;
808 for (p = protos; p->schema != NULL; ++p) {
809 if (!strcmp(tab->iri.iri_scheme, p->schema)) {
810 /* patch the port */
811 if (*tab->iri.iri_portstr == '\0' &&
812 p->port != NULL)
813 iri_setport(&tab->iri, p->port);
815 p->loadfn(tab, buf);
816 return;
820 TAILQ_FOREACH(proxy, &proxies, proxies) {
821 if (!strcmp(tab->iri.iri_scheme, proxy->match_proto)) {
822 load_via_proxy(tab, url, proxy);
823 return;
827 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
830 /*
831 * Load url in tab and handle history. If a tab is marked as lazy, only
832 * prepare the url but don't load it.
833 */
834 void
835 load_url(struct tab *tab, const char *url, const char *base, int mode)
837 size_t line_off, curr_off;
838 int lazy = tab->flags & TAB_LAZY;
839 int dohist = !(mode & LU_MODE_NOHIST);
841 if (operating && lazy) {
842 tab->flags ^= TAB_LAZY;
843 lazy = 0;
844 } else if (hist_size(tab->hist) != 0) {
845 get_scroll_position(tab, &line_off, &curr_off);
846 hist_set_offs(tab->hist, line_off, curr_off);
849 if (dohist) {
850 if (hist_push(tab->hist, url) == -1) {
851 ev_break();
852 return;
855 strlcpy(tab->buffer.page.title, url,
856 sizeof(tab->buffer.page.title));
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 if (base == NULL)
872 base = hist_cur(tab->hist);
874 load_url(tab, url, base, mode);
877 int
878 load_previous_page(struct tab *tab)
880 const char *h;
882 if ((h = hist_prev(tab->hist)) == NULL)
883 return 0;
884 do_load_url(tab, h, NULL, LU_MODE_NONE);
885 return 1;
888 int
889 load_next_page(struct tab *tab)
891 const char *h;
893 if ((h = hist_next(tab->hist)) == NULL)
894 return 0;
895 do_load_url(tab, 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 if
916 * load-url-use-heuristic allows it.
918 * - if it's a proper url use it
919 * - if it starts with a `./' or a `/' assume its a file:// url
920 * - assume it's a default-protocol:// url
922 * `ret' (of which len is the size) will be filled with the resulting
923 * url.
924 */
925 void
926 humanify_url(const char *raw, const char *base, char *ret, size_t len)
928 static struct iri iri;
930 if (load_url_use_heuristic)
931 base = NULL;
933 if (iri_parse(base, raw, &iri) == 0) {
934 iri_unparse(&iri, ret, len);
935 return;
938 if (!strncmp(raw, "./", 2)) {
939 strlcpy(ret, "file://", len);
940 strlcat(ret, cwd, len);
941 strlcat(ret, "/", len);
942 strlcat(ret, raw+2, len);
943 return;
946 if (*raw == '/') {
947 strlcpy(ret, "file://", len);
948 strlcat(ret, raw, len);
949 return;
952 strlcpy(ret, default_protocol, len);
953 strlcat(ret, "://", len);
954 strlcat(ret, raw, len);
957 int
958 bookmark_page(const char *url)
960 FILE *fp;
962 if ((fp = fopen(bookmark_file, "a")) == NULL)
963 return -1;
964 fprintf(fp, "=> %s\n", url);
965 fclose(fp);
966 return 0;
969 static pid_t
970 start_child(enum telescope_process p, const char *argv0, int fd)
972 const char *argv[5];
973 int argc = 0;
974 pid_t pid;
976 switch (pid = fork()) {
977 case -1:
978 die();
979 case 0:
980 break;
981 default:
982 close(fd);
983 return pid;
986 if (dup2(fd, 3) == -1)
987 err(1, "cannot setup imsg fd");
989 argv[argc++] = argv0;
990 switch (p) {
991 case PROC_UI:
992 errx(1, "Can't start ui process");
993 case PROC_NET:
994 argv[argc++] = "-Tn";
995 break;
998 if (safe_mode)
999 argv[argc++] = "-S";
1001 argv[argc++] = NULL;
1002 execvp(argv0, (char *const *)argv);
1003 err(1, "execvp(%s)", argv0);
1006 static void
1007 send_url(const char *url)
1009 struct sockaddr_un sun;
1010 struct imsgbuf ibuf;
1011 int ctl_sock;
1013 if ((ctl_sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
1014 err(1, "socket");
1016 memset(&sun, 0, sizeof(sun));
1017 sun.sun_family = AF_UNIX;
1018 strlcpy(sun.sun_path, ctlsock_path, sizeof(sun.sun_path));
1020 if (connect(ctl_sock, (struct sockaddr *)&sun, sizeof(sun)) == -1)
1021 err(1, "connect: %s", ctlsock_path);
1023 imsg_init(&ibuf, ctl_sock);
1024 imsg_compose(&ibuf, IMSG_CTL_OPEN_URL, 0, 0, -1, url,
1025 strlen(url) + 1);
1026 imsg_flush(&ibuf);
1027 close(ctl_sock);
1030 int
1031 ui_send_net(int type, uint32_t peerid, int fd, const void *data,
1032 uint16_t datalen)
1034 return imsg_compose_event(iev_net, type, peerid, 0, fd, data,
1035 datalen);
1038 static void __attribute__((noreturn))
1039 usage(int r)
1041 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1042 getprogname());
1043 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1044 exit(r);
1047 int
1048 main(int argc, char * const *argv)
1050 struct imsgev net_ibuf;
1051 pid_t pid;
1052 int control_fd;
1053 int pipe2net[2];
1054 int ch, configtest = 0, fail = 0;
1055 int proc = -1;
1056 int sessionfd = -1;
1057 int status;
1058 const char *argv0;
1060 argv0 = argv[0];
1062 signal(SIGCHLD, SIG_IGN);
1063 signal(SIGPIPE, SIG_IGN);
1065 if (getenv("NO_COLOR") != NULL)
1066 enable_colors = 0;
1068 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1069 switch (ch) {
1070 case 'c':
1071 fail = 1;
1072 strlcpy(config_path, optarg, sizeof(config_path));
1073 break;
1074 case 'n':
1075 configtest = 1;
1076 break;
1077 case 'h':
1078 usage(0);
1079 case 'S':
1080 safe_mode = 1;
1081 break;
1082 case 'T':
1083 switch (*optarg) {
1084 case 'n':
1085 proc = PROC_NET;
1086 break;
1087 default:
1088 errx(1, "invalid process spec %c",
1089 *optarg);
1091 break;
1092 case 'v':
1093 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1094 exit(0);
1095 break;
1096 default:
1097 usage(1);
1101 argc -= optind;
1102 argv += optind;
1104 if (proc != -1) {
1105 if (argc > 0)
1106 usage(1);
1107 else if (proc == PROC_NET)
1108 return net_main();
1109 else
1110 usage(1);
1113 /* setup keys before reading the config */
1114 TAILQ_INIT(&global_map.m);
1115 global_map.unhandled_input = global_key_unbound;
1116 TAILQ_INIT(&minibuffer_map.m);
1118 if (fs_init() == -1)
1119 err(1, "fs_init failed");
1120 if (certs_init(certs_file) == -1)
1121 err(1, "certs_init failed");
1122 config_init();
1123 parseconfig(config_path, fail);
1124 if (configtest) {
1125 puts("config OK");
1126 exit(0);
1129 if (default_protocol == NULL &&
1130 (default_protocol = strdup("gemini")) == NULL)
1131 err(1, "strdup");
1133 if (download_path == NULL &&
1134 (download_path = strdup("/tmp/")) == NULL)
1135 errx(1, "strdup");
1137 if (argc != 0) {
1138 char *base;
1140 if (asprintf(&base, "file://%s/", cwd) == -1)
1141 err(1, "asprintf");
1143 has_url = 1;
1144 humanify_url(argv[0], base, url, sizeof(url));
1146 free(base);
1149 if (!safe_mode && (sessionfd = lock_session()) == -1) {
1150 if (has_url) {
1151 send_url(url);
1152 exit(0);
1155 errx(1, "can't lock session, is another instance of "
1156 "telescope already running?");
1159 /* Start children. */
1160 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1161 err(1, "socketpair");
1162 start_child(PROC_NET, argv0, pipe2net[1]);
1163 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1164 iev_net = &net_ibuf;
1165 iev_net->handler = handle_dispatch_imsg;
1167 setproctitle("ui");
1169 /* initialize tofu store */
1170 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1172 if (ev_init() == -1)
1173 err(1, "ev_init");
1175 if (!safe_mode) {
1176 if ((control_fd = control_init(ctlsock_path)) == -1)
1177 err(1, "control_init %s", ctlsock_path);
1178 control_listen(control_fd);
1181 /* initialize the in-memory cache store */
1182 mcache_init();
1184 /* Setup event handler for the autosave */
1185 autosave_init();
1187 /* Setup event handlers for pipes to net */
1188 iev_net->events = EV_READ;
1189 ev_add(iev_net->ibuf.fd, iev_net->events, iev_net->handler, iev_net);
1191 if (ui_init()) {
1192 sandbox_ui_process();
1193 load_session(&certs);
1194 if (has_url)
1195 new_tab(url, NULL, NULL);
1196 operating = 1;
1197 switch_to_tab(current_tab);
1198 ui_main_loop();
1199 ui_end();
1202 ui_send_net(IMSG_QUIT, 0, -1, NULL, 0);
1203 imsg_flush(&iev_net->ibuf);
1205 /* wait for children to terminate */
1206 do {
1207 pid = wait(&status);
1208 if (pid == -1) {
1209 if (errno != EINTR && errno != ECHILD)
1210 err(1, "wait");
1211 } else if (WIFSIGNALED(status))
1212 warnx("child terminated; signal %d", WTERMSIG(status));
1213 } while (pid != -1 || (pid == -1 && errno == EINTR));
1215 if (!safe_mode)
1216 unlink(crashed_file);
1218 if (!safe_mode && close(sessionfd) == -1)
1219 err(1, "close(sessionfd = %d)", sessionfd);
1221 return 0;