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"
39 static struct option longopts[] = {
40 {"colors", no_argument, NULL, 'C'},
41 {"colours", no_argument, NULL, 'C'},
42 {"help", no_argument, NULL, 'h'},
43 {"safe", no_argument, NULL, 'S'},
44 {"version", no_argument, NULL, 'v'},
45 {NULL, 0, NULL, 0},
46 };
48 static const char *opts = "Cc:hnST:v";
50 static int has_url;
51 static char url[GEMINI_URL_LEN];
53 /*
54 * Used to know when we're finished loading.
55 */
56 int operating;
58 /*
59 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
60 * anything to the filesystem or execute external programs.
61 */
62 int safe_mode;
64 static struct imsgev *iev_fs, *iev_net;
66 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
67 struct tabshead ktabshead = TAILQ_HEAD_INITIALIZER(ktabshead);
68 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
70 enum telescope_process {
71 PROC_UI,
72 PROC_FS,
73 PROC_NET,
74 };
76 #define CANNOT_FETCH 0
77 #define TOO_MUCH_REDIRECTS 1
78 #define MALFORMED_RESPONSE 2
79 #define UNKNOWN_TYPE_OR_CSET 3
80 #define UNKNOWN_PROTOCOL 4
82 /* XXX: keep in sync with normalize_code */
83 const char *err_pages[70] = {
84 [CANNOT_FETCH] = "# Couldn't load the page\n",
85 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
86 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
87 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
88 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
90 [10] = "# Input required\n",
91 [11] = "# Input required\n",
92 [40] = "# Temporary failure\n",
93 [41] = "# Server unavailable\n",
94 [42] = "# CGI error\n",
95 [43] = "# Proxy error\n",
96 [44] = "# Slow down\n",
97 [50] = "# Permanent failure\n",
98 [51] = "# Not found\n",
99 [52] = "# Gone\n",
100 [53] = "# Proxy request refused\n",
101 [59] = "# Bad request\n",
102 [60] = "# Client certificate required\n",
103 [61] = "# Certificate not authorised\n",
104 [62] = "# Certificate not valid\n"
105 };
107 static void die(void) __attribute__((__noreturn__));
108 static struct tab *tab_by_id(uint32_t);
109 static void handle_imsg_err(struct imsg *, size_t);
110 static void handle_imsg_check_cert(struct imsg *, size_t);
111 static void handle_check_cert_user_choice(int, struct tab *);
112 static void handle_maybe_save_new_cert(int, struct tab *);
113 static void handle_imsg_got_code(struct imsg *, size_t);
114 static void handle_imsg_got_meta(struct imsg *, size_t);
115 static void handle_maybe_save_page(int, struct tab *);
116 static void handle_save_page_path(const char *, struct tab *);
117 static void handle_imsg_file_opened(struct imsg *, size_t);
118 static void handle_imsg_buf(struct imsg *, size_t);
119 static void handle_imsg_eof(struct imsg *, size_t);
120 static void handle_imsg_tofu(struct imsg *, size_t);
121 static void handle_imsg_bookmark_ok(struct imsg *, size_t);
122 static void handle_imsg_save_cert_ok(struct imsg *, size_t);
123 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
124 static void handle_imsg_session(struct imsg *, size_t);
125 static void handle_dispatch_imsg(int, short, void *);
126 static int load_about_url(struct tab *, const char *);
127 static int load_file_url(struct tab *, const char *);
128 static int load_finger_url(struct tab *, const char *);
129 static int load_gemini_url(struct tab *, const char *);
130 static int load_gopher_url(struct tab *, const char *);
131 static int load_via_proxy(struct tab *, const char *,
132 struct proxy *);
133 static int make_request(struct tab *, struct get_req *, int,
134 const char *);
135 static int make_fs_request(struct tab *, int, const char *);
136 static int do_load_url(struct tab *, const char *, const char *, int);
137 static pid_t start_child(enum telescope_process, const char *, int);
139 static struct proto {
140 const char *schema;
141 const char *port;
142 int (*loadfn)(struct tab *, const char *);
143 } protos[] = {
144 {"about", NULL, load_about_url},
145 {"file", NULL, load_file_url},
146 {"finger", "79", load_finger_url},
147 {"gemini", "1965", load_gemini_url},
148 {"gopher", "70", load_gopher_url},
149 {NULL, NULL, NULL},
150 };
152 static imsg_handlerfn *handlers[] = {
153 [IMSG_ERR] = handle_imsg_err,
154 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
155 [IMSG_GOT_CODE] = handle_imsg_got_code,
156 [IMSG_GOT_META] = handle_imsg_got_meta,
157 [IMSG_BUF] = handle_imsg_buf,
158 [IMSG_EOF] = handle_imsg_eof,
159 [IMSG_TOFU] = handle_imsg_tofu,
160 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
161 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
162 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
163 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
164 [IMSG_SESSION_TAB] = handle_imsg_session,
165 [IMSG_SESSION_TAB_HIST] = handle_imsg_session,
166 [IMSG_SESSION_END] = handle_imsg_session,
167 };
169 static struct ohash certs;
171 static void __attribute__((__noreturn__))
172 die(void)
174 abort(); /* TODO */
177 static struct tab *
178 tab_by_id(uint32_t id)
180 struct tab *t;
182 TAILQ_FOREACH(t, &tabshead, tabs) {
183 if (t->id == id)
184 return t;
187 return NULL;
190 static void
191 handle_imsg_err(struct imsg *imsg, size_t datalen)
193 struct tab *tab;
194 char *page;
196 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
197 return;
199 page = imsg->data;
200 page[datalen-1] = '\0';
202 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
203 tab->hist_cur->h, page) == -1)
204 die();
205 load_page_from_str(tab, page);
206 free(page);
209 static void
210 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
212 const char *hash, *host, *port;
213 int tofu_res;
214 struct tofu_entry *e;
215 struct tab *tab;
217 hash = imsg->data;
218 if (hash[datalen-1] != '\0')
219 abort();
221 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
222 return;
224 if (tab->proxy != NULL) {
225 host = tab->proxy->host;
226 port = tab->proxy->port;
227 } else {
228 host = tab->uri.host;
229 port = tab->uri.port;
232 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
233 /* TODO: an update in libressl/libretls changed
234 * significantly. Find a better approach at storing
235 * the certs! */
236 if (datalen > sizeof(e->hash))
237 abort();
239 tofu_res = 1; /* trust on first use */
240 if ((e = calloc(1, sizeof(*e))) == NULL)
241 abort();
242 strlcpy(e->domain, host, sizeof(e->domain));
243 if (*port != '\0' && strcmp(port, "1965")) {
244 strlcat(e->domain, ":", sizeof(e->domain));
245 strlcat(e->domain, port, sizeof(e->domain));
247 strlcpy(e->hash, hash, sizeof(e->hash));
248 tofu_add(&certs, e);
249 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
250 } else
251 tofu_res = !strcmp(hash, e->hash);
253 if (tofu_res) {
254 if (e->verified == -1)
255 tab->trust = TS_TEMP_TRUSTED;
256 else if (e->verified == 1)
257 tab->trust = TS_VERIFIED;
258 else
259 tab->trust = TS_TRUSTED;
261 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
262 &tofu_res, sizeof(tofu_res));
263 } else {
264 tab->trust = TS_UNTRUSTED;
265 load_page_from_str(tab, "# Certificate mismatch\n");
266 if ((tab->cert = strdup(hash)) == NULL)
267 die();
268 ui_yornp("Certificate mismatch. Proceed?",
269 handle_check_cert_user_choice, tab);
273 static void
274 handle_check_cert_user_choice(int accept, struct tab *tab)
276 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
277 sizeof(accept));
279 if (accept) {
280 /*
281 * trust the certificate for this session only. If
282 * the page results in a redirect while we're asking
283 * the user to save, we'll end up with an invalid
284 * tabid (one request == one tab id). It also makes
285 * sense to save it for the current session if the
286 * user accepted it.
287 */
288 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
289 tab->cert);
291 if (!safe_mode)
292 ui_yornp("Save the new certificate?",
293 handle_maybe_save_new_cert, tab);
294 else
295 message("Certificate temporarly trusted");
296 } else {
297 free(tab->cert);
298 tab->cert = NULL;
302 static void
303 handle_maybe_save_new_cert(int accept, struct tab *tab)
305 struct tofu_entry *e;
306 const char *host, *port;
308 if (tab->proxy != NULL) {
309 host = tab->proxy->host;
310 port = tab->proxy->port;
311 } else {
312 host = tab->uri.host;
313 port = tab->uri.port;
316 if (!accept)
317 goto end;
319 if ((e = calloc(1, sizeof(*e))) == NULL)
320 die();
322 strlcpy(e->domain, host, sizeof(e->domain));
323 if (*port != '\0' && strcmp(port, "1965")) {
324 strlcat(e->domain, ":", sizeof(e->domain));
325 strlcat(e->domain, port, sizeof(e->domain));
327 strlcpy(e->hash, tab->cert, sizeof(e->hash));
328 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
330 tofu_update(&certs, e);
332 tab->trust = TS_TRUSTED;
334 end:
335 free(tab->cert);
336 tab->cert = NULL;
339 static inline int
340 normalize_code(int n)
342 if (n < 20) {
343 if (n == 10 || n == 11)
344 return n;
345 return 10;
346 } else if (n < 30) {
347 return 20;
348 } else if (n < 40) {
349 if (n == 30 || n == 31)
350 return n;
351 return 30;
352 } else if (n < 50) {
353 if (n <= 44)
354 return n;
355 return 40;
356 } else if (n < 60) {
357 if (n <= 53 || n == 59)
358 return n;
359 return 50;
360 } else if (n < 70) {
361 if (n <= 62)
362 return n;
363 return 60;
364 } else
365 return MALFORMED_RESPONSE;
368 static void
369 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
371 struct tab *tab;
373 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
374 return;
376 if (sizeof(tab->code) != datalen)
377 die();
379 memcpy(&tab->code, imsg->data, sizeof(tab->code));
380 tab->code = normalize_code(tab->code);
381 if (tab->code != 30 && tab->code != 31)
382 tab->redirect_count = 0;
385 static void
386 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
388 struct tab *tab;
389 char buf[128];
391 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
392 return;
394 if (sizeof(tab->meta) <= datalen)
395 die();
397 memcpy(tab->meta, imsg->data, datalen);
399 if (tab->code < 10) { /* internal errors */
400 load_page_from_str(tab, err_pages[tab->code]);
401 } else if (tab->code < 20) { /* 1x */
402 load_page_from_str(tab, err_pages[tab->code]);
403 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
404 } else if (tab->code == 20) {
405 if (setup_parser_for(tab)) {
406 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
407 } else if (safe_mode) {
408 load_page_from_str(tab,
409 err_pages[UNKNOWN_TYPE_OR_CSET]);
410 } else {
411 struct hist *h;
413 if ((h = hist_pop(&tab->hist)) != NULL)
414 tab->hist_cur = h;
415 snprintf(buf, sizeof(buf),
416 "Can't display \"%s\", save it?", tab->meta);
417 ui_yornp(buf, handle_maybe_save_page, tab);
419 } else if (tab->code < 40) { /* 3x */
420 tab->redirect_count++;
422 /* TODO: make customizable? */
423 if (tab->redirect_count > 5) {
424 load_page_from_str(tab,
425 err_pages[TOO_MUCH_REDIRECTS]);
426 } else
427 do_load_url(tab, tab->meta, NULL, LU_MODE_NOCACHE);
428 } else { /* 4x, 5x & 6x */
429 load_page_from_str(tab, err_pages[tab->code]);
433 static void
434 handle_maybe_save_page(int dosave, struct tab *tab)
436 const char *f;
437 char input[PATH_MAX];
439 /* XXX: this print a message that is confusing */
440 ui_on_tab_loaded(tab);
442 if (!dosave) {
443 stop_tab(tab);
444 return;
447 if ((f = strrchr(tab->uri.path, '/')) == NULL)
448 f = "";
449 else
450 f++;
452 strlcpy(input, download_path, sizeof(input));
453 strlcat(input, f, sizeof(input));
455 ui_read("Save to path", handle_save_page_path, tab, input);
458 static void
459 handle_save_page_path(const char *path, struct tab *tab)
461 if (path == NULL) {
462 stop_tab(tab);
463 return;
466 ui_show_downloads_pane();
468 enqueue_download(tab->id, path);
469 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
471 /*
472 * Change this tab id, the old one is associated with the
473 * download now.
474 */
475 tab->id = tab_new_id();
478 static void
479 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
481 struct download *d;
482 const char *e;
484 /*
485 * There are no reason we shouldn't be able to find the
486 * required download.
487 */
488 if ((d = download_by_id(imsg->hdr.peerid)) == NULL)
489 die();
491 if (imsg->fd == -1) {
492 e = imsg->data;
493 if (e[datalen-1] != '\0')
494 die();
495 message("Can't open file %s: %s", d->path, e);
496 } else {
497 d->fd = imsg->fd;
498 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
502 static void
503 handle_imsg_session(struct imsg *imsg, size_t datalen)
505 static struct tab *curr;
506 static struct tab *tab;
507 struct session_tab st;
508 struct session_tab_hist sth;
509 struct hist *h;
510 int first_time;
512 /*
513 * The fs process tried to send tabs after it has announced
514 * that he's done. Something fishy is going on, better die.
515 */
516 if (operating)
517 die();
519 switch (imsg->hdr.type) {
520 case IMSG_SESSION_TAB:
521 if (datalen != sizeof(st))
522 die();
524 memcpy(&st, imsg->data, sizeof(st));
525 if ((tab = new_tab(st.uri, NULL, NULL)) == NULL)
526 die();
527 strlcpy(tab->buffer.page.title, st.title,
528 sizeof(tab->buffer.page.title));
529 if (st.flags & TAB_CURRENT)
530 curr = tab;
531 if (st.flags & TAB_KILLED)
532 kill_tab(tab, 1);
533 break;
535 case IMSG_SESSION_TAB_HIST:
536 if (tab == NULL || datalen != sizeof(sth))
537 die();
539 memcpy(&sth, imsg->data, sizeof(sth));
540 if (sth.uri[sizeof(sth.uri)-1] != '\0')
541 die();
543 if ((h = calloc(1, sizeof(*h))) == NULL)
544 die();
545 strlcpy(h->h, sth.uri, sizeof(h->h));
547 if (sth.future)
548 hist_push(&tab->hist, h);
549 else
550 hist_add_before(&tab->hist, tab->hist_cur, h);
551 break;
553 case IMSG_SESSION_END:
554 if (datalen != sizeof(first_time))
555 die();
556 memcpy(&first_time, imsg->data, sizeof(first_time));
557 if (first_time) {
558 new_tab("about:new", NULL, NULL);
559 curr = new_tab("about:help", NULL, NULL);
562 operating = 1;
563 if (curr != NULL)
564 switch_to_tab(curr);
565 if (has_url || TAILQ_EMPTY(&tabshead))
566 new_tab(url, NULL, NULL);
567 ui_main_loop();
568 break;
570 default:
571 die();
575 static void
576 handle_imsg_buf(struct imsg *imsg, size_t datalen)
578 struct tab *tab = NULL;
579 struct download *d = NULL;
581 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
582 (d = download_by_id(imsg->hdr.peerid)) == NULL)
583 return;
585 if (tab != NULL) {
586 if (!parser_parse(tab, imsg->data, datalen))
587 die();
588 ui_on_tab_refresh(tab);
589 } else {
590 d->bytes += datalen;
591 write(d->fd, imsg->data, datalen);
592 ui_on_download_refresh();
596 static void
597 handle_imsg_eof(struct imsg *imsg, size_t datalen)
599 struct tab *tab = NULL;
600 struct download *d = NULL;
602 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
603 (d = download_by_id(imsg->hdr.peerid)) == NULL)
604 return;
606 if (tab != NULL) {
607 if (!parser_free(tab))
608 die();
609 if (has_prefix(tab->hist_cur->h, "gemini://") ||
610 has_prefix(tab->hist_cur->h, "gopher://"))
611 mcache_tab(tab);
612 ui_on_tab_refresh(tab);
613 ui_on_tab_loaded(tab);
614 } else {
615 close(d->fd);
616 d->fd = -1;
617 ui_on_download_refresh();
621 static void
622 handle_imsg_tofu(struct imsg *imsg, size_t datalen)
624 struct tofu_entry *e;
626 if (operating)
627 die();
629 if ((e = calloc(1, sizeof(*e))) == NULL)
630 die();
632 if (datalen != sizeof(*e))
633 die();
634 memcpy(e, imsg->data, sizeof(*e));
635 if (e->domain[sizeof(e->domain)-1] != '\0' ||
636 e->hash[sizeof(e->hash)-1] != '\0')
637 die();
638 tofu_add(&certs, e);
641 static void
642 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
644 int res;
646 if (datalen != sizeof(res))
647 die();
649 memcpy(&res, imsg->data, sizeof(res));
650 if (res == 0)
651 message("Added to bookmarks!");
652 else
653 message("Failed to add to bookmarks: %s",
654 strerror(res));
657 static void
658 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
660 int res;
662 if (datalen != sizeof(res))
663 die();
664 memcpy(&res, imsg->data, datalen);
665 if (res != 0)
666 message("Failed to save the cert for: %s",
667 strerror(res));
670 static void
671 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
673 int res;
675 if (datalen != sizeof(res))
676 die();
677 memcpy(&res, imsg->data, datalen);
678 if (!res)
679 message("Failed to update the certificate");
682 static void
683 handle_dispatch_imsg(int fd, short ev, void *d)
685 struct imsgev *iev = d;
687 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
688 err(1, "connection closed");
691 static int
692 load_about_url(struct tab *tab, const char *url)
694 tab->trust = TS_UNKNOWN;
695 parser_init(tab, gemtext_initparser);
696 return make_fs_request(tab, IMSG_GET, url);
699 static int
700 load_file_url(struct tab *tab, const char *url)
702 tab->trust = TS_UNKNOWN;
703 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
706 static int
707 load_finger_url(struct tab *tab, const char *url)
709 struct get_req req;
710 size_t len;
711 char *at;
713 memset(&req, 0, sizeof(req));
714 strlcpy(req.port, tab->uri.port, sizeof(req.port));
716 /*
717 * Sometimes the finger url have the user as path component
718 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
719 * userinfo (e.g. finger://cobradile@finger.farm).
720 */
721 if ((at = strchr(tab->uri.host, '@')) != NULL) {
722 len = at - tab->uri.host;
723 memcpy(req.req, tab->uri.host, len);
725 if (len >= sizeof(req.req))
726 die();
727 req.req[len] = '\0';
729 strlcpy(req.host, at+1, sizeof(req.host));
730 } else {
731 strlcpy(req.host, tab->uri.host, sizeof(req.host));
733 /* +1 to skip the initial `/' */
734 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
736 strlcat(req.req, "\r\n", sizeof(req.req));
738 parser_init(tab, textplain_initparser);
739 return make_request(tab, &req, PROTO_FINGER, NULL);
742 static int
743 load_gemini_url(struct tab *tab, const char *url)
745 struct get_req req;
747 memset(&req, 0, sizeof(req));
748 strlcpy(req.host, tab->uri.host, sizeof(req.host));
749 strlcpy(req.port, tab->uri.port, sizeof(req.port));
751 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
754 static inline const char *
755 gopher_skip_selector(const char *path, int *ret_type)
757 *ret_type = 0;
759 if (!strcmp(path, "/") || *path == '\0') {
760 *ret_type = '1';
761 return path;
764 if (*path != '/')
765 return path;
766 path++;
768 switch (*ret_type = *path) {
769 case '0':
770 case '1':
771 case '7':
772 break;
774 default:
775 *ret_type = 0;
776 path -= 1;
777 return path;
780 return ++path;
783 static int
784 load_gopher_url(struct tab *tab, const char *url)
786 struct get_req req;
787 int type;
788 const char *path;
790 memset(&req, 0, sizeof(req));
791 strlcpy(req.host, tab->uri.host, sizeof(req.host));
792 strlcpy(req.port, tab->uri.port, sizeof(req.port));
794 path = gopher_skip_selector(tab->uri.path, &type);
795 switch (type) {
796 case '0':
797 parser_init(tab, textplain_initparser);
798 break;
799 case '1':
800 parser_init(tab, gophermap_initparser);
801 break;
802 case '7':
803 ui_require_input(tab, 0, PROTO_GOPHER);
804 return load_page_from_str(tab, err_pages[10]);
805 default:
806 return load_page_from_str(tab, "Unknown gopher selector");
809 strlcpy(req.req, path, sizeof(req.req));
810 if (*tab->uri.query != '\0') {
811 strlcat(req.req, "?", sizeof(req.req));
812 strlcat(req.req, tab->uri.query, sizeof(req.req));
814 strlcat(req.req, "\r\n", sizeof(req.req));
816 return make_request(tab, &req, PROTO_GOPHER, NULL);
819 static int
820 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
822 struct get_req req;
824 memset(&req, 0, sizeof(req));
825 strlcpy(req.host, p->host, sizeof(req.host));
826 strlcpy(req.port, p->port, sizeof(req.port));
828 tab->proxy = p;
830 return make_request(tab, &req, p->proto, tab->hist_cur->h);
833 static int
834 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
836 stop_tab(tab);
837 tab->id = tab_new_id();
838 req->proto = proto;
840 if (r != NULL) {
841 strlcpy(req->req, r, sizeof(req->req));
842 strlcat(req->req, "\r\n", sizeof(req->req));
845 start_loading_anim(tab);
846 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
848 /*
849 * So the various load_*_url can `return make_request` and
850 * do_load_url is happy.
851 */
852 return 1;
855 static int
856 make_fs_request(struct tab *tab, int type, const char *r)
858 stop_tab(tab);
859 tab->id = tab_new_id();
861 ui_send_fs(type, tab->id, r, strlen(r)+1);
863 /*
864 * So load_{about,file}_url can `return make_fs_request` and
865 * do_load_url is happy.
866 */
867 return 1;
870 void
871 gopher_send_search_req(struct tab *tab, const char *text)
873 struct get_req req;
875 memset(&req, 0, sizeof(req));
876 strlcpy(req.host, tab->uri.host, sizeof(req.host));
877 strlcpy(req.port, tab->uri.port, sizeof(req.port));
879 /* +2 to skip /7 */
880 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
881 if (*tab->uri.query != '\0') {
882 strlcat(req.req, "?", sizeof(req.req));
883 strlcat(req.req, tab->uri.query, sizeof(req.req));
886 strlcat(req.req, "\t", sizeof(req.req));
887 strlcat(req.req, text, sizeof(req.req));
888 strlcat(req.req, "\r\n", sizeof(req.req));
890 erase_buffer(&tab->buffer);
891 parser_init(tab, gophermap_initparser);
893 make_request(tab, &req, PROTO_GOPHER, NULL);
896 /*
897 * Effectively load the given url in the given tab. Return 1 when
898 * loading the page asynchronously, and thus when an erase_buffer can
899 * be done right after this function return, or 0 when loading the
900 * page synchronously.
901 */
902 static int
903 do_load_url(struct tab *tab, const char *url, const char *base, int mode)
905 struct phos_uri uri;
906 struct proto *p;
907 struct proxy *proxy;
908 int nocache = mode & LU_MODE_NOCACHE;
909 char *t;
911 tab->proxy = NULL;
912 tab->trust = TS_UNKNOWN;
914 if (base == NULL)
915 memcpy(&uri, &tab->uri, sizeof(tab->uri));
916 else
917 phos_parse_absolute_uri(base, &uri);
919 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
920 if (asprintf(&t, "#error loading %s\n>%s\n",
921 url, "Can't parse the URI") == -1)
922 die();
923 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
924 load_page_from_str(tab, t);
925 free(t);
926 return 0;
929 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
930 sizeof(tab->hist_cur->h));
932 if (!nocache && mcache_lookup(tab->hist_cur->h, tab)) {
933 ui_on_tab_refresh(tab);
934 ui_on_tab_loaded(tab);
935 return 0;
938 for (p = protos; p->schema != NULL; ++p) {
939 if (!strcmp(tab->uri.scheme, p->schema)) {
940 /* patch the port */
941 if (*tab->uri.port == '\0' && p->port != NULL)
942 strlcpy(tab->uri.port, p->port,
943 sizeof(tab->uri.port));
945 return p->loadfn(tab, url);
949 TAILQ_FOREACH(proxy, &proxies, proxies) {
950 if (!strcmp(tab->uri.scheme, proxy->match_proto))
951 return load_via_proxy(tab, url, proxy);
954 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
957 /*
958 * Load url in tab and handle history. If a tab is marked as lazy, only
959 * prepare the url but don't load it.
960 */
961 void
962 load_url(struct tab *tab, const char *url, const char *base, int mode)
964 int lazy = tab->flags & TAB_LAZY;
965 int nohist = mode & LU_MODE_NOHIST;
967 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
968 if (tab->hist_cur != NULL)
969 hist_clear_forward(&tab->hist,
970 TAILQ_NEXT(tab->hist_cur, entries));
972 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
973 == NULL) {
974 event_loopbreak();
975 return;
978 strlcpy(tab->buffer.page.title, url,
979 sizeof(tab->buffer.page.title));
980 hist_push(&tab->hist, tab->hist_cur);
982 if (lazy)
983 strlcpy(tab->hist_cur->h, url,
984 sizeof(tab->hist_cur->h));
987 if (!lazy)
988 do_load_url(tab, url, base, mode);
991 void
992 load_url_in_tab(struct tab *tab, const char *url, const char *base, int mode)
994 if (!operating) {
995 load_url(tab, url, base, mode);
996 return;
999 autosave_hook();
1001 message("Loading %s...", url);
1002 load_url(tab, url, base, mode);
1005 int
1006 load_previous_page(struct tab *tab)
1008 struct hist *h;
1010 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
1011 return 0;
1012 tab->hist_cur = h;
1013 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
1014 return 1;
1017 int
1018 load_next_page(struct tab *tab)
1020 struct hist *h;
1022 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
1023 return 0;
1024 tab->hist_cur = h;
1025 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
1026 return 1;
1029 void
1030 add_to_bookmarks(const char *str)
1032 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
1033 str, strlen(str)+1);
1037 * Given a user-entered URL, apply some heuristics to use it:
1039 * - if it's a proper url use it
1040 * - if it starts with a `./' or a `/' assume its a file:// url
1041 * - assume it's a gemini:// url
1043 * `ret' (of which len is the size) will be filled with the resulting
1044 * url.
1046 void
1047 humanify_url(const char *raw, char *ret, size_t len)
1049 struct phos_uri uri;
1050 char buf[PATH_MAX];
1052 if (phos_parse_absolute_uri(raw, &uri)) {
1053 strlcpy(ret, raw, len);
1054 return;
1057 if (has_prefix(raw, "./")) {
1058 strlcpy(ret, "file://", len);
1059 getcwd(buf, sizeof(buf));
1060 strlcat(ret, buf, len);
1061 strlcat(ret, "/", len);
1062 strlcat(ret, raw+2, len);
1063 return;
1066 if (*raw == '/') {
1067 strlcpy(ret, "file://", len);
1068 strlcat(ret, raw, len);
1069 return;
1072 strlcpy(ret, "gemini://", len);
1073 strlcat(ret, raw, len);
1076 static pid_t
1077 start_child(enum telescope_process p, const char *argv0, int fd)
1079 const char *argv[5];
1080 int argc = 0;
1081 pid_t pid;
1083 switch (pid = fork()) {
1084 case -1:
1085 die();
1086 case 0:
1087 break;
1088 default:
1089 close(fd);
1090 return pid;
1093 if (dup2(fd, 3) == -1)
1094 err(1, "cannot setup imsg fd");
1096 argv[argc++] = argv0;
1097 switch (p) {
1098 case PROC_UI:
1099 errx(1, "Can't start ui process");
1100 case PROC_FS:
1101 argv[argc++] = "-Tf";
1102 break;
1103 case PROC_NET:
1104 argv[argc++] = "-Tn";
1105 break;
1108 if (safe_mode)
1109 argv[argc++] = "-S";
1111 argv[argc++] = NULL;
1112 execvp(argv0, (char *const *)argv);
1113 err(1, "execvp(%s)", argv0);
1116 int
1117 ui_send_net(int type, uint32_t peerid, const void *data,
1118 uint16_t datalen)
1120 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1121 datalen);
1124 int
1125 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1127 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1128 datalen);
1131 static void __attribute__((noreturn))
1132 usage(int r)
1134 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1135 getprogname());
1136 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1137 exit(r);
1140 int
1141 main(int argc, char * const *argv)
1143 struct imsgev net_ibuf, fs_ibuf;
1144 pid_t pid;
1145 int pipe2net[2], pipe2fs[2];
1146 int ch, configtest = 0, fail = 0;
1147 int proc = -1;
1148 int sessionfd = -1;
1149 int status;
1150 const char *argv0;
1152 argv0 = argv[0];
1154 signal(SIGCHLD, SIG_IGN);
1155 signal(SIGPIPE, SIG_IGN);
1157 if (getenv("NO_COLOR") != NULL)
1158 enable_colors = 0;
1160 fs_init();
1162 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1163 switch (ch) {
1164 case 'C':
1165 exit(ui_print_colors());
1166 case 'c':
1167 fail = 1;
1168 strlcpy(config_path, optarg, sizeof(config_path));
1169 break;
1170 case 'n':
1171 configtest = 1;
1172 break;
1173 case 'h':
1174 usage(0);
1175 case 'S':
1176 safe_mode = 1;
1177 break;
1178 case 'T':
1179 switch (*optarg) {
1180 case 'f':
1181 proc = PROC_FS;
1182 break;
1183 case 'n':
1184 proc = PROC_NET;
1185 break;
1186 default:
1187 errx(1, "invalid process spec %c",
1188 *optarg);
1190 break;
1191 case 'v':
1192 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1193 exit(0);
1194 break;
1195 default:
1196 usage(1);
1200 argc -= optind;
1201 argv += optind;
1203 if (proc != -1) {
1204 if (argc > 0)
1205 usage(1);
1206 else if (proc == PROC_FS)
1207 return fs_main();
1208 else if (proc == PROC_NET)
1209 return net_main();
1210 else
1211 usage(1);
1214 if (argc != 0) {
1215 has_url = 1;
1216 humanify_url(argv[0], url, sizeof(url));
1219 /* setup keys before reading the config */
1220 TAILQ_INIT(&global_map.m);
1221 global_map.unhandled_input = global_key_unbound;
1222 TAILQ_INIT(&minibuffer_map.m);
1224 config_init();
1225 parseconfig(config_path, fail);
1226 if (configtest) {
1227 puts("config OK");
1228 exit(0);
1231 if (download_path == NULL &&
1232 (download_path = strdup("/tmp/")) == NULL)
1233 errx(1, "strdup");
1235 if (!safe_mode && (sessionfd = lock_session()) == -1)
1236 errx(1, "can't lock session, is another instance of "
1237 "telescope already running?");
1239 /* Start children. */
1240 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1241 err(1, "socketpair");
1242 start_child(PROC_FS, argv0, pipe2fs[1]);
1243 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1244 iev_fs = &fs_ibuf;
1245 iev_fs->handler = handle_dispatch_imsg;
1247 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1248 err(1, "socketpair");
1249 start_child(PROC_NET, argv0, pipe2net[1]);
1250 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1251 iev_net = &net_ibuf;
1252 iev_net->handler = handle_dispatch_imsg;
1254 setproctitle("ui");
1256 /* initialize tofu store */
1257 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1259 event_init();
1261 /* initialize the in-memory cache store */
1262 mcache_init();
1264 /* Setup event handler for the autosave */
1265 autosave_init();
1267 /* Setup event handlers for pipes to fs/net */
1268 iev_fs->events = EV_READ;
1269 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1270 iev_fs->handler, iev_fs);
1271 event_add(&iev_fs->ev, NULL);
1273 iev_net->events = EV_READ;
1274 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1275 iev_net->handler, iev_net);
1276 event_add(&iev_net->ev, NULL);
1278 if (ui_init()) {
1279 sandbox_ui_process();
1280 ui_send_fs(IMSG_INIT, 0, NULL, 0);
1281 event_dispatch();
1282 ui_end();
1285 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1286 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1287 imsg_flush(&iev_fs->ibuf);
1288 imsg_flush(&iev_net->ibuf);
1290 /* wait for children to terminate */
1291 do {
1292 pid = wait(&status);
1293 if (pid == -1) {
1294 if (errno != EINTR && errno != ECHILD)
1295 err(1, "wait");
1296 } else if (WIFSIGNALED(status))
1297 warnx("child terminated; signal %d", WTERMSIG(status));
1298 } while (pid != -1 || (pid == -1 && errno == EINTR));
1300 if (!safe_mode && close(sessionfd) == -1)
1301 err(1, "close(sessionfd = %d)", sessionfd);
1303 return 0;