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 tabshead ktabshead = TAILQ_HEAD_INITIALIZER(ktabshead);
67 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
69 enum telescope_process {
70 PROC_UI,
71 PROC_FS,
72 PROC_NET,
73 };
75 #define CANNOT_FETCH 0
76 #define TOO_MUCH_REDIRECTS 1
77 #define MALFORMED_RESPONSE 2
78 #define UNKNOWN_TYPE_OR_CSET 3
79 #define UNKNOWN_PROTOCOL 4
81 /* XXX: keep in sync with normalize_code */
82 const char *err_pages[70] = {
83 [CANNOT_FETCH] = "# Couldn't load the page\n",
84 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
85 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
86 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
87 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
89 [10] = "# Input required\n",
90 [11] = "# Input required\n",
91 [40] = "# Temporary failure\n",
92 [41] = "# Server unavailable\n",
93 [42] = "# CGI error\n",
94 [43] = "# Proxy error\n",
95 [44] = "# Slow down\n",
96 [50] = "# Permanent failure\n",
97 [51] = "# Not found\n",
98 [52] = "# Gone\n",
99 [53] = "# Proxy request refused\n",
100 [59] = "# Bad request\n",
101 [60] = "# Client certificate required\n",
102 [61] = "# Certificate not authorised\n",
103 [62] = "# Certificate not valid\n"
104 };
106 static void die(void) __attribute__((__noreturn__));
107 static struct tab *tab_by_id(uint32_t);
108 static void handle_imsg_err(struct imsg *, size_t);
109 static void handle_imsg_check_cert(struct imsg *, size_t);
110 static void handle_check_cert_user_choice(int, struct tab *);
111 static void handle_maybe_save_new_cert(int, struct tab *);
112 static void handle_imsg_got_code(struct imsg *, size_t);
113 static void handle_imsg_got_meta(struct imsg *, size_t);
114 static void handle_maybe_save_page(int, struct tab *);
115 static void handle_save_page_path(const char *, struct tab *);
116 static void handle_imsg_file_opened(struct imsg *, size_t);
117 static void handle_imsg_buf(struct imsg *, size_t);
118 static void handle_imsg_eof(struct imsg *, size_t);
119 static void handle_imsg_tofu(struct imsg *, size_t);
120 static void handle_imsg_bookmark_ok(struct imsg *, size_t);
121 static void handle_imsg_save_cert_ok(struct imsg *, size_t);
122 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
123 static void handle_imsg_session(struct imsg *, size_t);
124 static void handle_dispatch_imsg(int, short, void *);
125 static int load_about_url(struct tab *, const char *);
126 static int load_file_url(struct tab *, const char *);
127 static int load_finger_url(struct tab *, const char *);
128 static int load_gemini_url(struct tab *, const char *);
129 static int load_gopher_url(struct tab *, const char *);
130 static int load_via_proxy(struct tab *, const char *,
131 struct proxy *);
132 static int make_request(struct tab *, struct get_req *, int,
133 const char *);
134 static int make_fs_request(struct tab *, int, const char *);
135 static int do_load_url(struct tab *, const char *, const char *);
136 static pid_t start_child(enum telescope_process, const char *, int);
138 static struct proto {
139 const char *schema;
140 const char *port;
141 int (*loadfn)(struct tab *, const char *);
142 } protos[] = {
143 {"about", NULL, load_about_url},
144 {"file", NULL, load_file_url},
145 {"finger", "79", load_finger_url},
146 {"gemini", "1965", load_gemini_url},
147 {"gopher", "70", load_gopher_url},
148 {NULL, NULL, NULL},
149 };
151 static imsg_handlerfn *handlers[] = {
152 [IMSG_ERR] = handle_imsg_err,
153 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
154 [IMSG_GOT_CODE] = handle_imsg_got_code,
155 [IMSG_GOT_META] = handle_imsg_got_meta,
156 [IMSG_BUF] = handle_imsg_buf,
157 [IMSG_EOF] = handle_imsg_eof,
158 [IMSG_TOFU] = handle_imsg_tofu,
159 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
160 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
161 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
162 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
163 [IMSG_SESSION_TAB] = handle_imsg_session,
164 [IMSG_SESSION_TAB_HIST] = handle_imsg_session,
165 [IMSG_SESSION_END] = handle_imsg_session,
166 };
168 static struct ohash certs;
170 static void __attribute__((__noreturn__))
171 die(void)
173 abort(); /* TODO */
176 static struct tab *
177 tab_by_id(uint32_t id)
179 struct tab *t;
181 TAILQ_FOREACH(t, &tabshead, tabs) {
182 if (t->id == id)
183 return t;
186 return NULL;
189 static void
190 handle_imsg_err(struct imsg *imsg, size_t datalen)
192 struct tab *tab;
193 char *page;
195 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
196 return;
198 page = imsg->data;
199 page[datalen-1] = '\0';
201 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
202 tab->hist_cur->h, page) == -1)
203 die();
204 load_page_from_str(tab, page);
205 free(page);
208 static void
209 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
211 const char *hash, *host, *port;
212 int tofu_res;
213 struct tofu_entry *e;
214 struct tab *tab;
216 hash = imsg->data;
217 if (hash[datalen-1] != '\0')
218 abort();
220 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
221 return;
223 if (tab->proxy != NULL) {
224 host = tab->proxy->host;
225 port = tab->proxy->port;
226 } else {
227 host = tab->uri.host;
228 port = tab->uri.port;
231 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
232 /* TODO: an update in libressl/libretls changed
233 * significantly. Find a better approach at storing
234 * the certs! */
235 if (datalen > sizeof(e->hash))
236 abort();
238 tofu_res = 1; /* trust on first use */
239 if ((e = calloc(1, sizeof(*e))) == NULL)
240 abort();
241 strlcpy(e->domain, host, sizeof(e->domain));
242 if (*port != '\0' && strcmp(port, "1965")) {
243 strlcat(e->domain, ":", sizeof(e->domain));
244 strlcat(e->domain, port, sizeof(e->domain));
246 strlcpy(e->hash, hash, sizeof(e->hash));
247 tofu_add(&certs, e);
248 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
249 } else
250 tofu_res = !strcmp(hash, e->hash);
252 if (tofu_res) {
253 if (e->verified == -1)
254 tab->trust = TS_TEMP_TRUSTED;
255 else if (e->verified == 1)
256 tab->trust = TS_VERIFIED;
257 else
258 tab->trust = TS_TRUSTED;
260 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
261 &tofu_res, sizeof(tofu_res));
262 } else {
263 tab->trust = TS_UNTRUSTED;
264 load_page_from_str(tab, "# Certificate mismatch\n");
265 if ((tab->cert = strdup(hash)) == NULL)
266 die();
267 ui_yornp("Certificate mismatch. Proceed?",
268 handle_check_cert_user_choice, tab);
272 static void
273 handle_check_cert_user_choice(int accept, struct tab *tab)
275 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
276 sizeof(accept));
278 if (accept) {
279 /*
280 * trust the certificate for this session only. If
281 * the page results in a redirect while we're asking
282 * the user to save, we'll end up with an invalid
283 * tabid (one request == one tab id). It also makes
284 * sense to save it for the current session if the
285 * user accepted it.
286 */
287 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
288 tab->cert);
290 if (!safe_mode)
291 ui_yornp("Save the new certificate?",
292 handle_maybe_save_new_cert, tab);
293 else
294 message("Certificate temporarly trusted");
295 } else {
296 free(tab->cert);
297 tab->cert = NULL;
301 static void
302 handle_maybe_save_new_cert(int accept, struct tab *tab)
304 struct tofu_entry *e;
305 const char *host, *port;
307 if (tab->proxy != NULL) {
308 host = tab->proxy->host;
309 port = tab->proxy->port;
310 } else {
311 host = tab->uri.host;
312 port = tab->uri.port;
315 if (!accept)
316 goto end;
318 if ((e = calloc(1, sizeof(*e))) == NULL)
319 die();
321 strlcpy(e->domain, host, sizeof(e->domain));
322 if (*port != '\0' && strcmp(port, "1965")) {
323 strlcat(e->domain, ":", sizeof(e->domain));
324 strlcat(e->domain, port, sizeof(e->domain));
326 strlcpy(e->hash, tab->cert, sizeof(e->hash));
327 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
329 tofu_update(&certs, e);
331 tab->trust = TS_TRUSTED;
333 end:
334 free(tab->cert);
335 tab->cert = NULL;
338 static inline int
339 normalize_code(int n)
341 if (n < 20) {
342 if (n == 10 || n == 11)
343 return n;
344 return 10;
345 } else if (n < 30) {
346 return 20;
347 } else if (n < 40) {
348 if (n == 30 || n == 31)
349 return n;
350 return 30;
351 } else if (n < 50) {
352 if (n <= 44)
353 return n;
354 return 40;
355 } else if (n < 60) {
356 if (n <= 53 || n == 59)
357 return n;
358 return 50;
359 } else if (n < 70) {
360 if (n <= 62)
361 return n;
362 return 60;
363 } else
364 return MALFORMED_RESPONSE;
367 static void
368 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
370 struct tab *tab;
372 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
373 return;
375 if (sizeof(tab->code) != datalen)
376 die();
378 memcpy(&tab->code, imsg->data, sizeof(tab->code));
379 tab->code = normalize_code(tab->code);
380 if (tab->code != 30 && tab->code != 31)
381 tab->redirect_count = 0;
384 static void
385 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
387 struct tab *tab;
388 char buf[128];
390 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
391 return;
393 if (sizeof(tab->meta) <= datalen)
394 die();
396 memcpy(tab->meta, imsg->data, datalen);
398 if (tab->code < 10) { /* internal errors */
399 load_page_from_str(tab, err_pages[tab->code]);
400 } else if (tab->code < 20) { /* 1x */
401 load_page_from_str(tab, err_pages[tab->code]);
402 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
403 } else if (tab->code == 20) {
404 if (setup_parser_for(tab)) {
405 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
406 } else if (safe_mode) {
407 load_page_from_str(tab,
408 err_pages[UNKNOWN_TYPE_OR_CSET]);
409 } else {
410 struct hist *h;
412 if ((h = hist_pop(&tab->hist)) != NULL)
413 tab->hist_cur = h;
414 snprintf(buf, sizeof(buf),
415 "Can't display \"%s\", save it?", tab->meta);
416 ui_yornp(buf, handle_maybe_save_page, tab);
418 } else if (tab->code < 40) { /* 3x */
419 tab->redirect_count++;
421 /* TODO: make customizable? */
422 if (tab->redirect_count > 5) {
423 load_page_from_str(tab,
424 err_pages[TOO_MUCH_REDIRECTS]);
425 } else
426 do_load_url(tab, tab->meta, NULL);
427 } else { /* 4x, 5x & 6x */
428 load_page_from_str(tab, err_pages[tab->code]);
432 static void
433 handle_maybe_save_page(int dosave, struct tab *tab)
435 const char *f;
436 char input[PATH_MAX];
438 /* XXX: this print a message that is confusing */
439 ui_on_tab_loaded(tab);
441 if (!dosave) {
442 stop_tab(tab);
443 return;
446 if ((f = strrchr(tab->uri.path, '/')) == NULL)
447 f = "";
448 else
449 f++;
451 strlcpy(input, download_path, sizeof(input));
452 strlcat(input, f, sizeof(input));
454 ui_read("Save to path", handle_save_page_path, tab, input);
457 static void
458 handle_save_page_path(const char *path, struct tab *tab)
460 if (path == NULL) {
461 stop_tab(tab);
462 return;
465 ui_show_downloads_pane();
467 enqueue_download(tab->id, path);
468 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
470 /*
471 * Change this tab id, the old one is associated with the
472 * download now.
473 */
474 tab->id = tab_new_id();
477 static void
478 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
480 struct download *d;
481 const char *e;
483 /*
484 * There are no reason we shouldn't be able to find the
485 * required download.
486 */
487 if ((d = download_by_id(imsg->hdr.peerid)) == NULL)
488 die();
490 if (imsg->fd == -1) {
491 e = imsg->data;
492 if (e[datalen-1] != '\0')
493 die();
494 message("Can't open file %s: %s", d->path, e);
495 } else {
496 d->fd = imsg->fd;
497 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
501 static void
502 handle_imsg_session(struct imsg *imsg, size_t datalen)
504 static struct tab *curr;
505 static struct tab *tab;
506 struct session_tab st;
507 struct session_tab_hist sth;
508 struct hist *h;
509 int first_time;
511 /*
512 * The fs process tried to send tabs after it has announced
513 * that he's done. Something fishy is going on, better die.
514 */
515 if (operating)
516 die();
518 switch (imsg->hdr.type) {
519 case IMSG_SESSION_TAB:
520 if (datalen != sizeof(st))
521 die();
523 memcpy(&st, imsg->data, sizeof(st));
524 if ((tab = new_tab(st.uri, NULL, NULL)) == NULL)
525 die();
526 strlcpy(tab->buffer.page.title, st.title,
527 sizeof(tab->buffer.page.title));
528 if (st.flags & TAB_CURRENT)
529 curr = tab;
530 if (st.flags & TAB_KILLED)
531 kill_tab(tab, 1);
532 break;
534 case IMSG_SESSION_TAB_HIST:
535 if (tab == NULL || datalen != sizeof(sth))
536 die();
538 memcpy(&sth, imsg->data, sizeof(sth));
539 if (sth.uri[sizeof(sth.uri)-1] != '\0')
540 die();
542 if ((h = calloc(1, sizeof(*h))) == NULL)
543 die();
544 strlcpy(h->h, sth.uri, sizeof(h->h));
546 if (sth.future)
547 hist_push(&tab->hist, h);
548 else
549 hist_add_before(&tab->hist, tab->hist_cur, h);
550 break;
552 case IMSG_SESSION_END:
553 if (datalen != sizeof(first_time))
554 die();
555 memcpy(&first_time, imsg->data, sizeof(first_time));
556 if (first_time) {
557 new_tab("about:new", NULL, NULL);
558 curr = new_tab("about:help", NULL, NULL);
561 operating = 1;
562 if (curr != NULL)
563 switch_to_tab(curr);
564 if (has_url || TAILQ_EMPTY(&tabshead))
565 new_tab(url, NULL, NULL);
566 ui_main_loop();
567 break;
569 default:
570 die();
574 static void
575 handle_imsg_buf(struct imsg *imsg, size_t datalen)
577 struct tab *tab = NULL;
578 struct download *d = NULL;
580 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
581 (d = download_by_id(imsg->hdr.peerid)) == NULL)
582 return;
584 if (tab != NULL) {
585 if (!parser_parse(tab, imsg->data, datalen))
586 die();
587 ui_on_tab_refresh(tab);
588 } else {
589 d->bytes += datalen;
590 write(d->fd, imsg->data, datalen);
591 ui_on_download_refresh();
595 static void
596 handle_imsg_eof(struct imsg *imsg, size_t datalen)
598 struct tab *tab = NULL;
599 struct download *d = NULL;
601 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
602 (d = download_by_id(imsg->hdr.peerid)) == NULL)
603 return;
605 if (tab != NULL) {
606 if (!parser_free(tab))
607 die();
608 ui_on_tab_refresh(tab);
609 ui_on_tab_loaded(tab);
610 } else {
611 close(d->fd);
612 d->fd = -1;
613 ui_on_download_refresh();
617 static void
618 handle_imsg_tofu(struct imsg *imsg, size_t datalen)
620 struct tofu_entry *e;
622 if (operating)
623 die();
625 if ((e = calloc(1, sizeof(*e))) == NULL)
626 die();
628 if (datalen != sizeof(*e))
629 die();
630 memcpy(e, imsg->data, sizeof(*e));
631 if (e->domain[sizeof(e->domain)-1] != '\0' ||
632 e->hash[sizeof(e->hash)-1] != '\0')
633 die();
634 tofu_add(&certs, e);
637 static void
638 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
640 int res;
642 if (datalen != sizeof(res))
643 die();
645 memcpy(&res, imsg->data, sizeof(res));
646 if (res == 0)
647 message("Added to bookmarks!");
648 else
649 message("Failed to add to bookmarks: %s",
650 strerror(res));
653 static void
654 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
656 int res;
658 if (datalen != sizeof(res))
659 die();
660 memcpy(&res, imsg->data, datalen);
661 if (res != 0)
662 message("Failed to save the cert for: %s",
663 strerror(res));
666 static void
667 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
669 int res;
671 if (datalen != sizeof(res))
672 die();
673 memcpy(&res, imsg->data, datalen);
674 if (!res)
675 message("Failed to update the certificate");
678 static void
679 handle_dispatch_imsg(int fd, short ev, void *d)
681 struct imsgev *iev = d;
683 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
684 err(1, "connection closed");
687 static int
688 load_about_url(struct tab *tab, const char *url)
690 tab->trust = TS_UNKNOWN;
691 parser_init(tab, gemtext_initparser);
692 return make_fs_request(tab, IMSG_GET, url);
695 static int
696 load_file_url(struct tab *tab, const char *url)
698 tab->trust = TS_UNKNOWN;
699 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
702 static int
703 load_finger_url(struct tab *tab, const char *url)
705 struct get_req req;
706 size_t len;
707 char *at;
709 memset(&req, 0, sizeof(req));
710 strlcpy(req.port, tab->uri.port, sizeof(req.port));
712 /*
713 * Sometimes the finger url have the user as path component
714 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
715 * userinfo (e.g. finger://cobradile@finger.farm).
716 */
717 if ((at = strchr(tab->uri.host, '@')) != NULL) {
718 len = at - tab->uri.host;
719 memcpy(req.req, tab->uri.host, len);
721 if (len >= sizeof(req.req))
722 die();
723 req.req[len] = '\0';
725 strlcpy(req.host, at+1, sizeof(req.host));
726 } else {
727 strlcpy(req.host, tab->uri.host, sizeof(req.host));
729 /* +1 to skip the initial `/' */
730 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
732 strlcat(req.req, "\r\n", sizeof(req.req));
734 parser_init(tab, textplain_initparser);
735 return make_request(tab, &req, PROTO_FINGER, NULL);
738 static int
739 load_gemini_url(struct tab *tab, const char *url)
741 struct get_req req;
743 memset(&req, 0, sizeof(req));
744 strlcpy(req.host, tab->uri.host, sizeof(req.host));
745 strlcpy(req.port, tab->uri.port, sizeof(req.port));
747 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
750 static inline const char *
751 gopher_skip_selector(const char *path, int *ret_type)
753 *ret_type = 0;
755 if (!strcmp(path, "/") || *path == '\0') {
756 *ret_type = '1';
757 return path;
760 if (*path != '/')
761 return path;
762 path++;
764 switch (*ret_type = *path) {
765 case '0':
766 case '1':
767 case '7':
768 break;
770 default:
771 *ret_type = 0;
772 path -= 1;
773 return path;
776 return ++path;
779 static int
780 load_gopher_url(struct tab *tab, const char *url)
782 struct get_req req;
783 int type;
784 const char *path;
786 memset(&req, 0, sizeof(req));
787 strlcpy(req.host, tab->uri.host, sizeof(req.host));
788 strlcpy(req.port, tab->uri.port, sizeof(req.port));
790 path = gopher_skip_selector(tab->uri.path, &type);
791 switch (type) {
792 case '0':
793 parser_init(tab, textplain_initparser);
794 break;
795 case '1':
796 parser_init(tab, gophermap_initparser);
797 break;
798 case '7':
799 ui_require_input(tab, 0, PROTO_GOPHER);
800 return load_page_from_str(tab, err_pages[10]);
801 default:
802 return load_page_from_str(tab, "Unknown gopher selector");
805 strlcpy(req.req, path, sizeof(req.req));
806 if (*tab->uri.query != '\0') {
807 strlcat(req.req, "?", sizeof(req.req));
808 strlcat(req.req, tab->uri.query, sizeof(req.req));
810 strlcat(req.req, "\r\n", sizeof(req.req));
812 return make_request(tab, &req, PROTO_GOPHER, NULL);
815 static int
816 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
818 struct get_req req;
820 memset(&req, 0, sizeof(req));
821 strlcpy(req.host, p->host, sizeof(req.host));
822 strlcpy(req.port, p->port, sizeof(req.port));
824 tab->proxy = p;
826 return make_request(tab, &req, p->proto, tab->hist_cur->h);
829 static int
830 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
832 stop_tab(tab);
833 tab->id = tab_new_id();
834 req->proto = proto;
836 if (r != NULL) {
837 strlcpy(req->req, r, sizeof(req->req));
838 strlcat(req->req, "\r\n", sizeof(req->req));
841 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
843 /*
844 * So the various load_*_url can `return make_request` and
845 * do_load_url is happy.
846 */
847 return 1;
850 static int
851 make_fs_request(struct tab *tab, int type, const char *r)
853 stop_tab(tab);
854 tab->id = tab_new_id();
856 ui_send_fs(type, tab->id, r, strlen(r)+1);
858 /*
859 * So load_{about,file}_url can `return make_fs_request` and
860 * do_load_url is happy.
861 */
862 return 1;
865 void
866 gopher_send_search_req(struct tab *tab, const char *text)
868 struct get_req req;
870 start_loading_anim(tab);
872 memset(&req, 0, sizeof(req));
873 strlcpy(req.host, tab->uri.host, sizeof(req.host));
874 strlcpy(req.port, tab->uri.port, sizeof(req.port));
876 /* +2 to skip /7 */
877 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
878 if (*tab->uri.query != '\0') {
879 strlcat(req.req, "?", sizeof(req.req));
880 strlcat(req.req, tab->uri.query, sizeof(req.req));
883 strlcat(req.req, "\t", sizeof(req.req));
884 strlcat(req.req, text, sizeof(req.req));
885 strlcat(req.req, "\r\n", sizeof(req.req));
887 erase_buffer(&tab->buffer);
888 parser_init(tab, gophermap_initparser);
890 make_request(tab, &req, PROTO_GOPHER, NULL);
893 /*
894 * Effectively load the given url in the given tab. Return 1 when
895 * loading the page asynchronously, and thus when an erase_buffer can
896 * be done right after this function return, or 0 when loading the
897 * page synchronously.
898 */
899 static int
900 do_load_url(struct tab *tab, const char *url, const char *base)
902 struct phos_uri uri;
903 struct proto *p;
904 struct proxy *proxy;
905 char *t;
907 tab->proxy = NULL;
909 tab->trust = TS_UNKNOWN;
911 if (base == NULL)
912 memcpy(&uri, &tab->uri, sizeof(tab->uri));
913 else
914 phos_parse_absolute_uri(base, &uri);
916 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
917 if (asprintf(&t, "#error loading %s\n>%s\n",
918 url, "Can't parse the URI") == -1)
919 die();
920 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
921 load_page_from_str(tab, t);
922 free(t);
923 return 0;
926 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
927 sizeof(tab->hist_cur->h));
929 for (p = protos; p->schema != NULL; ++p) {
930 if (!strcmp(tab->uri.scheme, p->schema)) {
931 /* patch the port */
932 if (*tab->uri.port == '\0' && p->port != NULL)
933 strlcpy(tab->uri.port, p->port,
934 sizeof(tab->uri.port));
936 return p->loadfn(tab, url);
940 TAILQ_FOREACH(proxy, &proxies, proxies) {
941 if (!strcmp(tab->uri.scheme, proxy->match_proto))
942 return load_via_proxy(tab, url, proxy);
945 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
948 /*
949 * Load url in tab and handle history. If a tab is marked as lazy, only
950 * prepare the url but don't load it.
951 */
952 void
953 load_url(struct tab *tab, const char *url, const char *base, int nohist)
955 int lazy = tab->flags & TAB_LAZY;
957 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
958 if (tab->hist_cur != NULL)
959 hist_clear_forward(&tab->hist,
960 TAILQ_NEXT(tab->hist_cur, entries));
962 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
963 == NULL) {
964 event_loopbreak();
965 return;
968 strlcpy(tab->buffer.page.title, url,
969 sizeof(tab->buffer.page.title));
970 hist_push(&tab->hist, tab->hist_cur);
972 if (lazy)
973 strlcpy(tab->hist_cur->h, url,
974 sizeof(tab->hist_cur->h));
977 if (!lazy)
978 do_load_url(tab, url, base);
981 void
982 load_url_in_tab(struct tab *tab, const char *url, const char *base, int nohist)
984 if (!operating) {
985 load_url(tab, url, base, nohist);
986 return;
989 autosave_hook();
991 message("Loading %s...", url);
992 start_loading_anim(tab);
993 load_url(tab, url, base, nohist);
996 int
997 load_previous_page(struct tab *tab)
999 struct hist *h;
1001 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
1002 return 0;
1003 tab->hist_cur = h;
1004 do_load_url(tab, h->h, NULL);
1005 return 1;
1008 int
1009 load_next_page(struct tab *tab)
1011 struct hist *h;
1013 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
1014 return 0;
1015 tab->hist_cur = h;
1016 do_load_url(tab, h->h, NULL);
1017 return 1;
1020 void
1021 add_to_bookmarks(const char *str)
1023 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
1024 str, strlen(str)+1);
1028 * Given a user-entered URL, apply some heuristics to use it:
1030 * - if it's a proper url use it
1031 * - if it starts with a `./' or a `/' assume its a file:// url
1032 * - assume it's a gemini:// url
1034 * `ret' (of which len is the size) will be filled with the resulting
1035 * url.
1037 void
1038 humanify_url(const char *raw, char *ret, size_t len)
1040 struct phos_uri uri;
1041 char buf[PATH_MAX];
1043 if (phos_parse_absolute_uri(raw, &uri)) {
1044 strlcpy(ret, raw, len);
1045 return;
1048 if (has_prefix(raw, "./")) {
1049 strlcpy(ret, "file://", len);
1050 getcwd(buf, sizeof(buf));
1051 strlcat(ret, buf, len);
1052 strlcat(ret, "/", len);
1053 strlcat(ret, raw+2, len);
1054 return;
1057 if (*raw == '/') {
1058 strlcpy(ret, "file://", len);
1059 strlcat(ret, raw, len);
1060 return;
1063 strlcpy(ret, "gemini://", len);
1064 strlcat(ret, raw, len);
1067 static pid_t
1068 start_child(enum telescope_process p, const char *argv0, int fd)
1070 const char *argv[5];
1071 int argc = 0;
1072 pid_t pid;
1074 switch (pid = fork()) {
1075 case -1:
1076 die();
1077 case 0:
1078 break;
1079 default:
1080 close(fd);
1081 return pid;
1084 if (dup2(fd, 3) == -1)
1085 err(1, "cannot setup imsg fd");
1087 argv[argc++] = argv0;
1088 switch (p) {
1089 case PROC_UI:
1090 errx(1, "Can't start ui process");
1091 case PROC_FS:
1092 argv[argc++] = "-Tf";
1093 break;
1094 case PROC_NET:
1095 argv[argc++] = "-Tn";
1096 break;
1099 if (safe_mode)
1100 argv[argc++] = "-S";
1102 argv[argc++] = NULL;
1103 execvp(argv0, (char *const *)argv);
1104 err(1, "execvp(%s)", argv0);
1107 int
1108 ui_send_net(int type, uint32_t peerid, const void *data,
1109 uint16_t datalen)
1111 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1112 datalen);
1115 int
1116 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1118 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1119 datalen);
1122 static void __attribute__((noreturn))
1123 usage(int r)
1125 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1126 getprogname());
1127 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1128 exit(r);
1131 int
1132 main(int argc, char * const *argv)
1134 struct imsgev net_ibuf, fs_ibuf;
1135 pid_t pid;
1136 int pipe2net[2], pipe2fs[2];
1137 int ch, configtest = 0, fail = 0;
1138 int proc = -1;
1139 int sessionfd = -1;
1140 int status;
1141 const char *argv0;
1143 argv0 = argv[0];
1145 signal(SIGCHLD, SIG_IGN);
1146 signal(SIGPIPE, SIG_IGN);
1148 if (getenv("NO_COLOR") != NULL)
1149 enable_colors = 0;
1151 fs_init();
1153 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1154 switch (ch) {
1155 case 'C':
1156 exit(ui_print_colors());
1157 case 'c':
1158 fail = 1;
1159 strlcpy(config_path, optarg, sizeof(config_path));
1160 break;
1161 case 'n':
1162 configtest = 1;
1163 break;
1164 case 'h':
1165 usage(0);
1166 case 'S':
1167 safe_mode = 1;
1168 break;
1169 case 'T':
1170 switch (*optarg) {
1171 case 'f':
1172 proc = PROC_FS;
1173 break;
1174 case 'n':
1175 proc = PROC_NET;
1176 break;
1177 default:
1178 errx(1, "invalid process spec %c",
1179 *optarg);
1181 break;
1182 case 'v':
1183 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1184 exit(0);
1185 break;
1186 default:
1187 usage(1);
1191 argc -= optind;
1192 argv += optind;
1194 if (proc != -1) {
1195 if (argc > 0)
1196 usage(1);
1197 else if (proc == PROC_FS)
1198 return fs_main();
1199 else if (proc == PROC_NET)
1200 return net_main();
1201 else
1202 usage(1);
1205 if (argc != 0) {
1206 has_url = 1;
1207 humanify_url(argv[0], url, sizeof(url));
1210 /* setup keys before reading the config */
1211 TAILQ_INIT(&global_map.m);
1212 global_map.unhandled_input = global_key_unbound;
1213 TAILQ_INIT(&minibuffer_map.m);
1215 config_init();
1216 parseconfig(config_path, fail);
1217 if (configtest) {
1218 puts("config OK");
1219 exit(0);
1222 if (download_path == NULL &&
1223 (download_path = strdup("/tmp/")) == NULL)
1224 errx(1, "strdup");
1226 if (!safe_mode && (sessionfd = lock_session()) == -1)
1227 errx(1, "can't lock session, is another instance of "
1228 "telescope already running?");
1230 /* Start children. */
1231 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1232 err(1, "socketpair");
1233 start_child(PROC_FS, argv0, pipe2fs[1]);
1234 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1235 iev_fs = &fs_ibuf;
1236 iev_fs->handler = handle_dispatch_imsg;
1238 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1239 err(1, "socketpair");
1240 start_child(PROC_NET, argv0, pipe2net[1]);
1241 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1242 iev_net = &net_ibuf;
1243 iev_net->handler = handle_dispatch_imsg;
1245 setproctitle("ui");
1247 /* initialize tofu store */
1248 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1250 event_init();
1252 /* Setup event handler for the autosave */
1253 autosave_init();
1255 /* Setup event handlers for pipes to fs/net */
1256 iev_fs->events = EV_READ;
1257 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1258 iev_fs->handler, iev_fs);
1259 event_add(&iev_fs->ev, NULL);
1261 iev_net->events = EV_READ;
1262 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1263 iev_net->handler, iev_net);
1264 event_add(&iev_net->ev, NULL);
1266 if (ui_init()) {
1267 sandbox_ui_process();
1268 ui_send_fs(IMSG_INIT, 0, NULL, 0);
1269 event_dispatch();
1270 ui_end();
1273 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1274 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1275 imsg_flush(&iev_fs->ibuf);
1276 imsg_flush(&iev_net->ibuf);
1278 /* wait for children to terminate */
1279 do {
1280 pid = wait(&status);
1281 if (pid == -1) {
1282 if (errno != EINTR && errno != ECHILD)
1283 err(1, "wait");
1284 } else if (WIFSIGNALED(status))
1285 warnx("child terminated; signal %d", WTERMSIG(status));
1286 } while (pid != -1 || (pid == -1 && errno == EINTR));
1288 if (!safe_mode && close(sessionfd) == -1)
1289 err(1, "close(sessionfd = %d)", sessionfd);
1291 return 0;