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 "exec.h"
40 #include "fs.h"
41 #include "hist.h"
42 #include "imsgev.h"
43 #include "iri.h"
44 #include "keymap.h"
45 #include "mailcap.h"
46 #include "mcache.h"
47 #include "minibuffer.h"
48 #include "parser.h"
49 #include "parser.h"
50 #include "session.h"
51 #include "telescope.h"
52 #include "tofu.h"
53 #include "ui.h"
54 #include "utils.h"
55 #include "xwrapper.h"
57 static const struct option longopts[] = {
58 {"help", no_argument, NULL, 'h'},
59 {"safe", no_argument, NULL, 'S'},
60 {"version", no_argument, NULL, 'v'},
61 {NULL, 0, NULL, 0},
62 };
64 static const char *opts = "c:hnST:v";
66 static int has_url;
67 static char url[GEMINI_URL_LEN];
69 /*
70 * Used to know when we're finished loading.
71 */
72 int operating;
74 /*
75 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
76 * anything to the filesystem or execute external programs.
77 */
78 int safe_mode;
80 static struct imsgev *iev_net;
82 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
83 struct tabshead ktabshead = TAILQ_HEAD_INITIALIZER(ktabshead);
84 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
86 enum telescope_process {
87 PROC_UI,
88 PROC_NET,
89 };
91 #define CANNOT_FETCH 0
92 #define TOO_MANY_REDIRECTS 1
93 #define MALFORMED_RESPONSE 2
94 #define UNKNOWN_TYPE_OR_CSET 3
95 #define UNKNOWN_PROTOCOL 4
97 /* XXX: keep in sync with normalize_code */
98 const char *err_pages[70] = {
99 [CANNOT_FETCH] = "# Couldn't load the page\n",
100 [TOO_MANY_REDIRECTS] = "# Too many redirects\n",
101 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
102 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported document format or charset\n",
103 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
105 [10] = "# Input required\n",
106 [11] = "# Input required\n",
107 [40] = "# Temporary failure\n",
108 [41] = "# Server unavailable\n",
109 [42] = "# CGI error\n",
110 [43] = "# Proxy error\n",
111 [44] = "# Slow down\n",
112 [50] = "# Permanent failure\n",
113 [51] = "# Not found\n",
114 [52] = "# Gone\n",
115 [53] = "# Proxy request refused\n",
116 [59] = "# Bad request\n",
117 [60] = "# Client certificate required\n",
118 [61] = "# Certificate not authorised\n",
119 [62] = "# Certificate not valid\n"
120 };
122 static void die(void) __attribute__((__noreturn__));
123 static struct tab *tab_by_id(uint32_t);
124 static void handle_imsg_check_cert(struct imsg *);
125 static void handle_check_cert_user_choice(int, void *);
126 static void handle_maybe_save_new_cert(int, void *);
127 static void handle_maybe_save_page(int, void *);
128 static void handle_save_page_path(const char *, struct tab *);
129 static void handle_dispatch_imsg(int, int, void *);
130 static void load_about_url(struct tab *, const char *);
131 static void load_file_url(struct tab *, const char *);
132 static void load_finger_url(struct tab *, const char *);
133 static void load_gemini_url(struct tab *, const char *);
134 static void load_gopher_url(struct tab *, const char *);
135 static void load_via_proxy(struct tab *, const char *,
136 struct proxy *);
137 static void make_request(struct tab *, struct get_req *, int,
138 const char *);
139 static void do_load_url(struct tab *, const char *, const char *, int);
140 static pid_t start_child(enum telescope_process, const char *, int);
141 static void send_url(const char *);
143 static const struct proto {
144 const char *schema;
145 const char *port;
146 void (*loadfn)(struct tab *, const char *);
147 } protos[] = {
148 {"about", NULL, load_about_url},
149 {"file", NULL, load_file_url},
150 {"finger", "79", load_finger_url},
151 {"gemini", "1965", load_gemini_url},
152 {"gopher", "70", load_gopher_url},
153 {NULL, NULL, NULL},
154 };
156 static struct ohash certs;
158 static void __attribute__((__noreturn__))
159 die(void)
161 abort(); /* TODO */
164 static struct tab *
165 tab_by_id(uint32_t id)
167 struct tab *t;
169 TAILQ_FOREACH(t, &tabshead, tabs) {
170 if (t->id == id)
171 return t;
174 return NULL;
177 static void
178 handle_imsg_check_cert(struct imsg *imsg)
180 char *hash;
181 const char *host, *port;
182 int tofu_res;
183 struct ibuf ibuf;
184 struct tofu_entry *e;
185 struct tab *tab;
186 size_t datalen;
188 if (imsg_get_ibuf(imsg, &ibuf) == -1 ||
189 ibuf_borrow_str(&ibuf, &hash) == -1)
190 abort();
191 datalen = strlen(hash);
193 if ((tab = tab_by_id(imsg_get_id(imsg))) == NULL)
194 return;
196 if (tab->proxy != NULL) {
197 host = tab->proxy->host;
198 port = tab->proxy->port;
199 } else {
200 host = tab->iri.iri_host;
201 port = tab->iri.iri_portstr;
204 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
205 /* TODO: an update in libressl/libretls changed
206 * significantly. Find a better approach at storing
207 * the certs! */
208 if (datalen > sizeof(e->hash))
209 abort();
211 tofu_res = 1; /* trust on first use */
212 e = xcalloc(1, sizeof(*e));
213 strlcpy(e->domain, host, sizeof(e->domain));
214 if (*port != '\0' && strcmp(port, "1965")) {
215 strlcat(e->domain, ":", sizeof(e->domain));
216 strlcat(e->domain, port, sizeof(e->domain));
218 strlcpy(e->hash, hash, sizeof(e->hash));
219 tofu_save(&certs, e);
220 } else
221 tofu_res = !strcmp(hash, e->hash);
223 if (tofu_res) {
224 if (e->verified == -1)
225 tab->trust = TS_TEMP_TRUSTED;
226 else if (e->verified == 1)
227 tab->trust = TS_VERIFIED;
228 else
229 tab->trust = TS_TRUSTED;
231 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid, -1,
232 &tofu_res, sizeof(tofu_res));
233 } else {
234 tab->trust = TS_UNTRUSTED;
235 load_page_from_str(tab, "# Certificate mismatch\n");
236 tab->cert = xstrdup(hash);
237 ui_yornp("Certificate mismatch. Proceed?",
238 handle_check_cert_user_choice, tab);
242 static void
243 handle_check_cert_user_choice(int accept, void *d)
245 struct tab *tab = d;
247 ui_send_net(IMSG_CERT_STATUS, tab->id, -1, &accept,
248 sizeof(accept));
250 if (accept) {
251 const char *host, *port;
253 host = tab->iri.iri_host;
254 port = tab->iri.iri_portstr;
256 /*
257 * trust the certificate for this session only. If
258 * the page results in a redirect while we're asking
259 * the user to save, we'll end up with an invalid
260 * tabid (one request == one tab id). It also makes
261 * sense to save it for the current session if the
262 * user accepted it.
263 */
264 tofu_temp_trust(&certs, host, port, tab->cert);
266 if (!safe_mode)
267 ui_yornp("Save the new certificate?",
268 handle_maybe_save_new_cert, tab);
269 else
270 message("Certificate temporarly trusted");
271 } else {
272 free(tab->cert);
273 tab->cert = NULL;
277 static void
278 handle_maybe_save_new_cert(int accept, void *data)
280 struct tab *tab = data;
281 struct tofu_entry *e;
282 const char *host, *port;
284 if (tab->proxy != NULL) {
285 host = tab->proxy->host;
286 port = tab->proxy->port;
287 } else {
288 host = tab->iri.iri_host;
289 port = tab->iri.iri_portstr;
292 if (!accept)
293 goto end;
295 e = xcalloc(1, sizeof(*e));
297 strlcpy(e->domain, host, sizeof(e->domain));
298 if (*port != '\0' && strcmp(port, "1965")) {
299 strlcat(e->domain, ":", sizeof(e->domain));
300 strlcat(e->domain, port, sizeof(e->domain));
302 strlcpy(e->hash, tab->cert, sizeof(e->hash));
304 tofu_update_persist(&certs, e);
306 tab->trust = TS_TRUSTED;
308 end:
309 free(tab->cert);
310 tab->cert = NULL;
313 static inline int
314 normalize_code(int n)
316 if (n < 20) {
317 if (n == 10 || n == 11)
318 return n;
319 return 10;
320 } else if (n < 30) {
321 return 20;
322 } else if (n < 40) {
323 if (n == 30 || n == 31)
324 return n;
325 return 30;
326 } else if (n < 50) {
327 if (n <= 44)
328 return n;
329 return 40;
330 } else if (n < 60) {
331 if (n <= 53 || n == 59)
332 return n;
333 return 50;
334 } else if (n < 70) {
335 if (n <= 62)
336 return n;
337 return 60;
338 } else
339 return MALFORMED_RESPONSE;
342 static void
343 handle_request_response(struct tab *tab)
345 char buf[128];
347 if (tab->code != 30 && tab->code != 31)
348 tab->redirect_count = 0;
350 if (tab->code < 10) { /* internal errors */
351 load_page_from_str(tab, err_pages[tab->code]);
352 } else if (tab->code < 20) { /* 1x */
353 free(tab->last_input_url);
354 tab->last_input_url = xstrdup(hist_cur(tab->hist));
356 load_page_from_str(tab, err_pages[tab->code]);
357 ui_require_input(tab, tab->code == 11, ir_select_gemini);
358 } else if (tab->code == 20) {
359 history_add(hist_cur(tab->hist));
360 if (setup_parser_for(tab)) {
361 ui_send_net(IMSG_PROCEED, tab->id, -1, NULL, 0);
362 } else if (safe_mode) {
363 load_page_from_str(tab,
364 err_pages[UNKNOWN_TYPE_OR_CSET]);
365 } else {
366 hist_prev(tab->hist);
367 snprintf(buf, sizeof(buf),
368 "Can't display \"%s\", save it?", tab->meta);
369 ui_yornp(buf, handle_maybe_save_page, tab);
371 } else if (tab->code < 40) { /* 3x */
372 tab->redirect_count++;
374 /* TODO: make customizable? */
375 if (tab->redirect_count > 5) {
376 load_page_from_str(tab,
377 err_pages[TOO_MANY_REDIRECTS]);
378 } else
379 do_load_url(tab, tab->meta, hist_cur(tab->hist),
380 LU_MODE_NOCACHE);
381 } else { /* 4x, 5x & 6x */
382 load_page_from_str(tab, err_pages[tab->code]);
383 if (tab->code >= 60) {
384 cmd_use_certificate(&tab->buffer);
385 ui_force_tab_refresh(tab);
390 static void
391 handle_maybe_save_page(int dosave, void *data)
393 struct tab *tab = data;
394 const char *f;
395 char input[PATH_MAX];
397 /* XXX: this print a message that is confusing */
398 ui_on_tab_loaded(tab);
400 if (!dosave) {
401 stop_tab(tab);
402 return;
405 if ((f = strrchr(tab->iri.iri_path, '/')) == NULL)
406 f = "";
407 else
408 f++;
410 strlcpy(input, download_path, sizeof(input));
411 strlcat(input, f, sizeof(input));
413 ui_read("Save to path", handle_save_page_path, tab, input);
416 static void
417 handle_save_page_path(const char *path, struct tab *tab)
419 struct download *d;
420 int fd;
422 if (path == NULL) {
423 stop_tab(tab);
424 return;
427 if ((fd = open(path, O_WRONLY|O_TRUNC|O_CREAT, 0644)) == -1) {
428 message("Can't open file %s: %s", path, strerror(errno));
429 stop_tab(tab);
430 return;
433 ui_show_downloads_pane();
434 d = enqueue_download(tab->id, path, tab->meta);
435 d->fd = fd;
436 ui_send_net(IMSG_PROCEED, d->id, -1, NULL, 0);
438 /*
439 * Change this tab id, the old one is associated with the
440 * download now.
441 */
442 tab->id = tab_new_id();
445 static void
446 handle_dispatch_imsg(int fd, int event, void *data)
448 struct imsgev *iev = data;
449 struct imsgbuf *imsgbuf = &iev->ibuf;
450 struct imsg imsg;
451 struct ibuf ibuf;
452 struct tab *tab;
453 struct download *d;
454 const char *h;
455 char *str, *page;
456 ssize_t n;
457 int code;
459 if (event & EV_READ) {
460 if (imsgbuf_read(imsgbuf) == -1)
461 err(1, "imsg_read");
463 if (event & EV_WRITE) {
464 if (imsgbuf_write(imsgbuf) == -1)
465 err(1, "msgbuf_write");
468 for (;;) {
469 if ((n = imsg_get(imsgbuf, &imsg)) == -1)
470 err(1, "imsg_get");
471 if (n == 0)
472 break;
474 switch (imsg_get_type(&imsg)) {
475 case IMSG_ERR:
476 if ((tab = tab_by_id(imsg_get_id(&imsg))) == NULL)
477 break;
478 if (imsg_get_ibuf(&imsg, &ibuf) == -1 ||
479 ibuf_borrow_str(&ibuf, &str) == -1)
480 die();
481 xasprintf(&page, "# Error loading %s\n\n> %s\n",
482 hist_cur(tab->hist), str);
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->buffer, 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_FAULTY_GEMSERVER:
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) {
526 tab->faulty_gemserver = 1;
527 ui_on_tab_refresh(tab);
528 } else {
529 message("Download interrupted!");
531 break;
532 case IMSG_EOF:
533 if ((tab = tab_by_id(imsg_get_id(&imsg))) == NULL &&
534 ((d = download_by_id(imsg_get_id(&imsg)))) == NULL)
535 return;
537 if (tab == NULL && d != NULL) {
538 download_finished(d);
539 return;
542 if (tab != NULL) {
543 if (!parser_free(tab))
544 die();
545 h = hist_cur(tab->hist);
546 if (!strncmp(h, "gemini://", 9) ||
547 !strncmp(h, "gopher://", 9) ||
548 !strncmp(h, "finger://", 9))
549 mcache_tab(tab);
551 /*
552 * Gemini is handled as soon as a 2x
553 * reply is got.
554 */
555 if (!strncmp(h, "finger://", 9) ||
556 !strncmp(h, "gopher://", 9))
557 history_add(h);
559 ui_on_tab_refresh(tab);
560 ui_on_tab_loaded(tab);
562 break;
563 default:
564 errx(1, "got unknown imsg %d", imsg_get_type(&imsg));
567 imsg_free(&imsg);
570 imsg_event_add(iev);
573 static void
574 load_about_url(struct tab *tab, const char *url)
576 tab->trust = TS_TRUSTED;
577 fs_load_url(tab, url);
578 ui_on_tab_refresh(tab);
579 ui_on_tab_loaded(tab);
582 static void
583 load_file_url(struct tab *tab, const char *url)
585 tab->trust = TS_TRUSTED;
586 fs_load_url(tab, url);
587 ui_on_tab_refresh(tab);
588 ui_on_tab_loaded(tab);
591 static void
592 load_finger_url(struct tab *tab, const char *url)
594 struct get_req req;
595 const char *path;
597 memset(&req, 0, sizeof(req));
598 strlcpy(req.host, tab->iri.iri_host, sizeof(req.host));
599 strlcpy(req.port, tab->iri.iri_portstr, sizeof(req.port));
601 /*
602 * Sometimes the finger url have the user as path component
603 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
604 * userinfo (e.g. finger://cobradile@finger.farm).
605 */
606 if (tab->iri.iri_flags & IH_UINFO) {
607 strlcpy(req.req, tab->iri.iri_uinfo, sizeof(req.req));
608 } else {
609 path = tab->iri.iri_path;
610 while (*path == '/')
611 ++path;
612 strlcpy(req.req, path, sizeof(req.req));
614 strlcat(req.req, "\r\n", sizeof(req.req));
616 parser_init(&tab->buffer, &textplain_parser);
617 make_request(tab, &req, PROTO_FINGER, NULL);
620 static void
621 load_gemini_url(struct tab *tab, const char *url)
623 struct get_req req;
625 memset(&req, 0, sizeof(req));
626 strlcpy(req.host, tab->iri.iri_host, sizeof(req.host));
627 strlcpy(req.port, tab->iri.iri_portstr, sizeof(req.port));
629 make_request(tab, &req, PROTO_GEMINI, hist_cur(tab->hist));
632 static inline const char *
633 gopher_skip_selector(const char *path, int *ret_type)
635 *ret_type = 0;
637 if (!strcmp(path, "/") || *path == '\0') {
638 *ret_type = '1';
639 return path;
642 if (*path != '/')
643 return path;
644 path++;
646 switch (*ret_type = *path) {
647 case '0':
648 case '1':
649 case '7':
650 break;
652 default:
653 *ret_type = 0;
654 path -= 1;
655 return path;
658 return ++path;
661 static void
662 load_gopher_url(struct tab *tab, const char *url)
664 struct get_req req;
665 int type;
666 const char *path;
668 memset(&req, 0, sizeof(req));
669 strlcpy(req.host, tab->iri.iri_host, sizeof(req.host));
670 strlcpy(req.port, tab->iri.iri_portstr, sizeof(req.port));
672 path = gopher_skip_selector(tab->iri.iri_path, &type);
673 switch (type) {
674 case '0':
675 parser_init(&tab->buffer, &textplain_parser);
676 break;
677 case '1':
678 parser_init(&tab->buffer, &gophermap_parser);
679 break;
680 case '7':
681 free(tab->last_input_url);
682 tab->last_input_url = xstrdup(url);
683 ui_require_input(tab, 0, ir_select_gopher);
684 load_page_from_str(tab, err_pages[10]);
685 return;
686 default:
687 load_page_from_str(tab, "Unknown gopher selector");
688 return;
691 if (iri_urlunescape(path, req.req, sizeof(req.req)) == -1)
692 strlcpy(req.req, path, sizeof(req.req));
693 if (tab->iri.iri_flags & IH_QUERY) {
694 strlcat(req.req, "?", sizeof(req.req));
695 strlcat(req.req, tab->iri.iri_query, sizeof(req.req));
697 strlcat(req.req, "\r\n", sizeof(req.req));
699 make_request(tab, &req, PROTO_GOPHER, NULL);
702 static void
703 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
705 struct get_req req;
707 memset(&req, 0, sizeof(req));
708 strlcpy(req.host, p->host, sizeof(req.host));
709 strlcpy(req.port, p->port, sizeof(req.port));
711 tab->proxy = p;
713 make_request(tab, &req, p->proto, hist_cur(tab->hist));
716 static void
717 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
719 int use_cert = 0, fd = -1;
721 if (proto == PROTO_GEMINI) {
722 tab->client_cert = cert_for(&tab->iri, &tab->client_cert_temp);
723 use_cert = (tab->client_cert != NULL);
726 stop_tab(tab);
727 tab->id = tab_new_id();
728 tab->faulty_gemserver = 0;
729 req->proto = proto;
731 if (r != NULL) {
732 strlcpy(req->req, r, sizeof(req->req));
733 strlcat(req->req, "\r\n", sizeof(req->req));
736 start_loading_anim(tab);
738 if (!use_cert)
739 tab->client_cert = NULL;
740 if (use_cert && (fd = cert_open(tab->client_cert)) == -1) {
741 tab->client_cert = NULL;
742 message("failed to open certificate: %s", strerror(errno));
745 ui_send_net(IMSG_GET, tab->id, fd, req, sizeof(*req));
748 void
749 gopher_send_search_req(struct tab *tab, const char *text)
751 struct get_req req;
753 memset(&req, 0, sizeof(req));
754 strlcpy(req.host, tab->iri.iri_host, sizeof(req.host));
755 strlcpy(req.port, tab->iri.iri_portstr, sizeof(req.port));
757 /* +2 to skip /7 */
758 strlcpy(req.req, tab->iri.iri_path+2, sizeof(req.req));
759 if (tab->iri.iri_flags & IH_QUERY) {
760 strlcat(req.req, "?", sizeof(req.req));
761 strlcat(req.req, tab->iri.iri_query, sizeof(req.req));
764 strlcat(req.req, "\t", sizeof(req.req));
765 strlcat(req.req, text, sizeof(req.req));
766 strlcat(req.req, "\r\n", sizeof(req.req));
768 erase_buffer(&tab->buffer);
769 parser_init(&tab->buffer, &gophermap_parser);
771 make_request(tab, &req, PROTO_GOPHER, NULL);
774 void
775 load_page_from_str(struct tab *tab, const char *page)
777 parser_init(&tab->buffer, &gemtext_parser);
778 if (!parser_parse(&tab->buffer, page, strlen(page)))
779 abort();
780 if (!parser_free(tab))
781 abort();
782 ui_on_tab_refresh(tab);
783 ui_on_tab_loaded(tab);
786 static void
787 do_load_url_cmd(int res, void *d)
789 struct tab *tab = d;
790 const char *argv[3];
792 if (!res)
793 return;
795 argv[0] = DEFAULT_OPENER;
796 argv[1] = hist_cur(tab->hist);
797 argv[2] = NULL;
798 exec_cmd((char **)argv, EXEC_BACKGROUND);
799 message("Link opened with %s", DEFAULT_OPENER);
802 /*
803 * Effectively load the given url in the given tab.
804 */
805 static void
806 do_load_url(struct tab *tab, const char *url, const char *base, int mode)
808 const struct proto *p;
809 struct proxy *proxy;
810 int nocache = mode & LU_MODE_NOCACHE;
811 char *t;
812 char buf[1025];
814 tab->proxy = NULL;
815 tab->trust = TS_UNKNOWN;
817 if (iri_parse(base, url, &tab->iri) == -1) {
818 xasprintf(&t, "# error loading %s\n>%s\n", url,
819 "Can't parse the IRI");
820 hist_set_cur(tab->hist, url);
821 load_page_from_str(tab, t);
822 free(t);
823 return;
826 iri_unparse(&tab->iri, buf, sizeof(buf));
827 hist_set_cur(tab->hist, buf);
829 if (!nocache && mcache_lookup(buf, tab)) {
830 ui_on_tab_refresh(tab);
831 ui_on_tab_loaded(tab);
832 return;
835 for (p = protos; p->schema != NULL; ++p) {
836 if (!strcmp(tab->iri.iri_scheme, p->schema)) {
837 /* patch the port */
838 if (*tab->iri.iri_portstr == '\0' &&
839 p->port != NULL)
840 iri_setport(&tab->iri, p->port);
842 p->loadfn(tab, buf);
843 return;
847 TAILQ_FOREACH(proxy, &proxies, proxies) {
848 if (!strcmp(tab->iri.iri_scheme, proxy->match_proto)) {
849 load_via_proxy(tab, url, proxy);
850 return;
854 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
855 ui_yornp("Open page with "DEFAULT_OPENER"?",
856 do_load_url_cmd, tab);
859 /*
860 * Load url in tab and handle history. If a tab is marked as lazy, only
861 * prepare the url but don't load it.
862 */
863 void
864 load_url(struct tab *tab, const char *url, const char *base, int mode)
866 size_t line_off, curr_off;
867 int lazy = tab->flags & TAB_LAZY;
868 int dohist = !(mode & LU_MODE_NOHIST);
870 if (operating && lazy) {
871 tab->flags ^= TAB_LAZY;
872 lazy = 0;
873 } else if (hist_size(tab->hist) != 0) {
874 get_scroll_position(tab, &line_off, &curr_off);
875 hist_set_offs(tab->hist, line_off, curr_off);
878 if (dohist) {
879 if (hist_push(tab->hist, url) == -1) {
880 ev_break();
881 return;
884 strlcpy(tab->buffer.title, url, sizeof(tab->buffer.title));
887 if (!lazy)
888 do_load_url(tab, url, base, mode);
891 void
892 load_url_in_tab(struct tab *tab, const char *url, const char *base, int mode)
894 if (operating) {
895 autosave_hook();
896 message("Loading %s...", url);
899 if (base == NULL)
900 base = hist_cur(tab->hist);
902 load_url(tab, url, base, mode);
905 int
906 load_previous_page(struct tab *tab)
908 const char *h;
910 if ((h = hist_prev(tab->hist)) == NULL)
911 return 0;
912 do_load_url(tab, h, NULL, LU_MODE_NONE);
913 return 1;
916 int
917 load_next_page(struct tab *tab)
919 const char *h;
921 if ((h = hist_next(tab->hist)) == NULL)
922 return 0;
923 do_load_url(tab, h, NULL, LU_MODE_NONE);
924 return 1;
927 void
928 write_buffer(const char *path, struct tab *tab)
930 FILE *fp;
932 if (path == NULL)
933 return;
935 if ((fp = fopen(path, "w")) == NULL)
936 return;
937 if (!parser_serialize(&tab->buffer, fp))
938 message("Failed to save the page.");
939 fclose(fp);
942 /*
943 * Given a user-entered URL, apply some heuristics to use it if
944 * load-url-use-heuristic allows it.
946 * - if it's a proper url use it
947 * - if it starts with a `./' or a `/' assume its a file:// url
948 * - assume it's a default-protocol:// url
950 * `ret' (of which len is the size) will be filled with the resulting
951 * url.
952 */
953 void
954 humanify_url(const char *raw, const char *base, char *ret, size_t len)
956 static struct iri iri;
958 if (load_url_use_heuristic)
959 base = NULL;
961 if (iri_parse(base, raw, &iri) == 0) {
962 iri_unparse(&iri, ret, len);
963 return;
966 if (!strncmp(raw, "./", 2)) {
967 strlcpy(ret, "file://", len);
968 strlcat(ret, cwd, len);
969 strlcat(ret, "/", len);
970 strlcat(ret, raw+2, len);
971 return;
974 if (*raw == '/') {
975 strlcpy(ret, "file://", len);
976 strlcat(ret, raw, len);
977 return;
980 strlcpy(ret, default_protocol, len);
981 strlcat(ret, "://", len);
982 strlcat(ret, raw, len);
985 int
986 bookmark_page(const char *url)
988 FILE *fp;
990 if ((fp = fopen(bookmark_file, "a")) == NULL)
991 return -1;
992 fprintf(fp, "=> %s\n", url);
993 fclose(fp);
994 return 0;
997 static pid_t
998 start_child(enum telescope_process p, const char *argv0, int fd)
1000 const char *argv[5];
1001 int argc = 0;
1002 pid_t pid;
1004 switch (pid = fork()) {
1005 case -1:
1006 die();
1007 case 0:
1008 break;
1009 default:
1010 close(fd);
1011 return pid;
1014 if (dup2(fd, 3) == -1)
1015 err(1, "cannot setup imsg fd");
1017 argv[argc++] = argv0;
1018 switch (p) {
1019 case PROC_UI:
1020 errx(1, "Can't start ui process");
1021 case PROC_NET:
1022 argv[argc++] = "-Tn";
1023 break;
1026 if (safe_mode)
1027 argv[argc++] = "-S";
1029 argv[argc++] = NULL;
1030 execvp(argv0, (char *const *)argv);
1031 err(1, "execvp(%s)", argv0);
1034 static void
1035 send_url(const char *url)
1037 struct sockaddr_un sun;
1038 struct imsgbuf ibuf;
1039 int ctl_sock;
1041 if ((ctl_sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
1042 err(1, "socket");
1044 memset(&sun, 0, sizeof(sun));
1045 sun.sun_family = AF_UNIX;
1046 strlcpy(sun.sun_path, ctlsock_path, sizeof(sun.sun_path));
1048 if (connect(ctl_sock, (struct sockaddr *)&sun, sizeof(sun)) == -1)
1049 err(1, "connect: %s", ctlsock_path);
1051 if (imsgbuf_init(&ibuf, ctl_sock) == -1)
1052 err(1, "imsgbuf_init");
1053 imsg_compose(&ibuf, IMSG_CTL_OPEN_URL, 0, 0, -1, url,
1054 strlen(url) + 1);
1055 imsgbuf_flush(&ibuf);
1056 close(ctl_sock);
1059 int
1060 ui_send_net(int type, uint32_t peerid, int fd, const void *data,
1061 uint16_t datalen)
1063 return imsg_compose_event(iev_net, type, peerid, 0, fd, data,
1064 datalen);
1067 static void __attribute__((noreturn))
1068 usage(int r)
1070 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1071 getprogname());
1072 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1073 exit(r);
1076 int
1077 main(int argc, char * const *argv)
1079 struct imsgev net_ibuf;
1080 pid_t pid;
1081 int control_fd;
1082 int pipe2net[2];
1083 int ch, configtest = 0, fail = 0;
1084 int proc = -1;
1085 int sessionfd = -1;
1086 int status;
1087 const char *argv0;
1089 argv0 = argv[0];
1091 signal(SIGPIPE, SIG_IGN);
1093 if (getenv("NO_COLOR") != NULL)
1094 enable_colors = 0;
1096 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1097 switch (ch) {
1098 case 'c':
1099 fail = 1;
1100 strlcpy(config_path, optarg, sizeof(config_path));
1101 break;
1102 case 'n':
1103 configtest = 1;
1104 break;
1105 case 'h':
1106 usage(0);
1107 case 'S':
1108 safe_mode = 1;
1109 break;
1110 case 'T':
1111 switch (*optarg) {
1112 case 'n':
1113 proc = PROC_NET;
1114 break;
1115 default:
1116 errx(1, "invalid process spec %c",
1117 *optarg);
1119 break;
1120 case 'v':
1121 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1122 exit(0);
1123 break;
1124 default:
1125 usage(1);
1129 argc -= optind;
1130 argv += optind;
1132 if (proc != -1) {
1133 if (argc > 0)
1134 usage(1);
1135 else if (proc == PROC_NET)
1136 return net_main();
1137 else
1138 usage(1);
1141 /* setup keys before reading the config */
1142 TAILQ_INIT(&global_map.m);
1143 global_map.unhandled_input = global_key_unbound;
1144 TAILQ_INIT(&minibuffer_map.m);
1146 init_mailcap();
1148 if (fs_init() == -1)
1149 err(1, "fs_init failed");
1150 if (certs_init(certs_file) == -1)
1151 err(1, "certs_init failed");
1152 config_init();
1153 parseconfig(config_path, fail);
1154 if (configtest) {
1155 puts("config OK");
1156 exit(0);
1159 if (default_protocol == NULL &&
1160 (default_protocol = strdup("gemini")) == NULL)
1161 err(1, "strdup");
1163 if (download_path == NULL &&
1164 (download_path = strdup("/tmp/")) == NULL)
1165 errx(1, "strdup");
1167 if (argc != 0) {
1168 char *base;
1170 xasprintf(&base, "file://%s/", cwd);
1172 has_url = 1;
1173 humanify_url(argv[0], base, url, sizeof(url));
1175 free(base);
1178 if (!safe_mode && (sessionfd = lock_session()) == -1) {
1179 if (has_url) {
1180 send_url(url);
1181 exit(0);
1184 errx(1, "can't lock session, is another instance of "
1185 "telescope already running?");
1188 /* Start children. */
1189 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1190 err(1, "socketpair");
1191 start_child(PROC_NET, argv0, pipe2net[1]);
1192 if (imsgbuf_init(&net_ibuf.ibuf, pipe2net[0]) == -1)
1193 err(1, "imsgbuf_init");
1194 imsgbuf_allow_fdpass(&net_ibuf.ibuf);
1195 iev_net = &net_ibuf;
1196 iev_net->handler = handle_dispatch_imsg;
1198 setproctitle("ui");
1200 /* initialize tofu store */
1201 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1203 if (ev_init() == -1)
1204 err(1, "ev_init");
1206 if (!safe_mode) {
1207 if ((control_fd = control_init(ctlsock_path)) == -1)
1208 err(1, "control_init %s", ctlsock_path);
1209 control_listen(control_fd);
1212 /* initialize the in-memory cache store */
1213 mcache_init();
1215 /* Setup event handler for the autosave */
1216 autosave_init();
1218 /* Setup event handlers for pipes to net */
1219 iev_net->events = EV_READ;
1220 ev_add(iev_net->ibuf.fd, iev_net->events, iev_net->handler, iev_net);
1222 if (ui_init()) {
1223 sandbox_ui_process();
1224 load_session(&certs);
1225 if (has_url)
1226 new_tab(url, NULL, NULL);
1227 operating = 1;
1228 switch_to_tab(current_tab);
1229 ui_main_loop();
1230 ui_end();
1233 ui_send_net(IMSG_QUIT, 0, -1, NULL, 0);
1234 imsgbuf_flush(&iev_net->ibuf);
1236 /* wait for children to terminate */
1237 do {
1238 pid = wait(&status);
1239 if (pid == -1) {
1240 if (errno != EINTR && errno != ECHILD)
1241 err(1, "wait");
1242 } else if (WIFSIGNALED(status))
1243 warnx("child terminated; signal %d", WTERMSIG(status));
1244 } while (pid != -1 || (pid == -1 && errno == EINTR));
1246 if (!safe_mode)
1247 unlink(crashed_file);
1249 if (!safe_mode && close(sessionfd) == -1)
1250 err(1, "close(sessionfd = %d)", sessionfd);
1252 return 0;