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/un.h>
21 #include <sys/wait.h>
23 #include <errno.h>
24 #include <getopt.h>
25 #include <signal.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
31 #include "control.h"
32 #include "defaults.h"
33 #include "fs.h"
34 #include "mcache.h"
35 #include "minibuffer.h"
36 #include "parser.h"
37 #include "session.h"
38 #include "telescope.h"
39 #include "ui.h"
40 #include "utils.h"
42 static struct option longopts[] = {
43 {"colors", no_argument, NULL, 'C'},
44 {"colours", no_argument, NULL, 'C'},
45 {"help", no_argument, NULL, 'h'},
46 {"safe", no_argument, NULL, 'S'},
47 {"version", no_argument, NULL, 'v'},
48 {NULL, 0, NULL, 0},
49 };
51 static const char *opts = "Cc:hnST:v";
53 static int has_url;
54 static char url[GEMINI_URL_LEN];
56 /*
57 * Used to know when we're finished loading.
58 */
59 int operating;
61 /*
62 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
63 * anything to the filesystem or execute external programs.
64 */
65 int safe_mode;
67 static struct imsgev *iev_fs, *iev_net;
69 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
70 struct tabshead ktabshead = TAILQ_HEAD_INITIALIZER(ktabshead);
71 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
73 enum telescope_process {
74 PROC_UI,
75 PROC_FS,
76 PROC_NET,
77 };
79 #define CANNOT_FETCH 0
80 #define TOO_MUCH_REDIRECTS 1
81 #define MALFORMED_RESPONSE 2
82 #define UNKNOWN_TYPE_OR_CSET 3
83 #define UNKNOWN_PROTOCOL 4
85 /* XXX: keep in sync with normalize_code */
86 const char *err_pages[70] = {
87 [CANNOT_FETCH] = "# Couldn't load the page\n",
88 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
89 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
90 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
91 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
93 [10] = "# Input required\n",
94 [11] = "# Input required\n",
95 [40] = "# Temporary failure\n",
96 [41] = "# Server unavailable\n",
97 [42] = "# CGI error\n",
98 [43] = "# Proxy error\n",
99 [44] = "# Slow down\n",
100 [50] = "# Permanent failure\n",
101 [51] = "# Not found\n",
102 [52] = "# Gone\n",
103 [53] = "# Proxy request refused\n",
104 [59] = "# Bad request\n",
105 [60] = "# Client certificate required\n",
106 [61] = "# Certificate not authorised\n",
107 [62] = "# Certificate not valid\n"
108 };
110 static void die(void) __attribute__((__noreturn__));
111 static struct tab *tab_by_id(uint32_t);
112 static void handle_imsg_err(struct imsg *, size_t);
113 static void handle_imsg_check_cert(struct imsg *, size_t);
114 static void handle_check_cert_user_choice(int, struct tab *);
115 static void handle_maybe_save_new_cert(int, struct tab *);
116 static void handle_imsg_got_code(struct imsg *, size_t);
117 static void handle_imsg_got_meta(struct imsg *, size_t);
118 static void handle_maybe_save_page(int, struct tab *);
119 static void handle_save_page_path(const char *, struct tab *);
120 static void handle_imsg_file_opened(struct imsg *, size_t);
121 static void handle_imsg_buf(struct imsg *, size_t);
122 static void handle_imsg_eof(struct imsg *, size_t);
123 static void handle_imsg_tofu(struct imsg *, size_t);
124 static void handle_imsg_bookmark_ok(struct imsg *, size_t);
125 static void handle_imsg_save_cert_ok(struct imsg *, size_t);
126 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
127 static void handle_imsg_session(struct imsg *, size_t);
128 static void handle_dispatch_imsg(int, short, void *);
129 static int load_about_url(struct tab *, const char *);
130 static int load_file_url(struct tab *, const char *);
131 static int load_finger_url(struct tab *, const char *);
132 static int load_gemini_url(struct tab *, const char *);
133 static int load_gopher_url(struct tab *, const char *);
134 static int load_via_proxy(struct tab *, const char *,
135 struct proxy *);
136 static int make_request(struct tab *, struct get_req *, int,
137 const char *);
138 static int make_fs_request(struct tab *, int, const char *);
139 static int do_load_url(struct tab *, const char *, const char *, int);
140 static pid_t start_child(enum telescope_process, const char *, int);
141 static void send_url(const char *);
143 static struct proto {
144 const char *schema;
145 const char *port;
146 int (*loadfn)(struct tab *, const char *);
147 } protos[] = {
148 {"about", NULL, load_about_url},
149 {"file", NULL, load_file_url},
150 {"finger", "79", load_finger_url},
151 {"gemini", "1965", load_gemini_url},
152 {"gopher", "70", load_gopher_url},
153 {NULL, NULL, NULL},
154 };
156 static imsg_handlerfn *handlers[] = {
157 [IMSG_ERR] = handle_imsg_err,
158 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
159 [IMSG_GOT_CODE] = handle_imsg_got_code,
160 [IMSG_GOT_META] = handle_imsg_got_meta,
161 [IMSG_BUF] = handle_imsg_buf,
162 [IMSG_EOF] = handle_imsg_eof,
163 [IMSG_TOFU] = handle_imsg_tofu,
164 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
165 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
166 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
167 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
168 [IMSG_SESSION_TAB] = handle_imsg_session,
169 [IMSG_SESSION_TAB_HIST] = handle_imsg_session,
170 [IMSG_SESSION_END] = handle_imsg_session,
171 };
173 static struct ohash certs;
175 static void __attribute__((__noreturn__))
176 die(void)
178 abort(); /* TODO */
181 static struct tab *
182 tab_by_id(uint32_t id)
184 struct tab *t;
186 TAILQ_FOREACH(t, &tabshead, tabs) {
187 if (t->id == id)
188 return t;
191 return NULL;
194 static void
195 handle_imsg_err(struct imsg *imsg, size_t datalen)
197 struct tab *tab;
198 char *page;
200 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
201 return;
203 page = imsg->data;
204 page[datalen-1] = '\0';
206 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
207 tab->hist_cur->h, page) == -1)
208 die();
209 load_page_from_str(tab, page);
210 free(page);
213 static void
214 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
216 const char *hash, *host, *port;
217 int tofu_res;
218 struct tofu_entry *e;
219 struct tab *tab;
221 hash = imsg->data;
222 if (hash[datalen-1] != '\0')
223 abort();
225 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
226 return;
228 if (tab->proxy != NULL) {
229 host = tab->proxy->host;
230 port = tab->proxy->port;
231 } else {
232 host = tab->uri.host;
233 port = tab->uri.port;
236 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
237 /* TODO: an update in libressl/libretls changed
238 * significantly. Find a better approach at storing
239 * the certs! */
240 if (datalen > sizeof(e->hash))
241 abort();
243 tofu_res = 1; /* trust on first use */
244 if ((e = calloc(1, sizeof(*e))) == NULL)
245 abort();
246 strlcpy(e->domain, host, sizeof(e->domain));
247 if (*port != '\0' && strcmp(port, "1965")) {
248 strlcat(e->domain, ":", sizeof(e->domain));
249 strlcat(e->domain, port, sizeof(e->domain));
251 strlcpy(e->hash, hash, sizeof(e->hash));
252 tofu_add(&certs, e);
253 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
254 } else
255 tofu_res = !strcmp(hash, e->hash);
257 if (tofu_res) {
258 if (e->verified == -1)
259 tab->trust = TS_TEMP_TRUSTED;
260 else if (e->verified == 1)
261 tab->trust = TS_VERIFIED;
262 else
263 tab->trust = TS_TRUSTED;
265 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
266 &tofu_res, sizeof(tofu_res));
267 } else {
268 tab->trust = TS_UNTRUSTED;
269 load_page_from_str(tab, "# Certificate mismatch\n");
270 if ((tab->cert = strdup(hash)) == NULL)
271 die();
272 ui_yornp("Certificate mismatch. Proceed?",
273 handle_check_cert_user_choice, tab);
277 static void
278 handle_check_cert_user_choice(int accept, struct tab *tab)
280 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
281 sizeof(accept));
283 if (accept) {
284 /*
285 * trust the certificate for this session only. If
286 * the page results in a redirect while we're asking
287 * the user to save, we'll end up with an invalid
288 * tabid (one request == one tab id). It also makes
289 * sense to save it for the current session if the
290 * user accepted it.
291 */
292 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
293 tab->cert);
295 if (!safe_mode)
296 ui_yornp("Save the new certificate?",
297 handle_maybe_save_new_cert, tab);
298 else
299 message("Certificate temporarly trusted");
300 } else {
301 free(tab->cert);
302 tab->cert = NULL;
306 static void
307 handle_maybe_save_new_cert(int accept, struct tab *tab)
309 struct tofu_entry *e;
310 const char *host, *port;
312 if (tab->proxy != NULL) {
313 host = tab->proxy->host;
314 port = tab->proxy->port;
315 } else {
316 host = tab->uri.host;
317 port = tab->uri.port;
320 if (!accept)
321 goto end;
323 if ((e = calloc(1, sizeof(*e))) == NULL)
324 die();
326 strlcpy(e->domain, host, sizeof(e->domain));
327 if (*port != '\0' && strcmp(port, "1965")) {
328 strlcat(e->domain, ":", sizeof(e->domain));
329 strlcat(e->domain, port, sizeof(e->domain));
331 strlcpy(e->hash, tab->cert, sizeof(e->hash));
332 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
334 tofu_update(&certs, e);
336 tab->trust = TS_TRUSTED;
338 end:
339 free(tab->cert);
340 tab->cert = NULL;
343 static inline int
344 normalize_code(int n)
346 if (n < 20) {
347 if (n == 10 || n == 11)
348 return n;
349 return 10;
350 } else if (n < 30) {
351 return 20;
352 } else if (n < 40) {
353 if (n == 30 || n == 31)
354 return n;
355 return 30;
356 } else if (n < 50) {
357 if (n <= 44)
358 return n;
359 return 40;
360 } else if (n < 60) {
361 if (n <= 53 || n == 59)
362 return n;
363 return 50;
364 } else if (n < 70) {
365 if (n <= 62)
366 return n;
367 return 60;
368 } else
369 return MALFORMED_RESPONSE;
372 static void
373 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
375 struct tab *tab;
377 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
378 return;
380 if (sizeof(tab->code) != datalen)
381 die();
383 memcpy(&tab->code, imsg->data, sizeof(tab->code));
384 tab->code = normalize_code(tab->code);
385 if (tab->code != 30 && tab->code != 31)
386 tab->redirect_count = 0;
389 static void
390 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
392 struct tab *tab;
393 char buf[128];
395 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
396 return;
398 if (sizeof(tab->meta) <= datalen)
399 die();
401 memcpy(tab->meta, imsg->data, datalen);
403 if (tab->code < 10) { /* internal errors */
404 load_page_from_str(tab, err_pages[tab->code]);
405 } else if (tab->code < 20) { /* 1x */
406 free(tab->last_input_url);
407 tab->last_input_url = strdup(tab->hist_cur->h);
408 if (tab->last_input_url == NULL)
409 die();
411 load_page_from_str(tab, err_pages[tab->code]);
412 ui_require_input(tab, tab->code == 11, ir_select_gemini);
413 } else if (tab->code == 20) {
414 if (setup_parser_for(tab)) {
415 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
416 } else if (safe_mode) {
417 load_page_from_str(tab,
418 err_pages[UNKNOWN_TYPE_OR_CSET]);
419 } else {
420 struct hist *h;
422 if ((h = hist_pop(&tab->hist)) != NULL)
423 tab->hist_cur = h;
424 snprintf(buf, sizeof(buf),
425 "Can't display \"%s\", save it?", tab->meta);
426 ui_yornp(buf, handle_maybe_save_page, tab);
428 } else if (tab->code < 40) { /* 3x */
429 tab->redirect_count++;
431 /* TODO: make customizable? */
432 if (tab->redirect_count > 5) {
433 load_page_from_str(tab,
434 err_pages[TOO_MUCH_REDIRECTS]);
435 } else
436 do_load_url(tab, tab->meta, NULL, LU_MODE_NOCACHE);
437 } else { /* 4x, 5x & 6x */
438 load_page_from_str(tab, err_pages[tab->code]);
442 static void
443 handle_maybe_save_page(int dosave, struct tab *tab)
445 const char *f;
446 char input[PATH_MAX];
448 /* XXX: this print a message that is confusing */
449 ui_on_tab_loaded(tab);
451 if (!dosave) {
452 stop_tab(tab);
453 return;
456 if ((f = strrchr(tab->uri.path, '/')) == NULL)
457 f = "";
458 else
459 f++;
461 strlcpy(input, download_path, sizeof(input));
462 strlcat(input, f, sizeof(input));
464 ui_read("Save to path", handle_save_page_path, tab, input);
467 static void
468 handle_save_page_path(const char *path, struct tab *tab)
470 if (path == NULL) {
471 stop_tab(tab);
472 return;
475 ui_show_downloads_pane();
477 enqueue_download(tab->id, path);
478 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
480 /*
481 * Change this tab id, the old one is associated with the
482 * download now.
483 */
484 tab->id = tab_new_id();
487 static void
488 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
490 struct download *d;
491 const char *e;
493 /*
494 * There are no reason we shouldn't be able to find the
495 * required download.
496 */
497 if ((d = download_by_id(imsg->hdr.peerid)) == NULL)
498 die();
500 if (imsg->fd == -1) {
501 e = imsg->data;
502 if (e[datalen-1] != '\0')
503 die();
504 message("Can't open file %s: %s", d->path, e);
505 } else {
506 d->fd = imsg->fd;
507 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
511 static void
512 handle_imsg_session(struct imsg *imsg, size_t datalen)
514 static struct tab *curr;
515 static struct tab *tab;
516 struct session_tab st;
517 struct session_tab_hist sth;
518 struct hist *h;
519 int first_time;
521 /*
522 * The fs process tried to send tabs after it has announced
523 * that he's done. Something fishy is going on, better die.
524 */
525 if (operating)
526 die();
528 switch (imsg->hdr.type) {
529 case IMSG_SESSION_TAB:
530 if (datalen != sizeof(st))
531 die();
533 memcpy(&st, imsg->data, sizeof(st));
534 if ((tab = new_tab(st.uri, NULL, NULL)) == NULL)
535 die();
536 tab->hist_cur->line_off = st.top_line;
537 tab->hist_cur->current_off = st.current_line;
538 strlcpy(tab->buffer.page.title, st.title,
539 sizeof(tab->buffer.page.title));
540 if (st.flags & TAB_CURRENT)
541 curr = tab;
542 if (st.flags & TAB_KILLED)
543 kill_tab(tab, 1);
544 break;
546 case IMSG_SESSION_TAB_HIST:
547 if (tab == NULL || datalen != sizeof(sth))
548 die();
550 memcpy(&sth, imsg->data, sizeof(sth));
551 if (sth.uri[sizeof(sth.uri)-1] != '\0')
552 die();
554 if ((h = calloc(1, sizeof(*h))) == NULL)
555 die();
556 strlcpy(h->h, sth.uri, sizeof(h->h));
558 if (sth.future)
559 hist_push(&tab->hist, h);
560 else
561 hist_add_before(&tab->hist, tab->hist_cur, h);
562 break;
564 case IMSG_SESSION_END:
565 if (datalen != sizeof(first_time))
566 die();
567 memcpy(&first_time, imsg->data, sizeof(first_time));
568 if (first_time) {
569 new_tab("about:new", NULL, NULL);
570 curr = new_tab("about:help", NULL, NULL);
573 operating = 1;
574 if (curr != NULL)
575 switch_to_tab(curr);
576 if (has_url || TAILQ_EMPTY(&tabshead))
577 new_tab(url, NULL, NULL);
578 ui_main_loop();
579 break;
581 default:
582 die();
586 static void
587 handle_imsg_buf(struct imsg *imsg, size_t datalen)
589 struct tab *tab = NULL;
590 struct download *d = NULL;
592 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
593 (d = download_by_id(imsg->hdr.peerid)) == NULL)
594 return;
596 if (tab != NULL) {
597 if (!parser_parse(tab, imsg->data, datalen))
598 die();
599 ui_on_tab_refresh(tab);
600 } else {
601 d->bytes += datalen;
602 write(d->fd, imsg->data, datalen);
603 ui_on_download_refresh();
607 static void
608 handle_imsg_eof(struct imsg *imsg, size_t datalen)
610 struct tab *tab = NULL;
611 struct download *d = NULL;
613 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
614 (d = download_by_id(imsg->hdr.peerid)) == NULL)
615 return;
617 if (tab != NULL) {
618 if (!parser_free(tab))
619 die();
620 if (has_prefix(tab->hist_cur->h, "gemini://") ||
621 has_prefix(tab->hist_cur->h, "gopher://"))
622 mcache_tab(tab);
623 ui_on_tab_refresh(tab);
624 ui_on_tab_loaded(tab);
625 } else {
626 close(d->fd);
627 d->fd = -1;
628 ui_on_download_refresh();
632 static void
633 handle_imsg_tofu(struct imsg *imsg, size_t datalen)
635 struct tofu_entry *e;
637 if (operating)
638 die();
640 if ((e = calloc(1, sizeof(*e))) == NULL)
641 die();
643 if (datalen != sizeof(*e))
644 die();
645 memcpy(e, imsg->data, sizeof(*e));
646 if (e->domain[sizeof(e->domain)-1] != '\0' ||
647 e->hash[sizeof(e->hash)-1] != '\0')
648 die();
649 tofu_add(&certs, e);
652 static void
653 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
655 int res;
657 if (datalen != sizeof(res))
658 die();
660 memcpy(&res, imsg->data, sizeof(res));
661 if (res == 0)
662 message("Added to bookmarks!");
663 else
664 message("Failed to add to bookmarks: %s",
665 strerror(res));
668 static void
669 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
671 int res;
673 if (datalen != sizeof(res))
674 die();
675 memcpy(&res, imsg->data, datalen);
676 if (res != 0)
677 message("Failed to save the cert for: %s",
678 strerror(res));
681 static void
682 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
684 int res;
686 if (datalen != sizeof(res))
687 die();
688 memcpy(&res, imsg->data, datalen);
689 if (!res)
690 message("Failed to update the certificate");
693 static void
694 handle_dispatch_imsg(int fd, short ev, void *d)
696 struct imsgev *iev = d;
698 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
699 err(1, "connection closed");
702 static int
703 load_about_url(struct tab *tab, const char *url)
705 tab->trust = TS_UNKNOWN;
706 parser_init(tab, gemtext_initparser);
707 return make_fs_request(tab, IMSG_GET, url);
710 static int
711 load_file_url(struct tab *tab, const char *url)
713 tab->trust = TS_UNKNOWN;
714 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
717 static int
718 load_finger_url(struct tab *tab, const char *url)
720 struct get_req req;
721 size_t len;
722 char *at;
724 memset(&req, 0, sizeof(req));
725 strlcpy(req.port, tab->uri.port, sizeof(req.port));
727 /*
728 * Sometimes the finger url have the user as path component
729 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
730 * userinfo (e.g. finger://cobradile@finger.farm).
731 */
732 if ((at = strchr(tab->uri.host, '@')) != NULL) {
733 len = at - tab->uri.host;
734 memcpy(req.req, tab->uri.host, len);
736 if (len >= sizeof(req.req))
737 die();
738 req.req[len] = '\0';
740 strlcpy(req.host, at+1, sizeof(req.host));
741 } else {
742 strlcpy(req.host, tab->uri.host, sizeof(req.host));
744 /* +1 to skip the initial `/' */
745 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
747 strlcat(req.req, "\r\n", sizeof(req.req));
749 parser_init(tab, textplain_initparser);
750 return make_request(tab, &req, PROTO_FINGER, NULL);
753 static int
754 load_gemini_url(struct tab *tab, const char *url)
756 struct get_req req;
758 memset(&req, 0, sizeof(req));
759 strlcpy(req.host, tab->uri.host, sizeof(req.host));
760 strlcpy(req.port, tab->uri.port, sizeof(req.port));
762 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
765 static inline const char *
766 gopher_skip_selector(const char *path, int *ret_type)
768 *ret_type = 0;
770 if (!strcmp(path, "/") || *path == '\0') {
771 *ret_type = '1';
772 return path;
775 if (*path != '/')
776 return path;
777 path++;
779 switch (*ret_type = *path) {
780 case '0':
781 case '1':
782 case '7':
783 break;
785 default:
786 *ret_type = 0;
787 path -= 1;
788 return path;
791 return ++path;
794 static int
795 load_gopher_url(struct tab *tab, const char *url)
797 struct get_req req;
798 int type;
799 const char *path;
801 memset(&req, 0, sizeof(req));
802 strlcpy(req.host, tab->uri.host, sizeof(req.host));
803 strlcpy(req.port, tab->uri.port, sizeof(req.port));
805 path = gopher_skip_selector(tab->uri.path, &type);
806 switch (type) {
807 case '0':
808 parser_init(tab, textplain_initparser);
809 break;
810 case '1':
811 parser_init(tab, gophermap_initparser);
812 break;
813 case '7':
814 free(tab->last_input_url);
815 tab->last_input_url = strdup(url);
816 if (tab->last_input_url == NULL)
817 die();
818 ui_require_input(tab, 0, ir_select_gopher);
819 return load_page_from_str(tab, err_pages[10]);
820 default:
821 return load_page_from_str(tab, "Unknown gopher selector");
824 strlcpy(req.req, path, sizeof(req.req));
825 if (*tab->uri.query != '\0') {
826 strlcat(req.req, "?", sizeof(req.req));
827 strlcat(req.req, tab->uri.query, sizeof(req.req));
829 strlcat(req.req, "\r\n", sizeof(req.req));
831 return make_request(tab, &req, PROTO_GOPHER, NULL);
834 static int
835 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
837 struct get_req req;
839 memset(&req, 0, sizeof(req));
840 strlcpy(req.host, p->host, sizeof(req.host));
841 strlcpy(req.port, p->port, sizeof(req.port));
843 tab->proxy = p;
845 return make_request(tab, &req, p->proto, tab->hist_cur->h);
848 static int
849 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
851 stop_tab(tab);
852 tab->id = tab_new_id();
853 req->proto = proto;
855 if (r != NULL) {
856 strlcpy(req->req, r, sizeof(req->req));
857 strlcat(req->req, "\r\n", sizeof(req->req));
860 start_loading_anim(tab);
861 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
863 /*
864 * So the various load_*_url can `return make_request` and
865 * do_load_url is happy.
866 */
867 return 1;
870 static int
871 make_fs_request(struct tab *tab, int type, const char *r)
873 stop_tab(tab);
874 tab->id = tab_new_id();
876 ui_send_fs(type, tab->id, r, strlen(r)+1);
878 /*
879 * So load_{about,file}_url can `return make_fs_request` and
880 * do_load_url is happy.
881 */
882 return 1;
885 void
886 gopher_send_search_req(struct tab *tab, const char *text)
888 struct get_req req;
890 memset(&req, 0, sizeof(req));
891 strlcpy(req.host, tab->uri.host, sizeof(req.host));
892 strlcpy(req.port, tab->uri.port, sizeof(req.port));
894 /* +2 to skip /7 */
895 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
896 if (*tab->uri.query != '\0') {
897 strlcat(req.req, "?", sizeof(req.req));
898 strlcat(req.req, tab->uri.query, sizeof(req.req));
901 strlcat(req.req, "\t", sizeof(req.req));
902 strlcat(req.req, text, sizeof(req.req));
903 strlcat(req.req, "\r\n", sizeof(req.req));
905 erase_buffer(&tab->buffer);
906 parser_init(tab, gophermap_initparser);
908 make_request(tab, &req, PROTO_GOPHER, NULL);
911 int
912 load_page_from_str(struct tab *tab, const char *page)
914 parser_init(tab, gemtext_initparser);
915 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
916 abort();
917 if (!tab->buffer.page.free(&tab->buffer.page))
918 abort();
919 ui_on_tab_refresh(tab);
920 ui_on_tab_loaded(tab);
921 return 0;
924 /*
925 * Effectively load the given url in the given tab. Return 1 when
926 * loading the page asynchronously, and thus when an erase_buffer can
927 * be done right after this function return, or 0 when loading the
928 * page synchronously.
929 */
930 static int
931 do_load_url(struct tab *tab, const char *url, const char *base, int mode)
933 struct phos_uri uri;
934 struct proto *p;
935 struct proxy *proxy;
936 int nocache = mode & LU_MODE_NOCACHE;
937 char *t;
939 tab->proxy = NULL;
940 tab->trust = TS_UNKNOWN;
942 if (base == NULL)
943 memcpy(&uri, &tab->uri, sizeof(tab->uri));
944 else
945 phos_parse_absolute_uri(base, &uri);
947 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
948 if (asprintf(&t, "#error loading %s\n>%s\n",
949 url, "Can't parse the URI") == -1)
950 die();
951 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
952 load_page_from_str(tab, t);
953 free(t);
954 return 0;
957 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
958 sizeof(tab->hist_cur->h));
960 if (!nocache && mcache_lookup(tab->hist_cur->h, tab)) {
961 ui_on_tab_refresh(tab);
962 ui_on_tab_loaded(tab);
963 return 0;
966 for (p = protos; p->schema != NULL; ++p) {
967 if (!strcmp(tab->uri.scheme, p->schema)) {
968 /* patch the port */
969 if (*tab->uri.port == '\0' && p->port != NULL)
970 strlcpy(tab->uri.port, p->port,
971 sizeof(tab->uri.port));
973 return p->loadfn(tab, tab->hist_cur->h);
977 TAILQ_FOREACH(proxy, &proxies, proxies) {
978 if (!strcmp(tab->uri.scheme, proxy->match_proto))
979 return load_via_proxy(tab, url, proxy);
982 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
985 /*
986 * Load url in tab and handle history. If a tab is marked as lazy, only
987 * prepare the url but don't load it.
988 */
989 void
990 load_url(struct tab *tab, const char *url, const char *base, int mode)
992 int lazy = tab->flags & TAB_LAZY;
993 int nohist = mode & LU_MODE_NOHIST;
995 if (operating && lazy) {
996 tab->flags ^= TAB_LAZY;
997 lazy = 0;
998 } else if (tab->hist_cur != NULL)
999 get_scroll_position(tab, &tab->hist_cur->line_off,
1000 &tab->hist_cur->current_off);
1002 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
1003 if (tab->hist_cur != NULL)
1004 hist_clear_forward(&tab->hist,
1005 TAILQ_NEXT(tab->hist_cur, entries));
1007 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
1008 == NULL) {
1009 event_loopbreak();
1010 return;
1013 strlcpy(tab->buffer.page.title, url,
1014 sizeof(tab->buffer.page.title));
1015 hist_push(&tab->hist, tab->hist_cur);
1017 if (lazy)
1018 strlcpy(tab->hist_cur->h, url,
1019 sizeof(tab->hist_cur->h));
1022 if (!lazy)
1023 do_load_url(tab, url, base, mode);
1026 void
1027 load_url_in_tab(struct tab *tab, const char *url, const char *base, int mode)
1029 if (operating) {
1030 autosave_hook();
1031 message("Loading %s...", url);
1034 load_url(tab, url, base, mode);
1037 int
1038 load_previous_page(struct tab *tab)
1040 struct hist *h;
1042 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
1043 return 0;
1044 tab->hist_cur = h;
1045 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
1046 return 1;
1049 int
1050 load_next_page(struct tab *tab)
1052 struct hist *h;
1054 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
1055 return 0;
1056 tab->hist_cur = h;
1057 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
1058 return 1;
1061 void
1062 add_to_bookmarks(const char *str)
1064 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
1065 str, strlen(str)+1);
1069 * Given a user-entered URL, apply some heuristics to use it:
1071 * - if it's a proper url use it
1072 * - if it starts with a `./' or a `/' assume its a file:// url
1073 * - assume it's a gemini:// url
1075 * `ret' (of which len is the size) will be filled with the resulting
1076 * url.
1078 void
1079 humanify_url(const char *raw, char *ret, size_t len)
1081 struct phos_uri uri;
1082 char buf[PATH_MAX];
1084 if (phos_parse_absolute_uri(raw, &uri)) {
1085 strlcpy(ret, raw, len);
1086 return;
1089 if (has_prefix(raw, "./")) {
1090 strlcpy(ret, "file://", len);
1091 getcwd(buf, sizeof(buf));
1092 strlcat(ret, buf, len);
1093 strlcat(ret, "/", len);
1094 strlcat(ret, raw+2, len);
1095 return;
1098 if (*raw == '/') {
1099 strlcpy(ret, "file://", len);
1100 strlcat(ret, raw, len);
1101 return;
1104 strlcpy(ret, "gemini://", len);
1105 strlcat(ret, raw, len);
1108 static pid_t
1109 start_child(enum telescope_process p, const char *argv0, int fd)
1111 const char *argv[5];
1112 int argc = 0;
1113 pid_t pid;
1115 switch (pid = fork()) {
1116 case -1:
1117 die();
1118 case 0:
1119 break;
1120 default:
1121 close(fd);
1122 return pid;
1125 if (dup2(fd, 3) == -1)
1126 err(1, "cannot setup imsg fd");
1128 argv[argc++] = argv0;
1129 switch (p) {
1130 case PROC_UI:
1131 errx(1, "Can't start ui process");
1132 case PROC_FS:
1133 argv[argc++] = "-Tf";
1134 break;
1135 case PROC_NET:
1136 argv[argc++] = "-Tn";
1137 break;
1140 if (safe_mode)
1141 argv[argc++] = "-S";
1143 argv[argc++] = NULL;
1144 execvp(argv0, (char *const *)argv);
1145 err(1, "execvp(%s)", argv0);
1148 static void
1149 send_url(const char *url)
1151 struct sockaddr_un sun;
1152 struct imsgbuf ibuf;
1153 int ctl_sock;
1155 if ((ctl_sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
1156 err(1, "socket");
1158 memset(&sun, 0, sizeof(sun));
1159 sun.sun_family = AF_UNIX;
1160 strlcpy(sun.sun_path, ctlsock_path, sizeof(sun.sun_path));
1162 if (connect(ctl_sock, (struct sockaddr *)&sun, sizeof(sun)) == -1)
1163 err(1, "connect: %s", ctlsock_path);
1165 imsg_init(&ibuf, ctl_sock);
1166 imsg_compose(&ibuf, IMSG_CTL_OPEN_URL, 0, 0, -1, url,
1167 strlen(url) + 1);
1168 imsg_flush(&ibuf);
1169 close(ctl_sock);
1172 int
1173 ui_send_net(int type, uint32_t peerid, const void *data,
1174 uint16_t datalen)
1176 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1177 datalen);
1180 int
1181 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1183 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1184 datalen);
1187 static void __attribute__((noreturn))
1188 usage(int r)
1190 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1191 getprogname());
1192 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1193 exit(r);
1196 int
1197 main(int argc, char * const *argv)
1199 struct imsgev net_ibuf, fs_ibuf;
1200 pid_t pid;
1201 int control_fd;
1202 int pipe2net[2], pipe2fs[2];
1203 int ch, configtest = 0, fail = 0;
1204 int proc = -1;
1205 int sessionfd = -1;
1206 int status;
1207 const char *argv0;
1209 argv0 = argv[0];
1211 signal(SIGCHLD, SIG_IGN);
1212 signal(SIGPIPE, SIG_IGN);
1214 if (getenv("NO_COLOR") != NULL)
1215 enable_colors = 0;
1217 fs_init();
1219 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1220 switch (ch) {
1221 case 'C':
1222 exit(ui_print_colors());
1223 case 'c':
1224 fail = 1;
1225 strlcpy(config_path, optarg, sizeof(config_path));
1226 break;
1227 case 'n':
1228 configtest = 1;
1229 break;
1230 case 'h':
1231 usage(0);
1232 case 'S':
1233 safe_mode = 1;
1234 break;
1235 case 'T':
1236 switch (*optarg) {
1237 case 'f':
1238 proc = PROC_FS;
1239 break;
1240 case 'n':
1241 proc = PROC_NET;
1242 break;
1243 default:
1244 errx(1, "invalid process spec %c",
1245 *optarg);
1247 break;
1248 case 'v':
1249 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1250 exit(0);
1251 break;
1252 default:
1253 usage(1);
1257 argc -= optind;
1258 argv += optind;
1260 if (proc != -1) {
1261 if (argc > 0)
1262 usage(1);
1263 else if (proc == PROC_FS)
1264 return fs_main();
1265 else if (proc == PROC_NET)
1266 return net_main();
1267 else
1268 usage(1);
1271 if (argc != 0) {
1272 has_url = 1;
1273 humanify_url(argv[0], url, sizeof(url));
1276 /* setup keys before reading the config */
1277 TAILQ_INIT(&global_map.m);
1278 global_map.unhandled_input = global_key_unbound;
1279 TAILQ_INIT(&minibuffer_map.m);
1281 config_init();
1282 parseconfig(config_path, fail);
1283 if (configtest) {
1284 puts("config OK");
1285 exit(0);
1288 if (download_path == NULL &&
1289 (download_path = strdup("/tmp/")) == NULL)
1290 errx(1, "strdup");
1292 if (!safe_mode && (sessionfd = lock_session()) == -1) {
1293 if (has_url) {
1294 send_url(url);
1295 exit(0);
1298 errx(1, "can't lock session, is another instance of "
1299 "telescope already running?");
1302 /* Start children. */
1303 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1304 err(1, "socketpair");
1305 start_child(PROC_FS, argv0, pipe2fs[1]);
1306 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1307 iev_fs = &fs_ibuf;
1308 iev_fs->handler = handle_dispatch_imsg;
1310 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1311 err(1, "socketpair");
1312 start_child(PROC_NET, argv0, pipe2net[1]);
1313 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1314 iev_net = &net_ibuf;
1315 iev_net->handler = handle_dispatch_imsg;
1317 setproctitle("ui");
1319 /* initialize tofu store */
1320 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1322 event_init();
1324 if (!safe_mode) {
1325 if ((control_fd = control_init(ctlsock_path)) == -1)
1326 err(1, "control_init %s", ctlsock_path);
1327 control_listen(control_fd);
1330 /* initialize the in-memory cache store */
1331 mcache_init();
1333 /* Setup event handler for the autosave */
1334 autosave_init();
1336 /* Setup event handlers for pipes to fs/net */
1337 iev_fs->events = EV_READ;
1338 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1339 iev_fs->handler, iev_fs);
1340 event_add(&iev_fs->ev, NULL);
1342 iev_net->events = EV_READ;
1343 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1344 iev_net->handler, iev_net);
1345 event_add(&iev_net->ev, NULL);
1347 if (ui_init()) {
1348 sandbox_ui_process();
1349 ui_send_fs(IMSG_INIT, 0, NULL, 0);
1350 event_dispatch();
1351 ui_end();
1354 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1355 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1356 imsg_flush(&iev_fs->ibuf);
1357 imsg_flush(&iev_net->ibuf);
1359 /* wait for children to terminate */
1360 do {
1361 pid = wait(&status);
1362 if (pid == -1) {
1363 if (errno != EINTR && errno != ECHILD)
1364 err(1, "wait");
1365 } else if (WIFSIGNALED(status))
1366 warnx("child terminated; signal %d", WTERMSIG(status));
1367 } while (pid != -1 || (pid == -1 && errno == EINTR));
1369 if (!safe_mode && close(sessionfd) == -1)
1370 err(1, "close(sessionfd = %d)", sessionfd);
1372 return 0;