1 #include <sys/socket.h>
14 #include "telescope.h"
17 static struct option longopts[] = {
18 {"colors", no_argument, NULL, 'c'},
19 {"help", no_argument, NULL, 'h'},
20 {"version", no_argument, NULL, 'v'},
24 static const char *opts = "Cc:hnT:v";
26 static struct imsgev *iev_fs, *iev_net;
28 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
29 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
31 enum telescope_process {
37 /* the first is also the fallback one */
38 static struct proto protos[] = {
39 { "gemini", load_gemini_url },
40 { "about", load_about_url },
45 #define CANNOT_FETCH 0
46 #define TOO_MUCH_REDIRECTS 1
47 #define MALFORMED_RESPONSE 2
48 #define UNKNOWN_TYPE_OR_CSET 3
49 #define UNKNOWN_PROTOCOL 4
51 /* XXX: keep in sync with telescope.c:/^normalize_code/ */
52 const char *err_pages[70] = {
53 [CANNOT_FETCH] = "# Couldn't load the page\n",
54 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
55 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
56 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
57 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
59 [10] = "# Input required\n",
60 [11] = "# Input required\n",
61 [40] = "# Temporary failure\n",
62 [41] = "# Server unavailable\n",
63 [42] = "# CGI error\n",
64 [43] = "# Proxy error\n",
65 [44] = "# Slow down\n",
66 [50] = "# Permanent failure\n",
67 [51] = "# Not found\n",
69 [53] = "# Proxy request refused\n",
70 [59] = "# Bad request\n",
71 [60] = "# Client certificate required\n",
72 [61] = "# Certificate not authorised\n",
73 [62] = "# Certificate not valid\n"
76 static void die(void) __attribute__((__noreturn__));
77 static struct tab *tab_by_id(uint32_t);
78 static void handle_imsg_err(struct imsg*, size_t);
79 static void handle_imsg_check_cert(struct imsg*, size_t);
80 static void handle_check_cert_user_choice(int, struct tab *);
81 static void handle_maybe_save_new_cert(int, struct tab *);
82 static void handle_imsg_got_code(struct imsg*, size_t);
83 static void handle_imsg_got_meta(struct imsg*, size_t);
84 static void handle_maybe_save_page(int, struct tab *);
85 static void handle_save_page_path(const char *, struct tab *);
86 static void handle_imsg_file_opened(struct imsg*, size_t);
87 static void handle_imsg_buf(struct imsg*, size_t);
88 static void handle_imsg_eof(struct imsg*, size_t);
89 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
90 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
91 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
92 static void handle_dispatch_imsg(int, short, void*);
93 static void load_page_from_str(struct tab*, const char*);
94 static int do_load_url(struct tab*, const char*);
95 static void parse_session_line(char *, const char **, uint32_t *);
96 static void load_last_session(void);
97 static pid_t start_child(enum telescope_process, const char *, int);
98 static int ui_send_net(int, uint32_t, const void *, uint16_t);
99 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
101 static imsg_handlerfn *handlers[] = {
102 [IMSG_ERR] = handle_imsg_err,
103 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
104 [IMSG_GOT_CODE] = handle_imsg_got_code,
105 [IMSG_GOT_META] = handle_imsg_got_meta,
106 [IMSG_BUF] = handle_imsg_buf,
107 [IMSG_EOF] = handle_imsg_eof,
108 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
109 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
110 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
111 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
114 static struct ohash certs;
116 static void __attribute__((__noreturn__))
123 tab_by_id(uint32_t id)
127 TAILQ_FOREACH(t, &tabshead, tabs) {
136 handle_imsg_err(struct imsg *imsg, size_t datalen)
141 tab = tab_by_id(imsg->hdr.peerid);
144 page[datalen-1] = '\0';
146 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
147 tab->hist_cur->h, page) == -1)
149 load_page_from_str(tab, page);
154 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
156 const char *hash, *host, *port;
158 struct tofu_entry *e;
162 if (hash[datalen-1] != '\0')
165 tab = tab_by_id(imsg->hdr.peerid);
167 if (tab->proxy != NULL) {
168 host = tab->proxy->host;
169 port = tab->proxy->port;
171 host = tab->uri.host;
172 port = tab->uri.port;
175 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
176 /* TODO: an update in libressl/libretls changed
177 * significantly. Find a better approach at storing
179 if (datalen > sizeof(e->hash))
182 tofu_res = 1; /* trust on first use */
183 if ((e = calloc(1, sizeof(*e))) == NULL)
185 strlcpy(e->domain, host, sizeof(e->domain));
186 if (*port != '\0' && strcmp(port, "1965")) {
187 strlcat(e->domain, ":", sizeof(e->domain));
188 strlcat(e->domain, port, sizeof(e->domain));
190 strlcpy(e->hash, hash, sizeof(e->hash));
192 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
194 tofu_res = !strcmp(hash, e->hash);
197 if (e->verified == -1)
198 tab->trust = TS_TEMP_TRUSTED;
199 else if (e->verified == 1)
200 tab->trust = TS_VERIFIED;
202 tab->trust = TS_TRUSTED;
204 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
205 &tofu_res, sizeof(tofu_res));
207 tab->trust = TS_UNTRUSTED;
208 load_page_from_str(tab, "# Certificate mismatch\n");
209 if ((tab->cert = strdup(hash)) == NULL)
211 ui_yornp("Certificate mismatch. Proceed?",
212 handle_check_cert_user_choice, tab);
217 handle_check_cert_user_choice(int accept, struct tab *tab)
219 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
224 * trust the certificate for this session only. If
225 * the page results in a redirect while we're asking
226 * the user to save, we'll end up with an invalid
227 * tabid (one request == one tab id) and crash. It
228 * also makes sense to save it for the current session
229 * if the user accepted it.
231 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
233 ui_yornp("Save the new certificate?",
234 handle_maybe_save_new_cert, tab);
242 handle_maybe_save_new_cert(int accept, struct tab *tab)
244 struct tofu_entry *e;
245 const char *host, *port;
247 if (tab->proxy != NULL) {
248 host = tab->proxy->host;
249 port = tab->proxy->port;
251 host = tab->uri.host;
252 port = tab->uri.port;
258 if ((e = calloc(1, sizeof(*e))) == NULL)
261 strlcpy(e->domain, host, sizeof(e->domain));
262 if (*port != '\0' && strcmp(port, "1965")) {
263 strlcat(e->domain, ":", sizeof(e->domain));
264 strlcat(e->domain, port, sizeof(e->domain));
266 strlcpy(e->hash, tab->cert, sizeof(e->hash));
267 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
269 tofu_update(&certs, e);
271 tab->trust = TS_TRUSTED;
279 normalize_code(int n)
282 if (n == 10 || n == 11)
288 if (n == 30 || n == 31)
296 if (n <= 53 || n == 59)
304 return MALFORMED_RESPONSE;
308 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
312 tab = tab_by_id(imsg->hdr.peerid);
314 if (sizeof(tab->code) != datalen)
317 memcpy(&tab->code, imsg->data, sizeof(tab->code));
318 tab->code = normalize_code(tab->code);
319 if (tab->code != 30 && tab->code != 31)
320 tab->redirect_count = 0;
324 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
328 tab = tab_by_id(imsg->hdr.peerid);
330 if (sizeof(tab->meta) <= datalen)
333 memcpy(tab->meta, imsg->data, datalen);
335 if (tab->code < 10) { /* internal errors */
336 load_page_from_str(tab, err_pages[tab->code]);
337 } else if (tab->code < 20) { /* 1x */
338 load_page_from_str(tab, err_pages[tab->code]);
339 ui_require_input(tab, tab->code == 11);
340 } else if (tab->code == 20) {
341 if (setup_parser_for(tab)) {
342 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
344 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
345 ui_yornp("Can't display page, wanna save?",
346 handle_maybe_save_page, tab);
348 } else if (tab->code < 40) { /* 3x */
349 tab->redirect_count++;
351 /* TODO: make customizable? */
352 if (tab->redirect_count > 5) {
353 load_page_from_str(tab,
354 err_pages[TOO_MUCH_REDIRECTS]);
356 do_load_url(tab, tab->meta);
357 } else { /* 4x, 5x & 6x */
358 load_page_from_str(tab, err_pages[tab->code]);
363 handle_maybe_save_page(int dosave, struct tab *tab)
366 ui_read("Save to path", handle_save_page_path, tab);
372 handle_save_page_path(const char *path, struct tab *tab)
379 tab->path = strdup(path);
381 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
385 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
392 tab = tab_by_id(imsg->hdr.peerid);
394 if (imsg->fd == -1) {
398 if (e[datalen-1] != '\0')
400 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
404 load_page_from_str(tab, page);
408 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
413 handle_imsg_buf(struct imsg *imsg, size_t datalen)
417 char *page, buf[FMT_SCALED_STRSIZE] = {0};
419 tab = tab_by_id(imsg->hdr.peerid);
421 tab->bytes += datalen;
423 if (!tab->buffer.page.parse(&tab->buffer.page,
424 imsg->data, datalen))
427 write(tab->fd, imsg->data, datalen);
428 fmt_scaled(tab->bytes, buf);
429 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
434 load_page_from_str(tab, page);
438 ui_on_tab_refresh(tab);
442 handle_imsg_eof(struct imsg *imsg, size_t datalen)
446 char *page, buf[FMT_SCALED_STRSIZE] = {0};
448 tab = tab_by_id(imsg->hdr.peerid);
451 if (!tab->buffer.page.free(&tab->buffer.page))
454 fmt_scaled(tab->bytes, buf);
455 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
460 load_page_from_str(tab, page);
469 ui_on_tab_refresh(tab);
470 ui_on_tab_loaded(tab);
474 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
478 if (datalen != sizeof(res))
481 memcpy(&res, imsg->data, sizeof(res));
483 message("Added to bookmarks!");
485 message("Failed to add to bookmarks: %s",
490 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
494 if (datalen != sizeof(res))
496 memcpy(&res, imsg->data, datalen);
498 message("Failed to save the cert for: %s",
503 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
507 if (datalen != sizeof(res))
509 memcpy(&res, imsg->data, datalen);
511 message("Failed to update the certificate");
515 handle_dispatch_imsg(int fd, short ev, void *d)
517 struct imsgev *iev = d;
518 dispatch_imsg(iev, ev, handlers, sizeof(handlers));
522 load_page_from_str(struct tab *tab, const char *page)
524 erase_buffer(&tab->buffer);
525 gemtext_initparser(&tab->buffer.page);
526 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
528 if (!tab->buffer.page.free(&tab->buffer.page))
530 ui_on_tab_refresh(tab);
531 ui_on_tab_loaded(tab);
535 load_about_url(struct tab *tab, const char *url)
537 tab->trust = TS_VERIFIED;
539 gemtext_initparser(&tab->buffer.page);
541 ui_send_fs(IMSG_GET, tab->id,
542 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
546 load_gemini_url(struct tab *tab, const char *url)
551 tab->id = tab_new_id();
553 memset(&req, 0, sizeof(req));
554 strlcpy(req.host, tab->uri.host, sizeof(req.host));
555 strlcpy(req.port, tab->uri.port, sizeof(req.host));
557 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
558 strlcat(req.req, "\r\n", sizeof(req.req));
560 req.proto = PROTO_GEMINI;
562 ui_send_net(IMSG_GET_RAW, tab->id,
567 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
572 tab->id = tab_new_id();
575 memset(&req, 0, sizeof(req));
576 strlcpy(req.host, p->host, sizeof(req.host));
577 strlcpy(req.port, p->port, sizeof(req.host));
579 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
580 strlcat(req.req, "\r\n", sizeof(req.req));
582 req.proto = p->proto;
584 ui_send_net(IMSG_GET_RAW, tab->id,
589 * Effectively load the given url in the given tab. Return 1 when
590 * loading the page asynchronously, and thus when an erase_buffer can
591 * be done right after this function return, or 0 when loading the
592 * page synchronously. In this last case, erase_buffer *MUST* be
593 * called by the handling function (such as load_page_from_str).
596 do_load_url(struct tab *tab, const char *url)
612 tab->trust = TS_UNKNOWN;
614 memcpy(&uri, &tab->uri, sizeof(tab->uri));
615 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
616 if (asprintf(&t, "#error loading %s\n>%s\n",
617 url, "Can't parse the URI") == -1)
619 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
620 load_page_from_str(tab, t);
625 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
626 sizeof(tab->hist_cur->h));
628 for (p = protos; p->schema != NULL; ++p) {
629 if (!strcmp(tab->uri.scheme, p->schema)) {
635 TAILQ_FOREACH(proxy, &proxies, proxies) {
636 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
637 load_via_proxy(tab, url, proxy);
642 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
647 * Load url in tab. If tab is marked as lazy, only prepare the url
648 * but don't load it. If tab is lazy and a url was already prepared,
652 load_url(struct tab *tab, const char *url)
656 lazy = tab->flags & TAB_LAZY;
658 if (lazy && tab->hist_cur != NULL) {
660 tab->flags &= ~TAB_LAZY;
663 if (!lazy || tab->hist_cur == NULL) {
664 if (tab->hist_cur != NULL)
665 hist_clear_forward(&tab->hist,
666 TAILQ_NEXT(tab->hist_cur, entries));
668 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
673 strlcpy(tab->buffer.page.title, url,
674 sizeof(tab->buffer.page.title));
675 hist_push(&tab->hist, tab->hist_cur);
678 strlcpy(tab->hist_cur->h, url,
679 sizeof(tab->hist_cur->h));
682 if (!lazy && do_load_url(tab, url))
683 erase_buffer(&tab->buffer);
687 load_previous_page(struct tab *tab)
691 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
694 do_load_url(tab, h->h);
699 load_next_page(struct tab *tab)
703 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
706 do_load_url(tab, h->h);
711 stop_tab(struct tab *tab)
713 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
720 load_page_from_str(tab, "Stopped.\n");
725 add_to_bookmarks(const char *str)
727 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
738 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
740 TAILQ_FOREACH(tab, &tabshead, tabs) {
742 if (tab == current_tab)
743 flags |= TAB_CURRENT;
745 t = tab->hist_cur->h;
746 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
748 t = tab->buffer.page.title;
749 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
752 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
756 * Parse a line of the session file. The format is:
758 * URL [flags,...] [title]\n
761 parse_session_line(char *line, const char **title, uint32_t *flags)
767 if ((s = strchr(line, ' ')) == NULL)
772 if ((t = strchr(s, ' ')) != NULL) {
777 while ((ap = strsep(&s, ",")) != NULL) {
780 else if (!strcmp(ap, "current"))
781 *flags |= TAB_CURRENT;
783 message("unknown tab flag: %s", ap);
788 load_last_session(void)
791 char *nl, *line = NULL;
796 struct tab *tab, *curr = NULL;
798 if ((session = fopen(session_file, "r")) == NULL) {
800 new_tab("about:new");
801 switch_to_tab(new_tab("about:help"));
805 while ((linelen = getline(&line, &linesize, session)) != -1) {
806 if ((nl = strchr(line, '\n')) != NULL)
808 parse_session_line(line, &title, &flags);
809 if ((tab = new_tab(line)) == NULL)
811 strlcpy(tab->buffer.page.title, title,
812 sizeof(tab->buffer.page.title));
813 if (flags & TAB_CURRENT)
818 message("error reading %s: %s",
819 session_file, strerror(errno));
830 start_child(enum telescope_process p, const char *argv0, int fd)
836 switch (pid = fork()) {
846 if (dup2(fd, 3) == -1)
847 err(1, "cannot setup imsg fd");
849 argv[argc++] = argv0;
852 errx(1, "Can't start ui process");
854 argv[argc++] = "-Tf";
857 argv[argc++] = "-Tn";
862 execvp(argv0, (char *const *)argv);
863 err(1, "execvp(%s)", argv0);
867 ui_send_net(int type, uint32_t peerid, const void *data,
870 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
875 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
877 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
881 static void __attribute__((noreturn))
884 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
886 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
891 main(int argc, char * const *argv)
893 struct imsgev net_ibuf, fs_ibuf;
894 int pipe2net[2], pipe2fs[2];
895 int ch, configtest = 0, fail = 0;
900 const char *url = NEW_TAB_URL;
905 signal(SIGCHLD, SIG_IGN);
906 signal(SIGPIPE, SIG_IGN);
908 if (getenv("NO_COLOR") != NULL)
911 strlcpy(path, getenv("HOME"), sizeof(path));
912 strlcat(path, "/.telescope/config", sizeof(path));
914 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
917 exit(ui_print_colors());
920 strlcpy(path, optarg, sizeof(path));
936 errx(1, "invalid process spec %c",
941 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
955 else if (proc == PROC_FS)
957 else if (proc == PROC_NET)
958 return client_main();
968 /* setup keys before reading the config */
969 TAILQ_INIT(&global_map.m);
970 global_map.unhandled_input = global_key_unbound;
971 TAILQ_INIT(&minibuffer_map.m);
974 parseconfig(path, fail);
981 if ((sessionfd = lock_session()) == -1)
982 errx(1, "can't lock session, is another instance of "
983 "telescope already running?");
985 /* Start children. */
986 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
987 err(1, "socketpair");
988 start_child(PROC_FS, argv0, pipe2fs[1]);
989 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
991 iev_fs->handler = handle_dispatch_imsg;
993 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
994 err(1, "socketpair");
995 start_child(PROC_NET, argv0, pipe2net[1]);
996 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
998 iev_net->handler = handle_dispatch_imsg;
1002 /* initialize tofu & load certificates */
1003 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1008 /* Setup event handlers for pipes to fs/net */
1009 iev_fs->events = EV_READ;
1010 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1011 iev_fs->handler, iev_fs);
1012 event_add(&iev_fs->ev, NULL);
1014 iev_net->events = EV_READ;
1015 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1016 iev_net->handler, iev_net);
1017 event_add(&iev_net->ev, NULL);
1020 load_last_session();
1021 if (has_url || TAILQ_EMPTY(&tabshead))
1024 sandbox_ui_process();
1029 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1030 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1031 imsg_flush(&iev_fs->ibuf);
1032 imsg_flush(&iev_net->ibuf);