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/wait.h>
22 #include <errno.h>
23 #include <getopt.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
30 #include "defaults.h"
31 #include "fs.h"
32 #include "minibuffer.h"
33 #include "parser.h"
34 #include "session.h"
35 #include "telescope.h"
36 #include "ui.h"
38 static struct option longopts[] = {
39 {"colors", no_argument, NULL, 'C'},
40 {"colours", no_argument, NULL, 'C'},
41 {"help", no_argument, NULL, 'h'},
42 {"safe", no_argument, NULL, 'S'},
43 {"version", no_argument, NULL, 'v'},
44 {NULL, 0, NULL, 0},
45 };
47 static const char *opts = "Cc:hnST:v";
49 static int has_url;
50 static char url[GEMINI_URL_LEN];
52 /*
53 * Used to know when we're finished loading.
54 */
55 int operating;
57 /*
58 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
59 * anything to the filesystem or execute external programs.
60 */
61 int safe_mode;
63 static struct imsgev *iev_fs, *iev_net;
65 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
66 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
68 enum telescope_process {
69 PROC_UI,
70 PROC_FS,
71 PROC_NET,
72 };
74 #define CANNOT_FETCH 0
75 #define TOO_MUCH_REDIRECTS 1
76 #define MALFORMED_RESPONSE 2
77 #define UNKNOWN_TYPE_OR_CSET 3
78 #define UNKNOWN_PROTOCOL 4
80 /* XXX: keep in sync with normalize_code */
81 const char *err_pages[70] = {
82 [CANNOT_FETCH] = "# Couldn't load the page\n",
83 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
84 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
85 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
86 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
88 [10] = "# Input required\n",
89 [11] = "# Input required\n",
90 [40] = "# Temporary failure\n",
91 [41] = "# Server unavailable\n",
92 [42] = "# CGI error\n",
93 [43] = "# Proxy error\n",
94 [44] = "# Slow down\n",
95 [50] = "# Permanent failure\n",
96 [51] = "# Not found\n",
97 [52] = "# Gone\n",
98 [53] = "# Proxy request refused\n",
99 [59] = "# Bad request\n",
100 [60] = "# Client certificate required\n",
101 [61] = "# Certificate not authorised\n",
102 [62] = "# Certificate not valid\n"
103 };
105 static void die(void) __attribute__((__noreturn__));
106 static struct tab *tab_by_id(uint32_t);
107 static void handle_imsg_err(struct imsg *, size_t);
108 static void handle_imsg_check_cert(struct imsg *, size_t);
109 static void handle_check_cert_user_choice(int, struct tab *);
110 static void handle_maybe_save_new_cert(int, struct tab *);
111 static void handle_imsg_got_code(struct imsg *, size_t);
112 static void handle_imsg_got_meta(struct imsg *, size_t);
113 static void handle_maybe_save_page(int, struct tab *);
114 static void handle_save_page_path(const char *, struct tab *);
115 static void handle_imsg_file_opened(struct imsg *, size_t);
116 static void handle_imsg_buf(struct imsg *, size_t);
117 static void handle_imsg_eof(struct imsg *, size_t);
118 static void handle_imsg_tofu(struct imsg *, size_t);
119 static void handle_imsg_bookmark_ok(struct imsg *, size_t);
120 static void handle_imsg_save_cert_ok(struct imsg *, size_t);
121 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
122 static void handle_imsg_session(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 make_fs_request(struct tab *, int, const char *);
134 static int do_load_url(struct tab *, const char *, const char *);
135 static pid_t start_child(enum telescope_process, const char *, int);
137 static 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 [IMSG_TOFU] = handle_imsg_tofu,
158 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
159 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
160 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
161 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
162 [IMSG_SESSION_TAB] = handle_imsg_session,
163 [IMSG_SESSION_TAB_HIST] = handle_imsg_session,
164 [IMSG_SESSION_END] = handle_imsg_session,
165 };
167 static struct ohash certs;
169 static void __attribute__((__noreturn__))
170 die(void)
172 abort(); /* TODO */
175 static struct tab *
176 tab_by_id(uint32_t id)
178 struct tab *t;
180 TAILQ_FOREACH(t, &tabshead, tabs) {
181 if (t->id == id)
182 return t;
185 return NULL;
188 static void
189 handle_imsg_err(struct imsg *imsg, size_t datalen)
191 struct tab *tab;
192 char *page;
194 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
195 return;
197 page = imsg->data;
198 page[datalen-1] = '\0';
200 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
201 tab->hist_cur->h, page) == -1)
202 die();
203 load_page_from_str(tab, page);
204 free(page);
207 static void
208 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
210 const char *hash, *host, *port;
211 int tofu_res;
212 struct tofu_entry *e;
213 struct tab *tab;
215 hash = imsg->data;
216 if (hash[datalen-1] != '\0')
217 abort();
219 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
220 return;
222 if (tab->proxy != NULL) {
223 host = tab->proxy->host;
224 port = tab->proxy->port;
225 } else {
226 host = tab->uri.host;
227 port = tab->uri.port;
230 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
231 /* TODO: an update in libressl/libretls changed
232 * significantly. Find a better approach at storing
233 * the certs! */
234 if (datalen > sizeof(e->hash))
235 abort();
237 tofu_res = 1; /* trust on first use */
238 if ((e = calloc(1, sizeof(*e))) == NULL)
239 abort();
240 strlcpy(e->domain, host, sizeof(e->domain));
241 if (*port != '\0' && strcmp(port, "1965")) {
242 strlcat(e->domain, ":", sizeof(e->domain));
243 strlcat(e->domain, port, sizeof(e->domain));
245 strlcpy(e->hash, hash, sizeof(e->hash));
246 tofu_add(&certs, e);
247 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
248 } else
249 tofu_res = !strcmp(hash, e->hash);
251 if (tofu_res) {
252 if (e->verified == -1)
253 tab->trust = TS_TEMP_TRUSTED;
254 else if (e->verified == 1)
255 tab->trust = TS_VERIFIED;
256 else
257 tab->trust = TS_TRUSTED;
259 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
260 &tofu_res, sizeof(tofu_res));
261 } else {
262 tab->trust = TS_UNTRUSTED;
263 load_page_from_str(tab, "# Certificate mismatch\n");
264 if ((tab->cert = strdup(hash)) == NULL)
265 die();
266 ui_yornp("Certificate mismatch. Proceed?",
267 handle_check_cert_user_choice, tab);
271 static void
272 handle_check_cert_user_choice(int accept, struct tab *tab)
274 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
275 sizeof(accept));
277 if (accept) {
278 /*
279 * trust the certificate for this session only. If
280 * the page results in a redirect while we're asking
281 * the user to save, we'll end up with an invalid
282 * tabid (one request == one tab id). It also makes
283 * sense to save it for the current session if the
284 * user accepted it.
285 */
286 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
287 tab->cert);
289 if (!safe_mode)
290 ui_yornp("Save the new certificate?",
291 handle_maybe_save_new_cert, tab);
292 else
293 message("Certificate temporarly trusted");
294 } else {
295 free(tab->cert);
296 tab->cert = NULL;
300 static void
301 handle_maybe_save_new_cert(int accept, struct tab *tab)
303 struct tofu_entry *e;
304 const char *host, *port;
306 if (tab->proxy != NULL) {
307 host = tab->proxy->host;
308 port = tab->proxy->port;
309 } else {
310 host = tab->uri.host;
311 port = tab->uri.port;
314 if (!accept)
315 goto end;
317 if ((e = calloc(1, sizeof(*e))) == NULL)
318 die();
320 strlcpy(e->domain, host, sizeof(e->domain));
321 if (*port != '\0' && strcmp(port, "1965")) {
322 strlcat(e->domain, ":", sizeof(e->domain));
323 strlcat(e->domain, port, sizeof(e->domain));
325 strlcpy(e->hash, tab->cert, sizeof(e->hash));
326 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
328 tofu_update(&certs, e);
330 tab->trust = TS_TRUSTED;
332 end:
333 free(tab->cert);
334 tab->cert = NULL;
337 static inline int
338 normalize_code(int n)
340 if (n < 20) {
341 if (n == 10 || n == 11)
342 return n;
343 return 10;
344 } else if (n < 30) {
345 return 20;
346 } else if (n < 40) {
347 if (n == 30 || n == 31)
348 return n;
349 return 30;
350 } else if (n < 50) {
351 if (n <= 44)
352 return n;
353 return 40;
354 } else if (n < 60) {
355 if (n <= 53 || n == 59)
356 return n;
357 return 50;
358 } else if (n < 70) {
359 if (n <= 62)
360 return n;
361 return 60;
362 } else
363 return MALFORMED_RESPONSE;
366 static void
367 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
369 struct tab *tab;
371 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
372 return;
374 if (sizeof(tab->code) != datalen)
375 die();
377 memcpy(&tab->code, imsg->data, sizeof(tab->code));
378 tab->code = normalize_code(tab->code);
379 if (tab->code != 30 && tab->code != 31)
380 tab->redirect_count = 0;
383 static void
384 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
386 struct tab *tab;
387 char buf[128];
389 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
390 return;
392 if (sizeof(tab->meta) <= datalen)
393 die();
395 memcpy(tab->meta, imsg->data, datalen);
397 if (tab->code < 10) { /* internal errors */
398 load_page_from_str(tab, err_pages[tab->code]);
399 } else if (tab->code < 20) { /* 1x */
400 load_page_from_str(tab, err_pages[tab->code]);
401 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
402 } else if (tab->code == 20) {
403 if (setup_parser_for(tab)) {
404 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
405 } else if (safe_mode) {
406 load_page_from_str(tab,
407 err_pages[UNKNOWN_TYPE_OR_CSET]);
408 } else {
409 struct hist *h;
411 if ((h = hist_pop(&tab->hist)) != NULL)
412 tab->hist_cur = h;
413 snprintf(buf, sizeof(buf),
414 "Can't display \"%s\", save it?", tab->meta);
415 ui_yornp(buf, handle_maybe_save_page, tab);
417 } else if (tab->code < 40) { /* 3x */
418 tab->redirect_count++;
420 /* TODO: make customizable? */
421 if (tab->redirect_count > 5) {
422 load_page_from_str(tab,
423 err_pages[TOO_MUCH_REDIRECTS]);
424 } else
425 do_load_url(tab, tab->meta, NULL);
426 } else { /* 4x, 5x & 6x */
427 load_page_from_str(tab, err_pages[tab->code]);
431 static void
432 handle_maybe_save_page(int dosave, struct tab *tab)
434 const char *f;
435 char input[PATH_MAX];
437 /* XXX: this print a message that is confusing */
438 ui_on_tab_loaded(tab);
440 if (!dosave) {
441 stop_tab(tab);
442 return;
445 if ((f = strrchr(tab->uri.path, '/')) == NULL)
446 f = "";
447 else
448 f++;
450 strlcpy(input, download_path, sizeof(input));
451 strlcat(input, f, sizeof(input));
453 ui_read("Save to path", handle_save_page_path, tab, input);
456 static void
457 handle_save_page_path(const char *path, struct tab *tab)
459 if (path == NULL) {
460 stop_tab(tab);
461 return;
464 ui_show_downloads_pane();
466 enqueue_download(tab->id, path);
467 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
469 /*
470 * Change this tab id, the old one is associated with the
471 * download now.
472 */
473 tab->id = tab_new_id();
476 static void
477 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
479 struct download *d;
480 const char *e;
482 /*
483 * There are no reason we shouldn't be able to find the
484 * required download.
485 */
486 if ((d = download_by_id(imsg->hdr.peerid)) == NULL)
487 die();
489 if (imsg->fd == -1) {
490 e = imsg->data;
491 if (e[datalen-1] != '\0')
492 die();
493 message("Can't open file %s: %s", d->path, e);
494 } else {
495 d->fd = imsg->fd;
496 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
500 static void
501 handle_imsg_session(struct imsg *imsg, size_t datalen)
503 static struct tab *curr;
504 static struct tab *tab;
505 struct session_tab st;
506 struct session_tab_hist sth;
507 struct hist *h;
508 int first_time;
510 /*
511 * The fs process tried to send tabs after it has announced
512 * that he's done. Something fishy is going on, better die.
513 */
514 if (operating)
515 die();
517 switch (imsg->hdr.type) {
518 case IMSG_SESSION_TAB:
519 if (datalen != sizeof(st))
520 die();
522 memcpy(&st, imsg->data, sizeof(st));
523 if ((tab = new_tab(st.uri, NULL, NULL)) == NULL)
524 die();
525 strlcpy(tab->buffer.page.title, st.title,
526 sizeof(tab->buffer.page.title));
527 if (st.flags & TAB_CURRENT)
528 curr = tab;
529 break;
531 case IMSG_SESSION_TAB_HIST:
532 if (tab == NULL || datalen != sizeof(sth))
533 die();
535 memcpy(&sth, imsg->data, sizeof(sth));
536 if (sth.uri[sizeof(sth.uri)-1] != '\0')
537 die();
539 if ((h = calloc(1, sizeof(*h))) == NULL)
540 die();
541 strlcpy(h->h, sth.uri, sizeof(h->h));
543 if (sth.future)
544 hist_push(&tab->hist, h);
545 else
546 hist_add_before(&tab->hist, tab->hist_cur, h);
547 break;
549 case IMSG_SESSION_END:
550 if (datalen != sizeof(first_time))
551 die();
552 memcpy(&first_time, imsg->data, sizeof(first_time));
553 if (first_time) {
554 new_tab("about:new", NULL, NULL);
555 curr = new_tab("about:help", NULL, NULL);
558 operating = 1;
559 if (curr != NULL)
560 switch_to_tab(curr);
561 if (has_url || TAILQ_EMPTY(&tabshead))
562 new_tab(url, NULL, NULL);
563 ui_main_loop();
564 break;
566 default:
567 die();
571 static void
572 handle_imsg_buf(struct imsg *imsg, size_t datalen)
574 struct tab *tab = NULL;
575 struct download *d = NULL;
577 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
578 (d = download_by_id(imsg->hdr.peerid)) == NULL)
579 return;
581 if (tab != NULL) {
582 if (!parser_parse(tab, imsg->data, datalen))
583 die();
584 ui_on_tab_refresh(tab);
585 } else {
586 d->bytes += datalen;
587 write(d->fd, imsg->data, datalen);
588 ui_on_download_refresh();
592 static void
593 handle_imsg_eof(struct imsg *imsg, size_t datalen)
595 struct tab *tab = NULL;
596 struct download *d = NULL;
598 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
599 (d = download_by_id(imsg->hdr.peerid)) == NULL)
600 return;
602 if (tab != NULL) {
603 if (!parser_free(tab))
604 die();
605 ui_on_tab_refresh(tab);
606 ui_on_tab_loaded(tab);
607 } else {
608 close(d->fd);
609 d->fd = -1;
610 ui_on_download_refresh();
614 static void
615 handle_imsg_tofu(struct imsg *imsg, size_t datalen)
617 struct tofu_entry *e;
619 if (operating)
620 die();
622 if ((e = calloc(1, sizeof(*e))) == NULL)
623 die();
625 if (datalen != sizeof(*e))
626 die();
627 memcpy(e, imsg->data, sizeof(*e));
628 if (e->domain[sizeof(e->domain)-1] != '\0' ||
629 e->hash[sizeof(e->hash)-1] != '\0')
630 die();
631 tofu_add(&certs, e);
634 static void
635 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
637 int res;
639 if (datalen != sizeof(res))
640 die();
642 memcpy(&res, imsg->data, sizeof(res));
643 if (res == 0)
644 message("Added to bookmarks!");
645 else
646 message("Failed to add to bookmarks: %s",
647 strerror(res));
650 static void
651 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
653 int res;
655 if (datalen != sizeof(res))
656 die();
657 memcpy(&res, imsg->data, datalen);
658 if (res != 0)
659 message("Failed to save the cert for: %s",
660 strerror(res));
663 static void
664 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
666 int res;
668 if (datalen != sizeof(res))
669 die();
670 memcpy(&res, imsg->data, datalen);
671 if (!res)
672 message("Failed to update the certificate");
675 static void
676 handle_dispatch_imsg(int fd, short ev, void *d)
678 struct imsgev *iev = d;
680 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
681 err(1, "connection closed");
684 static int
685 load_about_url(struct tab *tab, const char *url)
687 tab->trust = TS_UNKNOWN;
688 parser_init(tab, gemtext_initparser);
689 return make_fs_request(tab, IMSG_GET, url);
692 static int
693 load_file_url(struct tab *tab, const char *url)
695 tab->trust = TS_UNKNOWN;
696 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
699 static int
700 load_finger_url(struct tab *tab, const char *url)
702 struct get_req req;
703 size_t len;
704 char *at;
706 memset(&req, 0, sizeof(req));
707 strlcpy(req.port, tab->uri.port, sizeof(req.port));
709 /*
710 * Sometimes the finger url have the user as path component
711 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
712 * userinfo (e.g. finger://cobradile@finger.farm).
713 */
714 if ((at = strchr(tab->uri.host, '@')) != NULL) {
715 len = at - tab->uri.host;
716 memcpy(req.req, tab->uri.host, len);
718 if (len >= sizeof(req.req))
719 die();
720 req.req[len] = '\0';
722 strlcpy(req.host, at+1, sizeof(req.host));
723 } else {
724 strlcpy(req.host, tab->uri.host, sizeof(req.host));
726 /* +1 to skip the initial `/' */
727 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
729 strlcat(req.req, "\r\n", sizeof(req.req));
731 parser_init(tab, textplain_initparser);
732 return make_request(tab, &req, PROTO_FINGER, NULL);
735 static int
736 load_gemini_url(struct tab *tab, const char *url)
738 struct get_req req;
740 memset(&req, 0, sizeof(req));
741 strlcpy(req.host, tab->uri.host, sizeof(req.host));
742 strlcpy(req.port, tab->uri.port, sizeof(req.port));
744 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
747 static inline const char *
748 gopher_skip_selector(const char *path, int *ret_type)
750 *ret_type = 0;
752 if (!strcmp(path, "/") || *path == '\0') {
753 *ret_type = '1';
754 return path;
757 if (*path != '/')
758 return path;
759 path++;
761 switch (*ret_type = *path) {
762 case '0':
763 case '1':
764 case '7':
765 break;
767 default:
768 *ret_type = 0;
769 path -= 1;
770 return path;
773 return ++path;
776 static int
777 load_gopher_url(struct tab *tab, const char *url)
779 struct get_req req;
780 int type;
781 const char *path;
783 memset(&req, 0, sizeof(req));
784 strlcpy(req.host, tab->uri.host, sizeof(req.host));
785 strlcpy(req.port, tab->uri.port, sizeof(req.port));
787 path = gopher_skip_selector(tab->uri.path, &type);
788 switch (type) {
789 case '0':
790 parser_init(tab, textplain_initparser);
791 break;
792 case '1':
793 parser_init(tab, gophermap_initparser);
794 break;
795 case '7':
796 ui_require_input(tab, 0, PROTO_GOPHER);
797 return load_page_from_str(tab, err_pages[10]);
798 default:
799 return load_page_from_str(tab, "Unknown gopher selector");
802 strlcpy(req.req, path, sizeof(req.req));
803 if (*tab->uri.query != '\0') {
804 strlcat(req.req, "?", sizeof(req.req));
805 strlcat(req.req, tab->uri.query, sizeof(req.req));
807 strlcat(req.req, "\r\n", sizeof(req.req));
809 return make_request(tab, &req, PROTO_GOPHER, NULL);
812 static int
813 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
815 struct get_req req;
817 memset(&req, 0, sizeof(req));
818 strlcpy(req.host, p->host, sizeof(req.host));
819 strlcpy(req.port, p->port, sizeof(req.port));
821 tab->proxy = p;
823 return make_request(tab, &req, p->proto, tab->hist_cur->h);
826 static int
827 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
829 stop_tab(tab);
830 tab->id = tab_new_id();
831 req->proto = proto;
833 if (r != NULL) {
834 strlcpy(req->req, r, sizeof(req->req));
835 strlcat(req->req, "\r\n", sizeof(req->req));
838 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
840 /*
841 * So the various load_*_url can `return make_request` and
842 * do_load_url is happy.
843 */
844 return 1;
847 static int
848 make_fs_request(struct tab *tab, int type, const char *r)
850 stop_tab(tab);
851 tab->id = tab_new_id();
853 ui_send_fs(type, tab->id, r, strlen(r)+1);
855 /*
856 * So load_{about,file}_url can `return make_fs_request` and
857 * do_load_url is happy.
858 */
859 return 1;
862 void
863 gopher_send_search_req(struct tab *tab, const char *text)
865 struct get_req req;
867 start_loading_anim(tab);
869 memset(&req, 0, sizeof(req));
870 strlcpy(req.host, tab->uri.host, sizeof(req.host));
871 strlcpy(req.port, tab->uri.port, sizeof(req.port));
873 /* +2 to skip /7 */
874 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
875 if (*tab->uri.query != '\0') {
876 strlcat(req.req, "?", sizeof(req.req));
877 strlcat(req.req, tab->uri.query, sizeof(req.req));
880 strlcat(req.req, "\t", sizeof(req.req));
881 strlcat(req.req, text, sizeof(req.req));
882 strlcat(req.req, "\r\n", sizeof(req.req));
884 erase_buffer(&tab->buffer);
885 parser_init(tab, gophermap_initparser);
887 make_request(tab, &req, PROTO_GOPHER, NULL);
890 /*
891 * Effectively load the given url in the given tab. Return 1 when
892 * loading the page asynchronously, and thus when an erase_buffer can
893 * be done right after this function return, or 0 when loading the
894 * page synchronously.
895 */
896 static int
897 do_load_url(struct tab *tab, const char *url, const char *base)
899 struct phos_uri uri;
900 struct proto *p;
901 struct proxy *proxy;
902 char *t;
904 tab->proxy = NULL;
906 tab->trust = TS_UNKNOWN;
908 if (base == NULL)
909 memcpy(&uri, &tab->uri, sizeof(tab->uri));
910 else
911 phos_parse_absolute_uri(base, &uri);
913 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
914 if (asprintf(&t, "#error loading %s\n>%s\n",
915 url, "Can't parse the URI") == -1)
916 die();
917 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
918 load_page_from_str(tab, t);
919 free(t);
920 return 0;
923 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
924 sizeof(tab->hist_cur->h));
926 for (p = protos; p->schema != NULL; ++p) {
927 if (!strcmp(tab->uri.scheme, p->schema)) {
928 /* patch the port */
929 if (*tab->uri.port == '\0' && p->port != NULL)
930 strlcpy(tab->uri.port, p->port,
931 sizeof(tab->uri.port));
933 return p->loadfn(tab, url);
937 TAILQ_FOREACH(proxy, &proxies, proxies) {
938 if (!strcmp(tab->uri.scheme, proxy->match_proto))
939 return load_via_proxy(tab, url, proxy);
942 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
945 /*
946 * Load url in tab and handle history. If a tab is marked as lazy, only
947 * prepare the url but don't load it.
948 */
949 void
950 load_url(struct tab *tab, const char *url, const char *base, int nohist)
952 int lazy = tab->flags & TAB_LAZY;
954 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
955 if (tab->hist_cur != NULL)
956 hist_clear_forward(&tab->hist,
957 TAILQ_NEXT(tab->hist_cur, entries));
959 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
960 == NULL) {
961 event_loopbreak();
962 return;
965 strlcpy(tab->buffer.page.title, url,
966 sizeof(tab->buffer.page.title));
967 hist_push(&tab->hist, tab->hist_cur);
969 if (lazy)
970 strlcpy(tab->hist_cur->h, url,
971 sizeof(tab->hist_cur->h));
974 if (!lazy)
975 do_load_url(tab, url, base);
978 void
979 load_url_in_tab(struct tab *tab, const char *url, const char *base, int nohist)
981 if (!operating) {
982 load_url(tab, url, base, nohist);
983 return;
986 autosave_hook();
988 message("Loading %s...", url);
989 start_loading_anim(tab);
990 load_url(tab, url, base, nohist);
993 int
994 load_previous_page(struct tab *tab)
996 struct hist *h;
998 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
999 return 0;
1000 tab->hist_cur = h;
1001 do_load_url(tab, h->h, NULL);
1002 return 1;
1005 int
1006 load_next_page(struct tab *tab)
1008 struct hist *h;
1010 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
1011 return 0;
1012 tab->hist_cur = h;
1013 do_load_url(tab, h->h, NULL);
1014 return 1;
1017 void
1018 add_to_bookmarks(const char *str)
1020 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
1021 str, strlen(str)+1);
1025 * Given a user-entered URL, apply some heuristics to use it:
1027 * - if it's a proper url use it
1028 * - if it starts with a `./' or a `/' assume its a file:// url
1029 * - assume it's a gemini:// url
1031 * `ret' (of which len is the size) will be filled with the resulting
1032 * url.
1034 void
1035 humanify_url(const char *raw, char *ret, size_t len)
1037 struct phos_uri uri;
1038 char buf[PATH_MAX];
1040 if (phos_parse_absolute_uri(raw, &uri)) {
1041 strlcpy(ret, raw, len);
1042 return;
1045 if (has_prefix(raw, "./")) {
1046 strlcpy(ret, "file://", len);
1047 getcwd(buf, sizeof(buf));
1048 strlcat(ret, buf, len);
1049 strlcat(ret, "/", len);
1050 strlcat(ret, raw+2, len);
1051 return;
1054 if (*raw == '/') {
1055 strlcpy(ret, "file://", len);
1056 strlcat(ret, raw, len);
1057 return;
1060 strlcpy(ret, "gemini://", len);
1061 strlcat(ret, raw, len);
1064 static pid_t
1065 start_child(enum telescope_process p, const char *argv0, int fd)
1067 const char *argv[5];
1068 int argc = 0;
1069 pid_t pid;
1071 switch (pid = fork()) {
1072 case -1:
1073 die();
1074 case 0:
1075 break;
1076 default:
1077 close(fd);
1078 return pid;
1081 if (dup2(fd, 3) == -1)
1082 err(1, "cannot setup imsg fd");
1084 argv[argc++] = argv0;
1085 switch (p) {
1086 case PROC_UI:
1087 errx(1, "Can't start ui process");
1088 case PROC_FS:
1089 argv[argc++] = "-Tf";
1090 break;
1091 case PROC_NET:
1092 argv[argc++] = "-Tn";
1093 break;
1096 if (safe_mode)
1097 argv[argc++] = "-S";
1099 argv[argc++] = NULL;
1100 execvp(argv0, (char *const *)argv);
1101 err(1, "execvp(%s)", argv0);
1104 int
1105 ui_send_net(int type, uint32_t peerid, const void *data,
1106 uint16_t datalen)
1108 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1109 datalen);
1112 int
1113 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1115 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1116 datalen);
1119 static void __attribute__((noreturn))
1120 usage(int r)
1122 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1123 getprogname());
1124 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1125 exit(r);
1128 int
1129 main(int argc, char * const *argv)
1131 struct imsgev net_ibuf, fs_ibuf;
1132 pid_t pid;
1133 int pipe2net[2], pipe2fs[2];
1134 int ch, configtest = 0, fail = 0;
1135 int proc = -1;
1136 int sessionfd = -1;
1137 int status;
1138 const char *argv0;
1140 argv0 = argv[0];
1142 signal(SIGCHLD, SIG_IGN);
1143 signal(SIGPIPE, SIG_IGN);
1145 if (getenv("NO_COLOR") != NULL)
1146 enable_colors = 0;
1148 fs_init();
1150 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1151 switch (ch) {
1152 case 'C':
1153 exit(ui_print_colors());
1154 case 'c':
1155 fail = 1;
1156 strlcpy(config_path, optarg, sizeof(config_path));
1157 break;
1158 case 'n':
1159 configtest = 1;
1160 break;
1161 case 'h':
1162 usage(0);
1163 case 'S':
1164 safe_mode = 1;
1165 break;
1166 case 'T':
1167 switch (*optarg) {
1168 case 'f':
1169 proc = PROC_FS;
1170 break;
1171 case 'n':
1172 proc = PROC_NET;
1173 break;
1174 default:
1175 errx(1, "invalid process spec %c",
1176 *optarg);
1178 break;
1179 case 'v':
1180 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1181 exit(0);
1182 break;
1183 default:
1184 usage(1);
1188 argc -= optind;
1189 argv += optind;
1191 if (proc != -1) {
1192 if (argc > 0)
1193 usage(1);
1194 else if (proc == PROC_FS)
1195 return fs_main();
1196 else if (proc == PROC_NET)
1197 return net_main();
1198 else
1199 usage(1);
1202 if (argc != 0) {
1203 has_url = 1;
1204 humanify_url(argv[0], url, sizeof(url));
1207 /* setup keys before reading the config */
1208 TAILQ_INIT(&global_map.m);
1209 global_map.unhandled_input = global_key_unbound;
1210 TAILQ_INIT(&minibuffer_map.m);
1212 config_init();
1213 parseconfig(config_path, fail);
1214 if (configtest) {
1215 puts("config OK");
1216 exit(0);
1219 if (download_path == NULL &&
1220 (download_path = strdup("/tmp/")) == NULL)
1221 errx(1, "strdup");
1223 if (!safe_mode && (sessionfd = lock_session()) == -1)
1224 errx(1, "can't lock session, is another instance of "
1225 "telescope already running?");
1227 /* Start children. */
1228 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1229 err(1, "socketpair");
1230 start_child(PROC_FS, argv0, pipe2fs[1]);
1231 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1232 iev_fs = &fs_ibuf;
1233 iev_fs->handler = handle_dispatch_imsg;
1235 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1236 err(1, "socketpair");
1237 start_child(PROC_NET, argv0, pipe2net[1]);
1238 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1239 iev_net = &net_ibuf;
1240 iev_net->handler = handle_dispatch_imsg;
1242 setproctitle("ui");
1244 /* initialize tofu store */
1245 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1247 event_init();
1249 /* Setup event handler for the autosave */
1250 autosave_init();
1252 /* Setup event handlers for pipes to fs/net */
1253 iev_fs->events = EV_READ;
1254 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1255 iev_fs->handler, iev_fs);
1256 event_add(&iev_fs->ev, NULL);
1258 iev_net->events = EV_READ;
1259 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1260 iev_net->handler, iev_net);
1261 event_add(&iev_net->ev, NULL);
1263 if (ui_init()) {
1264 sandbox_ui_process();
1265 ui_send_fs(IMSG_INIT, 0, NULL, 0);
1266 event_dispatch();
1267 ui_end();
1270 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1271 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1272 imsg_flush(&iev_fs->ibuf);
1273 imsg_flush(&iev_net->ibuf);
1275 /* wait for children to terminate */
1276 do {
1277 pid = wait(&status);
1278 if (pid == -1) {
1279 if (errno != EINTR && errno != ECHILD)
1280 err(1, "wait");
1281 } else if (WIFSIGNALED(status))
1282 warnx("child terminated; signal %d", WTERMSIG(status));
1283 } while (pid != -1 || (pid == -1 && errno == EINTR));
1285 if (!safe_mode && close(sessionfd) == -1)
1286 err(1, "close(sessionfd = %d)", sessionfd);
1288 return 0;