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 "mcache.h"
33 #include "minibuffer.h"
34 #include "parser.h"
35 #include "session.h"
36 #include "telescope.h"
37 #include "ui.h"
38 #include "utils.h"
40 static struct option longopts[] = {
41 {"colors", no_argument, NULL, 'C'},
42 {"colours", no_argument, NULL, 'C'},
43 {"help", no_argument, NULL, 'h'},
44 {"safe", no_argument, NULL, 'S'},
45 {"version", no_argument, NULL, 'v'},
46 {NULL, 0, NULL, 0},
47 };
49 static const char *opts = "Cc:hnST:v";
51 static int has_url;
52 static char url[GEMINI_URL_LEN];
54 /*
55 * Used to know when we're finished loading.
56 */
57 int operating;
59 /*
60 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
61 * anything to the filesystem or execute external programs.
62 */
63 int safe_mode;
65 static struct imsgev *iev_fs, *iev_net;
67 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
68 struct tabshead ktabshead = TAILQ_HEAD_INITIALIZER(ktabshead);
69 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
71 enum telescope_process {
72 PROC_UI,
73 PROC_FS,
74 PROC_NET,
75 };
77 #define CANNOT_FETCH 0
78 #define TOO_MUCH_REDIRECTS 1
79 #define MALFORMED_RESPONSE 2
80 #define UNKNOWN_TYPE_OR_CSET 3
81 #define UNKNOWN_PROTOCOL 4
83 /* XXX: keep in sync with normalize_code */
84 const char *err_pages[70] = {
85 [CANNOT_FETCH] = "# Couldn't load the page\n",
86 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
87 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
88 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
89 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
91 [10] = "# Input required\n",
92 [11] = "# Input required\n",
93 [40] = "# Temporary failure\n",
94 [41] = "# Server unavailable\n",
95 [42] = "# CGI error\n",
96 [43] = "# Proxy error\n",
97 [44] = "# Slow down\n",
98 [50] = "# Permanent failure\n",
99 [51] = "# Not found\n",
100 [52] = "# Gone\n",
101 [53] = "# Proxy request refused\n",
102 [59] = "# Bad request\n",
103 [60] = "# Client certificate required\n",
104 [61] = "# Certificate not authorised\n",
105 [62] = "# Certificate not valid\n"
106 };
108 static void die(void) __attribute__((__noreturn__));
109 static struct tab *tab_by_id(uint32_t);
110 static void handle_imsg_err(struct imsg *, size_t);
111 static void handle_imsg_check_cert(struct imsg *, size_t);
112 static void handle_check_cert_user_choice(int, struct tab *);
113 static void handle_maybe_save_new_cert(int, struct tab *);
114 static void handle_imsg_got_code(struct imsg *, size_t);
115 static void handle_imsg_got_meta(struct imsg *, size_t);
116 static void handle_maybe_save_page(int, struct tab *);
117 static void handle_save_page_path(const char *, struct tab *);
118 static void handle_imsg_file_opened(struct imsg *, size_t);
119 static void handle_imsg_buf(struct imsg *, size_t);
120 static void handle_imsg_eof(struct imsg *, size_t);
121 static void handle_imsg_tofu(struct imsg *, size_t);
122 static void handle_imsg_bookmark_ok(struct imsg *, size_t);
123 static void handle_imsg_save_cert_ok(struct imsg *, size_t);
124 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
125 static void handle_imsg_session(struct imsg *, size_t);
126 static void handle_dispatch_imsg(int, short, void *);
127 static int load_about_url(struct tab *, const char *);
128 static int load_file_url(struct tab *, const char *);
129 static int load_finger_url(struct tab *, const char *);
130 static int load_gemini_url(struct tab *, const char *);
131 static int load_gopher_url(struct tab *, const char *);
132 static int load_via_proxy(struct tab *, const char *,
133 struct proxy *);
134 static int make_request(struct tab *, struct get_req *, int,
135 const char *);
136 static int make_fs_request(struct tab *, int, const char *);
137 static int do_load_url(struct tab *, const char *, const char *, int);
138 static pid_t start_child(enum telescope_process, const char *, int);
140 static struct proto {
141 const char *schema;
142 const char *port;
143 int (*loadfn)(struct tab *, const char *);
144 } protos[] = {
145 {"about", NULL, load_about_url},
146 {"file", NULL, load_file_url},
147 {"finger", "79", load_finger_url},
148 {"gemini", "1965", load_gemini_url},
149 {"gopher", "70", load_gopher_url},
150 {NULL, NULL, NULL},
151 };
153 static imsg_handlerfn *handlers[] = {
154 [IMSG_ERR] = handle_imsg_err,
155 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
156 [IMSG_GOT_CODE] = handle_imsg_got_code,
157 [IMSG_GOT_META] = handle_imsg_got_meta,
158 [IMSG_BUF] = handle_imsg_buf,
159 [IMSG_EOF] = handle_imsg_eof,
160 [IMSG_TOFU] = handle_imsg_tofu,
161 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
162 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
163 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
164 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
165 [IMSG_SESSION_TAB] = handle_imsg_session,
166 [IMSG_SESSION_TAB_HIST] = handle_imsg_session,
167 [IMSG_SESSION_END] = handle_imsg_session,
168 };
170 static struct ohash certs;
172 static void __attribute__((__noreturn__))
173 die(void)
175 abort(); /* TODO */
178 static struct tab *
179 tab_by_id(uint32_t id)
181 struct tab *t;
183 TAILQ_FOREACH(t, &tabshead, tabs) {
184 if (t->id == id)
185 return t;
188 return NULL;
191 static void
192 handle_imsg_err(struct imsg *imsg, size_t datalen)
194 struct tab *tab;
195 char *page;
197 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
198 return;
200 page = imsg->data;
201 page[datalen-1] = '\0';
203 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
204 tab->hist_cur->h, page) == -1)
205 die();
206 load_page_from_str(tab, page);
207 free(page);
210 static void
211 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
213 const char *hash, *host, *port;
214 int tofu_res;
215 struct tofu_entry *e;
216 struct tab *tab;
218 hash = imsg->data;
219 if (hash[datalen-1] != '\0')
220 abort();
222 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
223 return;
225 if (tab->proxy != NULL) {
226 host = tab->proxy->host;
227 port = tab->proxy->port;
228 } else {
229 host = tab->uri.host;
230 port = tab->uri.port;
233 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
234 /* TODO: an update in libressl/libretls changed
235 * significantly. Find a better approach at storing
236 * the certs! */
237 if (datalen > sizeof(e->hash))
238 abort();
240 tofu_res = 1; /* trust on first use */
241 if ((e = calloc(1, sizeof(*e))) == NULL)
242 abort();
243 strlcpy(e->domain, host, sizeof(e->domain));
244 if (*port != '\0' && strcmp(port, "1965")) {
245 strlcat(e->domain, ":", sizeof(e->domain));
246 strlcat(e->domain, port, sizeof(e->domain));
248 strlcpy(e->hash, hash, sizeof(e->hash));
249 tofu_add(&certs, e);
250 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
251 } else
252 tofu_res = !strcmp(hash, e->hash);
254 if (tofu_res) {
255 if (e->verified == -1)
256 tab->trust = TS_TEMP_TRUSTED;
257 else if (e->verified == 1)
258 tab->trust = TS_VERIFIED;
259 else
260 tab->trust = TS_TRUSTED;
262 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
263 &tofu_res, sizeof(tofu_res));
264 } else {
265 tab->trust = TS_UNTRUSTED;
266 load_page_from_str(tab, "# Certificate mismatch\n");
267 if ((tab->cert = strdup(hash)) == NULL)
268 die();
269 ui_yornp("Certificate mismatch. Proceed?",
270 handle_check_cert_user_choice, tab);
274 static void
275 handle_check_cert_user_choice(int accept, struct tab *tab)
277 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
278 sizeof(accept));
280 if (accept) {
281 /*
282 * trust the certificate for this session only. If
283 * the page results in a redirect while we're asking
284 * the user to save, we'll end up with an invalid
285 * tabid (one request == one tab id). It also makes
286 * sense to save it for the current session if the
287 * user accepted it.
288 */
289 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
290 tab->cert);
292 if (!safe_mode)
293 ui_yornp("Save the new certificate?",
294 handle_maybe_save_new_cert, tab);
295 else
296 message("Certificate temporarly trusted");
297 } else {
298 free(tab->cert);
299 tab->cert = NULL;
303 static void
304 handle_maybe_save_new_cert(int accept, struct tab *tab)
306 struct tofu_entry *e;
307 const char *host, *port;
309 if (tab->proxy != NULL) {
310 host = tab->proxy->host;
311 port = tab->proxy->port;
312 } else {
313 host = tab->uri.host;
314 port = tab->uri.port;
317 if (!accept)
318 goto end;
320 if ((e = calloc(1, sizeof(*e))) == NULL)
321 die();
323 strlcpy(e->domain, host, sizeof(e->domain));
324 if (*port != '\0' && strcmp(port, "1965")) {
325 strlcat(e->domain, ":", sizeof(e->domain));
326 strlcat(e->domain, port, sizeof(e->domain));
328 strlcpy(e->hash, tab->cert, sizeof(e->hash));
329 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
331 tofu_update(&certs, e);
333 tab->trust = TS_TRUSTED;
335 end:
336 free(tab->cert);
337 tab->cert = NULL;
340 static inline int
341 normalize_code(int n)
343 if (n < 20) {
344 if (n == 10 || n == 11)
345 return n;
346 return 10;
347 } else if (n < 30) {
348 return 20;
349 } else if (n < 40) {
350 if (n == 30 || n == 31)
351 return n;
352 return 30;
353 } else if (n < 50) {
354 if (n <= 44)
355 return n;
356 return 40;
357 } else if (n < 60) {
358 if (n <= 53 || n == 59)
359 return n;
360 return 50;
361 } else if (n < 70) {
362 if (n <= 62)
363 return n;
364 return 60;
365 } else
366 return MALFORMED_RESPONSE;
369 static void
370 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
372 struct tab *tab;
374 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
375 return;
377 if (sizeof(tab->code) != datalen)
378 die();
380 memcpy(&tab->code, imsg->data, sizeof(tab->code));
381 tab->code = normalize_code(tab->code);
382 if (tab->code != 30 && tab->code != 31)
383 tab->redirect_count = 0;
386 static void
387 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
389 struct tab *tab;
390 char buf[128];
392 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
393 return;
395 if (sizeof(tab->meta) <= datalen)
396 die();
398 memcpy(tab->meta, imsg->data, datalen);
400 if (tab->code < 10) { /* internal errors */
401 load_page_from_str(tab, err_pages[tab->code]);
402 } else if (tab->code < 20) { /* 1x */
403 free(tab->last_input_url);
404 tab->last_input_url = strdup(tab->hist_cur->h);
405 if (tab->last_input_url == NULL)
406 die();
408 load_page_from_str(tab, err_pages[tab->code]);
409 ui_require_input(tab, tab->code == 11, ir_select_gemini);
410 } else if (tab->code == 20) {
411 if (setup_parser_for(tab)) {
412 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
413 } else if (safe_mode) {
414 load_page_from_str(tab,
415 err_pages[UNKNOWN_TYPE_OR_CSET]);
416 } else {
417 struct hist *h;
419 if ((h = hist_pop(&tab->hist)) != NULL)
420 tab->hist_cur = h;
421 snprintf(buf, sizeof(buf),
422 "Can't display \"%s\", save it?", tab->meta);
423 ui_yornp(buf, handle_maybe_save_page, tab);
425 } else if (tab->code < 40) { /* 3x */
426 tab->redirect_count++;
428 /* TODO: make customizable? */
429 if (tab->redirect_count > 5) {
430 load_page_from_str(tab,
431 err_pages[TOO_MUCH_REDIRECTS]);
432 } else
433 do_load_url(tab, tab->meta, NULL, LU_MODE_NOCACHE);
434 } else { /* 4x, 5x & 6x */
435 load_page_from_str(tab, err_pages[tab->code]);
439 static void
440 handle_maybe_save_page(int dosave, struct tab *tab)
442 const char *f;
443 char input[PATH_MAX];
445 /* XXX: this print a message that is confusing */
446 ui_on_tab_loaded(tab);
448 if (!dosave) {
449 stop_tab(tab);
450 return;
453 if ((f = strrchr(tab->uri.path, '/')) == NULL)
454 f = "";
455 else
456 f++;
458 strlcpy(input, download_path, sizeof(input));
459 strlcat(input, f, sizeof(input));
461 ui_read("Save to path", handle_save_page_path, tab, input);
464 static void
465 handle_save_page_path(const char *path, struct tab *tab)
467 if (path == NULL) {
468 stop_tab(tab);
469 return;
472 ui_show_downloads_pane();
474 enqueue_download(tab->id, path);
475 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
477 /*
478 * Change this tab id, the old one is associated with the
479 * download now.
480 */
481 tab->id = tab_new_id();
484 static void
485 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
487 struct download *d;
488 const char *e;
490 /*
491 * There are no reason we shouldn't be able to find the
492 * required download.
493 */
494 if ((d = download_by_id(imsg->hdr.peerid)) == NULL)
495 die();
497 if (imsg->fd == -1) {
498 e = imsg->data;
499 if (e[datalen-1] != '\0')
500 die();
501 message("Can't open file %s: %s", d->path, e);
502 } else {
503 d->fd = imsg->fd;
504 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
508 static void
509 handle_imsg_session(struct imsg *imsg, size_t datalen)
511 static struct tab *curr;
512 static struct tab *tab;
513 struct session_tab st;
514 struct session_tab_hist sth;
515 struct hist *h;
516 int first_time;
518 /*
519 * The fs process tried to send tabs after it has announced
520 * that he's done. Something fishy is going on, better die.
521 */
522 if (operating)
523 die();
525 switch (imsg->hdr.type) {
526 case IMSG_SESSION_TAB:
527 if (datalen != sizeof(st))
528 die();
530 memcpy(&st, imsg->data, sizeof(st));
531 if ((tab = new_tab(st.uri, NULL, NULL)) == NULL)
532 die();
533 tab->hist_cur->line_off = st.top_line;
534 tab->hist_cur->current_off = st.current_line;
535 strlcpy(tab->buffer.page.title, st.title,
536 sizeof(tab->buffer.page.title));
537 if (st.flags & TAB_CURRENT)
538 curr = tab;
539 if (st.flags & TAB_KILLED)
540 kill_tab(tab, 1);
541 break;
543 case IMSG_SESSION_TAB_HIST:
544 if (tab == NULL || datalen != sizeof(sth))
545 die();
547 memcpy(&sth, imsg->data, sizeof(sth));
548 if (sth.uri[sizeof(sth.uri)-1] != '\0')
549 die();
551 if ((h = calloc(1, sizeof(*h))) == NULL)
552 die();
553 strlcpy(h->h, sth.uri, sizeof(h->h));
555 if (sth.future)
556 hist_push(&tab->hist, h);
557 else
558 hist_add_before(&tab->hist, tab->hist_cur, h);
559 break;
561 case IMSG_SESSION_END:
562 if (datalen != sizeof(first_time))
563 die();
564 memcpy(&first_time, imsg->data, sizeof(first_time));
565 if (first_time) {
566 new_tab("about:new", NULL, NULL);
567 curr = new_tab("about:help", NULL, NULL);
570 operating = 1;
571 if (curr != NULL)
572 switch_to_tab(curr);
573 if (has_url || TAILQ_EMPTY(&tabshead))
574 new_tab(url, NULL, NULL);
575 ui_main_loop();
576 break;
578 default:
579 die();
583 static void
584 handle_imsg_buf(struct imsg *imsg, size_t datalen)
586 struct tab *tab = NULL;
587 struct download *d = NULL;
589 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
590 (d = download_by_id(imsg->hdr.peerid)) == NULL)
591 return;
593 if (tab != NULL) {
594 if (!parser_parse(tab, imsg->data, datalen))
595 die();
596 ui_on_tab_refresh(tab);
597 } else {
598 d->bytes += datalen;
599 write(d->fd, imsg->data, datalen);
600 ui_on_download_refresh();
604 static void
605 handle_imsg_eof(struct imsg *imsg, size_t datalen)
607 struct tab *tab = NULL;
608 struct download *d = NULL;
610 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
611 (d = download_by_id(imsg->hdr.peerid)) == NULL)
612 return;
614 if (tab != NULL) {
615 if (!parser_free(tab))
616 die();
617 if (has_prefix(tab->hist_cur->h, "gemini://") ||
618 has_prefix(tab->hist_cur->h, "gopher://"))
619 mcache_tab(tab);
620 ui_on_tab_refresh(tab);
621 ui_on_tab_loaded(tab);
622 } else {
623 close(d->fd);
624 d->fd = -1;
625 ui_on_download_refresh();
629 static void
630 handle_imsg_tofu(struct imsg *imsg, size_t datalen)
632 struct tofu_entry *e;
634 if (operating)
635 die();
637 if ((e = calloc(1, sizeof(*e))) == NULL)
638 die();
640 if (datalen != sizeof(*e))
641 die();
642 memcpy(e, imsg->data, sizeof(*e));
643 if (e->domain[sizeof(e->domain)-1] != '\0' ||
644 e->hash[sizeof(e->hash)-1] != '\0')
645 die();
646 tofu_add(&certs, e);
649 static void
650 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
652 int res;
654 if (datalen != sizeof(res))
655 die();
657 memcpy(&res, imsg->data, sizeof(res));
658 if (res == 0)
659 message("Added to bookmarks!");
660 else
661 message("Failed to add to bookmarks: %s",
662 strerror(res));
665 static void
666 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
668 int res;
670 if (datalen != sizeof(res))
671 die();
672 memcpy(&res, imsg->data, datalen);
673 if (res != 0)
674 message("Failed to save the cert for: %s",
675 strerror(res));
678 static void
679 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
681 int res;
683 if (datalen != sizeof(res))
684 die();
685 memcpy(&res, imsg->data, datalen);
686 if (!res)
687 message("Failed to update the certificate");
690 static void
691 handle_dispatch_imsg(int fd, short ev, void *d)
693 struct imsgev *iev = d;
695 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
696 err(1, "connection closed");
699 static int
700 load_about_url(struct tab *tab, const char *url)
702 tab->trust = TS_UNKNOWN;
703 parser_init(tab, gemtext_initparser);
704 return make_fs_request(tab, IMSG_GET, url);
707 static int
708 load_file_url(struct tab *tab, const char *url)
710 tab->trust = TS_UNKNOWN;
711 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
714 static int
715 load_finger_url(struct tab *tab, const char *url)
717 struct get_req req;
718 size_t len;
719 char *at;
721 memset(&req, 0, sizeof(req));
722 strlcpy(req.port, tab->uri.port, sizeof(req.port));
724 /*
725 * Sometimes the finger url have the user as path component
726 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
727 * userinfo (e.g. finger://cobradile@finger.farm).
728 */
729 if ((at = strchr(tab->uri.host, '@')) != NULL) {
730 len = at - tab->uri.host;
731 memcpy(req.req, tab->uri.host, len);
733 if (len >= sizeof(req.req))
734 die();
735 req.req[len] = '\0';
737 strlcpy(req.host, at+1, sizeof(req.host));
738 } else {
739 strlcpy(req.host, tab->uri.host, sizeof(req.host));
741 /* +1 to skip the initial `/' */
742 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
744 strlcat(req.req, "\r\n", sizeof(req.req));
746 parser_init(tab, textplain_initparser);
747 return make_request(tab, &req, PROTO_FINGER, NULL);
750 static int
751 load_gemini_url(struct tab *tab, const char *url)
753 struct get_req req;
755 memset(&req, 0, sizeof(req));
756 strlcpy(req.host, tab->uri.host, sizeof(req.host));
757 strlcpy(req.port, tab->uri.port, sizeof(req.port));
759 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
762 static inline const char *
763 gopher_skip_selector(const char *path, int *ret_type)
765 *ret_type = 0;
767 if (!strcmp(path, "/") || *path == '\0') {
768 *ret_type = '1';
769 return path;
772 if (*path != '/')
773 return path;
774 path++;
776 switch (*ret_type = *path) {
777 case '0':
778 case '1':
779 case '7':
780 break;
782 default:
783 *ret_type = 0;
784 path -= 1;
785 return path;
788 return ++path;
791 static int
792 load_gopher_url(struct tab *tab, const char *url)
794 struct get_req req;
795 int type;
796 const char *path;
798 memset(&req, 0, sizeof(req));
799 strlcpy(req.host, tab->uri.host, sizeof(req.host));
800 strlcpy(req.port, tab->uri.port, sizeof(req.port));
802 path = gopher_skip_selector(tab->uri.path, &type);
803 switch (type) {
804 case '0':
805 parser_init(tab, textplain_initparser);
806 break;
807 case '1':
808 parser_init(tab, gophermap_initparser);
809 break;
810 case '7':
811 free(tab->last_input_url);
812 tab->last_input_url = strdup(url);
813 if (tab->last_input_url == NULL)
814 die();
815 ui_require_input(tab, 0, ir_select_gopher);
816 return load_page_from_str(tab, err_pages[10]);
817 default:
818 return load_page_from_str(tab, "Unknown gopher selector");
821 strlcpy(req.req, path, sizeof(req.req));
822 if (*tab->uri.query != '\0') {
823 strlcat(req.req, "?", sizeof(req.req));
824 strlcat(req.req, tab->uri.query, sizeof(req.req));
826 strlcat(req.req, "\r\n", sizeof(req.req));
828 return make_request(tab, &req, PROTO_GOPHER, NULL);
831 static int
832 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
834 struct get_req req;
836 memset(&req, 0, sizeof(req));
837 strlcpy(req.host, p->host, sizeof(req.host));
838 strlcpy(req.port, p->port, sizeof(req.port));
840 tab->proxy = p;
842 return make_request(tab, &req, p->proto, tab->hist_cur->h);
845 static int
846 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
848 stop_tab(tab);
849 tab->id = tab_new_id();
850 req->proto = proto;
852 if (r != NULL) {
853 strlcpy(req->req, r, sizeof(req->req));
854 strlcat(req->req, "\r\n", sizeof(req->req));
857 start_loading_anim(tab);
858 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
860 /*
861 * So the various load_*_url can `return make_request` and
862 * do_load_url is happy.
863 */
864 return 1;
867 static int
868 make_fs_request(struct tab *tab, int type, const char *r)
870 stop_tab(tab);
871 tab->id = tab_new_id();
873 ui_send_fs(type, tab->id, r, strlen(r)+1);
875 /*
876 * So load_{about,file}_url can `return make_fs_request` and
877 * do_load_url is happy.
878 */
879 return 1;
882 void
883 gopher_send_search_req(struct tab *tab, const char *text)
885 struct get_req req;
887 memset(&req, 0, sizeof(req));
888 strlcpy(req.host, tab->uri.host, sizeof(req.host));
889 strlcpy(req.port, tab->uri.port, sizeof(req.port));
891 /* +2 to skip /7 */
892 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
893 if (*tab->uri.query != '\0') {
894 strlcat(req.req, "?", sizeof(req.req));
895 strlcat(req.req, tab->uri.query, sizeof(req.req));
898 strlcat(req.req, "\t", sizeof(req.req));
899 strlcat(req.req, text, sizeof(req.req));
900 strlcat(req.req, "\r\n", sizeof(req.req));
902 erase_buffer(&tab->buffer);
903 parser_init(tab, gophermap_initparser);
905 make_request(tab, &req, PROTO_GOPHER, NULL);
908 int
909 load_page_from_str(struct tab *tab, const char *page)
911 parser_init(tab, gemtext_initparser);
912 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
913 abort();
914 if (!tab->buffer.page.free(&tab->buffer.page))
915 abort();
916 ui_on_tab_refresh(tab);
917 ui_on_tab_loaded(tab);
918 return 0;
921 /*
922 * Effectively load the given url in the given tab. Return 1 when
923 * loading the page asynchronously, and thus when an erase_buffer can
924 * be done right after this function return, or 0 when loading the
925 * page synchronously.
926 */
927 static int
928 do_load_url(struct tab *tab, const char *url, const char *base, int mode)
930 struct phos_uri uri;
931 struct proto *p;
932 struct proxy *proxy;
933 int nocache = mode & LU_MODE_NOCACHE;
934 char *t;
936 tab->proxy = NULL;
937 tab->trust = TS_UNKNOWN;
939 if (base == NULL)
940 memcpy(&uri, &tab->uri, sizeof(tab->uri));
941 else
942 phos_parse_absolute_uri(base, &uri);
944 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
945 if (asprintf(&t, "#error loading %s\n>%s\n",
946 url, "Can't parse the URI") == -1)
947 die();
948 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
949 load_page_from_str(tab, t);
950 free(t);
951 return 0;
954 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
955 sizeof(tab->hist_cur->h));
957 if (!nocache && mcache_lookup(tab->hist_cur->h, tab)) {
958 ui_on_tab_refresh(tab);
959 ui_on_tab_loaded(tab);
960 return 0;
963 for (p = protos; p->schema != NULL; ++p) {
964 if (!strcmp(tab->uri.scheme, p->schema)) {
965 /* patch the port */
966 if (*tab->uri.port == '\0' && p->port != NULL)
967 strlcpy(tab->uri.port, p->port,
968 sizeof(tab->uri.port));
970 return p->loadfn(tab, tab->hist_cur->h);
974 TAILQ_FOREACH(proxy, &proxies, proxies) {
975 if (!strcmp(tab->uri.scheme, proxy->match_proto))
976 return load_via_proxy(tab, url, proxy);
979 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
982 /*
983 * Load url in tab and handle history. If a tab is marked as lazy, only
984 * prepare the url but don't load it.
985 */
986 void
987 load_url(struct tab *tab, const char *url, const char *base, int mode)
989 int lazy = tab->flags & TAB_LAZY;
990 int nohist = mode & LU_MODE_NOHIST;
992 if (operating && lazy) {
993 tab->flags ^= TAB_LAZY;
994 lazy = 0;
995 } else if (tab->hist_cur != NULL)
996 get_scroll_position(tab, &tab->hist_cur->line_off,
997 &tab->hist_cur->current_off);
999 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
1000 if (tab->hist_cur != NULL)
1001 hist_clear_forward(&tab->hist,
1002 TAILQ_NEXT(tab->hist_cur, entries));
1004 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
1005 == NULL) {
1006 event_loopbreak();
1007 return;
1010 strlcpy(tab->buffer.page.title, url,
1011 sizeof(tab->buffer.page.title));
1012 hist_push(&tab->hist, tab->hist_cur);
1014 if (lazy)
1015 strlcpy(tab->hist_cur->h, url,
1016 sizeof(tab->hist_cur->h));
1019 if (!lazy)
1020 do_load_url(tab, url, base, mode);
1023 void
1024 load_url_in_tab(struct tab *tab, const char *url, const char *base, int mode)
1026 if (operating) {
1027 autosave_hook();
1028 message("Loading %s...", url);
1031 load_url(tab, url, base, mode);
1034 int
1035 load_previous_page(struct tab *tab)
1037 struct hist *h;
1039 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
1040 return 0;
1041 tab->hist_cur = h;
1042 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
1043 return 1;
1046 int
1047 load_next_page(struct tab *tab)
1049 struct hist *h;
1051 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
1052 return 0;
1053 tab->hist_cur = h;
1054 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
1055 return 1;
1058 void
1059 add_to_bookmarks(const char *str)
1061 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
1062 str, strlen(str)+1);
1066 * Given a user-entered URL, apply some heuristics to use it:
1068 * - if it's a proper url use it
1069 * - if it starts with a `./' or a `/' assume its a file:// url
1070 * - assume it's a gemini:// url
1072 * `ret' (of which len is the size) will be filled with the resulting
1073 * url.
1075 void
1076 humanify_url(const char *raw, char *ret, size_t len)
1078 struct phos_uri uri;
1079 char buf[PATH_MAX];
1081 if (phos_parse_absolute_uri(raw, &uri)) {
1082 strlcpy(ret, raw, len);
1083 return;
1086 if (has_prefix(raw, "./")) {
1087 strlcpy(ret, "file://", len);
1088 getcwd(buf, sizeof(buf));
1089 strlcat(ret, buf, len);
1090 strlcat(ret, "/", len);
1091 strlcat(ret, raw+2, len);
1092 return;
1095 if (*raw == '/') {
1096 strlcpy(ret, "file://", len);
1097 strlcat(ret, raw, len);
1098 return;
1101 strlcpy(ret, "gemini://", len);
1102 strlcat(ret, raw, len);
1105 static pid_t
1106 start_child(enum telescope_process p, const char *argv0, int fd)
1108 const char *argv[5];
1109 int argc = 0;
1110 pid_t pid;
1112 switch (pid = fork()) {
1113 case -1:
1114 die();
1115 case 0:
1116 break;
1117 default:
1118 close(fd);
1119 return pid;
1122 if (dup2(fd, 3) == -1)
1123 err(1, "cannot setup imsg fd");
1125 argv[argc++] = argv0;
1126 switch (p) {
1127 case PROC_UI:
1128 errx(1, "Can't start ui process");
1129 case PROC_FS:
1130 argv[argc++] = "-Tf";
1131 break;
1132 case PROC_NET:
1133 argv[argc++] = "-Tn";
1134 break;
1137 if (safe_mode)
1138 argv[argc++] = "-S";
1140 argv[argc++] = NULL;
1141 execvp(argv0, (char *const *)argv);
1142 err(1, "execvp(%s)", argv0);
1145 int
1146 ui_send_net(int type, uint32_t peerid, const void *data,
1147 uint16_t datalen)
1149 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1150 datalen);
1153 int
1154 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1156 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1157 datalen);
1160 static void __attribute__((noreturn))
1161 usage(int r)
1163 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1164 getprogname());
1165 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1166 exit(r);
1169 int
1170 main(int argc, char * const *argv)
1172 struct imsgev net_ibuf, fs_ibuf;
1173 pid_t pid;
1174 int pipe2net[2], pipe2fs[2];
1175 int ch, configtest = 0, fail = 0;
1176 int proc = -1;
1177 int sessionfd = -1;
1178 int status;
1179 const char *argv0;
1181 argv0 = argv[0];
1183 signal(SIGCHLD, SIG_IGN);
1184 signal(SIGPIPE, SIG_IGN);
1186 if (getenv("NO_COLOR") != NULL)
1187 enable_colors = 0;
1189 fs_init();
1191 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1192 switch (ch) {
1193 case 'C':
1194 exit(ui_print_colors());
1195 case 'c':
1196 fail = 1;
1197 strlcpy(config_path, optarg, sizeof(config_path));
1198 break;
1199 case 'n':
1200 configtest = 1;
1201 break;
1202 case 'h':
1203 usage(0);
1204 case 'S':
1205 safe_mode = 1;
1206 break;
1207 case 'T':
1208 switch (*optarg) {
1209 case 'f':
1210 proc = PROC_FS;
1211 break;
1212 case 'n':
1213 proc = PROC_NET;
1214 break;
1215 default:
1216 errx(1, "invalid process spec %c",
1217 *optarg);
1219 break;
1220 case 'v':
1221 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1222 exit(0);
1223 break;
1224 default:
1225 usage(1);
1229 argc -= optind;
1230 argv += optind;
1232 if (proc != -1) {
1233 if (argc > 0)
1234 usage(1);
1235 else if (proc == PROC_FS)
1236 return fs_main();
1237 else if (proc == PROC_NET)
1238 return net_main();
1239 else
1240 usage(1);
1243 if (argc != 0) {
1244 has_url = 1;
1245 humanify_url(argv[0], url, sizeof(url));
1248 /* setup keys before reading the config */
1249 TAILQ_INIT(&global_map.m);
1250 global_map.unhandled_input = global_key_unbound;
1251 TAILQ_INIT(&minibuffer_map.m);
1253 config_init();
1254 parseconfig(config_path, fail);
1255 if (configtest) {
1256 puts("config OK");
1257 exit(0);
1260 if (download_path == NULL &&
1261 (download_path = strdup("/tmp/")) == NULL)
1262 errx(1, "strdup");
1264 if (!safe_mode && (sessionfd = lock_session()) == -1)
1265 errx(1, "can't lock session, is another instance of "
1266 "telescope already running?");
1268 /* Start children. */
1269 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1270 err(1, "socketpair");
1271 start_child(PROC_FS, argv0, pipe2fs[1]);
1272 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1273 iev_fs = &fs_ibuf;
1274 iev_fs->handler = handle_dispatch_imsg;
1276 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1277 err(1, "socketpair");
1278 start_child(PROC_NET, argv0, pipe2net[1]);
1279 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1280 iev_net = &net_ibuf;
1281 iev_net->handler = handle_dispatch_imsg;
1283 setproctitle("ui");
1285 /* initialize tofu store */
1286 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1288 event_init();
1290 /* initialize the in-memory cache store */
1291 mcache_init();
1293 /* Setup event handler for the autosave */
1294 autosave_init();
1296 /* Setup event handlers for pipes to fs/net */
1297 iev_fs->events = EV_READ;
1298 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1299 iev_fs->handler, iev_fs);
1300 event_add(&iev_fs->ev, NULL);
1302 iev_net->events = EV_READ;
1303 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1304 iev_net->handler, iev_net);
1305 event_add(&iev_net->ev, NULL);
1307 if (ui_init()) {
1308 sandbox_ui_process();
1309 ui_send_fs(IMSG_INIT, 0, NULL, 0);
1310 event_dispatch();
1311 ui_end();
1314 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1315 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1316 imsg_flush(&iev_fs->ibuf);
1317 imsg_flush(&iev_net->ibuf);
1319 /* wait for children to terminate */
1320 do {
1321 pid = wait(&status);
1322 if (pid == -1) {
1323 if (errno != EINTR && errno != ECHILD)
1324 err(1, "wait");
1325 } else if (WIFSIGNALED(status))
1326 warnx("child terminated; signal %d", WTERMSIG(status));
1327 } while (pid != -1 || (pid == -1 && errno == EINTR));
1329 if (!safe_mode && close(sessionfd) == -1)
1330 err(1, "close(sessionfd = %d)", sessionfd);
1332 return 0;