1 #include <sys/socket.h>
15 #include "telescope.h"
18 static struct option longopts[] = {
19 {"colors", no_argument, NULL, 'c'},
20 {"help", no_argument, NULL, 'h'},
21 {"version", no_argument, NULL, 'v'},
25 static const char *opts = "Cc:hnT:v";
27 static struct imsgev *iev_fs, *iev_net;
29 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
30 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
32 enum telescope_process {
38 /* the first is also the fallback one */
39 static struct proto protos[] = {
40 { "gemini", load_gemini_url },
41 { "about", load_about_url },
45 static void die(void) __attribute__((__noreturn__));
46 static struct tab *tab_by_id(uint32_t);
47 static void handle_imsg_err(struct imsg*, size_t);
48 static void handle_imsg_check_cert(struct imsg*, size_t);
49 static void handle_check_cert_user_choice(int, struct tab *);
50 static void handle_maybe_save_new_cert(int, struct tab *);
51 static void handle_imsg_got_code(struct imsg*, size_t);
52 static void handle_imsg_got_meta(struct imsg*, size_t);
53 static void handle_maybe_save_page(int, struct tab *);
54 static void handle_save_page_path(const char *, struct tab *);
55 static void handle_imsg_file_opened(struct imsg*, size_t);
56 static void handle_imsg_buf(struct imsg*, size_t);
57 static void handle_imsg_eof(struct imsg*, size_t);
58 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
59 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
60 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
61 static void handle_dispatch_imsg(int, short, void*);
62 static void load_page_from_str(struct tab*, const char*);
63 static int do_load_url(struct tab*, const char*);
64 static void parse_session_line(char *, uint32_t *);
65 static void load_last_session(void);
66 static pid_t start_child(enum telescope_process, const char *, int);
67 static int ui_send_net(int, uint32_t, const void *, uint16_t);
68 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
70 static imsg_handlerfn *handlers[] = {
71 [IMSG_ERR] = handle_imsg_err,
72 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
73 [IMSG_GOT_CODE] = handle_imsg_got_code,
74 [IMSG_GOT_META] = handle_imsg_got_meta,
75 [IMSG_BUF] = handle_imsg_buf,
76 [IMSG_EOF] = handle_imsg_eof,
77 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
78 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
79 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
80 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
83 static struct ohash certs;
85 static void __attribute__((__noreturn__))
92 tab_by_id(uint32_t id)
96 TAILQ_FOREACH(t, &tabshead, tabs) {
105 handle_imsg_err(struct imsg *imsg, size_t datalen)
110 tab = tab_by_id(imsg->hdr.peerid);
113 page[datalen-1] = '\0';
115 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
116 tab->hist_cur->h, page) == -1)
118 load_page_from_str(tab, page);
123 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
125 const char *hash, *host, *port;
127 struct tofu_entry *e;
131 if (hash[datalen-1] != '\0')
134 tab = tab_by_id(imsg->hdr.peerid);
136 if (tab->proxy != NULL) {
137 host = tab->proxy->host;
138 port = tab->proxy->port;
140 host = tab->uri.host;
141 port = tab->uri.port;
144 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
145 /* TODO: an update in libressl/libretls changed
146 * significantly. Find a better approach at storing
148 if (datalen > sizeof(e->hash))
151 tofu_res = 1; /* trust on first use */
152 if ((e = calloc(1, sizeof(*e))) == NULL)
154 strlcpy(e->domain, host, sizeof(e->domain));
155 if (*port != '\0' && strcmp(port, "1965")) {
156 strlcat(e->domain, ":", sizeof(e->domain));
157 strlcat(e->domain, port, sizeof(e->domain));
159 strlcpy(e->hash, hash, sizeof(e->hash));
161 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
163 tofu_res = !strcmp(hash, e->hash);
166 if (e->verified == -1)
167 tab->trust = TS_TEMP_TRUSTED;
168 else if (e->verified == 1)
169 tab->trust = TS_VERIFIED;
171 tab->trust = TS_TRUSTED;
173 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
174 &tofu_res, sizeof(tofu_res));
176 tab->trust = TS_UNTRUSTED;
177 load_page_from_str(tab, "# Certificate mismatch\n");
178 if ((tab->cert = strdup(hash)) == NULL)
180 ui_yornp("Certificate mismatch. Proceed?",
181 handle_check_cert_user_choice, tab);
186 handle_check_cert_user_choice(int accept, struct tab *tab)
188 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
193 * trust the certificate for this session only. If
194 * the page results in a redirect while we're asking
195 * the user to save, we'll end up with an invalid
196 * tabid (one request == one tab id) and crash. It
197 * also makes sense to save it for the current session
198 * if the user accepted it.
200 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
202 ui_yornp("Save the new certificate?",
203 handle_maybe_save_new_cert, tab);
211 handle_maybe_save_new_cert(int accept, struct tab *tab)
213 struct tofu_entry *e;
214 const char *host, *port;
216 if (tab->proxy != NULL) {
217 host = tab->proxy->host;
218 port = tab->proxy->port;
220 host = tab->uri.host;
221 port = tab->uri.port;
227 if ((e = calloc(1, sizeof(*e))) == NULL)
230 strlcpy(e->domain, host, sizeof(e->domain));
231 if (*port != '\0' && strcmp(port, "1965")) {
232 strlcat(e->domain, ":", sizeof(e->domain));
233 strlcat(e->domain, port, sizeof(e->domain));
235 strlcpy(e->hash, tab->cert, sizeof(e->hash));
236 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
238 tofu_update(&certs, e);
240 tab->trust = TS_TRUSTED;
248 normalize_code(int n)
251 if (n == 10 || n == 11)
257 if (n == 30 || n == 31)
265 if (n <= 53 || n == 59)
273 return MALFORMED_RESPONSE;
277 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
281 tab = tab_by_id(imsg->hdr.peerid);
283 if (sizeof(tab->code) != datalen)
286 memcpy(&tab->code, imsg->data, sizeof(tab->code));
287 tab->code = normalize_code(tab->code);
288 if (tab->code != 30 && tab->code != 31)
289 tab->redirect_count = 0;
293 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
297 tab = tab_by_id(imsg->hdr.peerid);
299 if (sizeof(tab->meta) <= datalen)
302 memcpy(tab->meta, imsg->data, datalen);
304 if (tab->code < 10) { /* internal errors */
305 load_page_from_str(tab, err_pages[tab->code]);
306 } else if (tab->code < 20) { /* 1x */
307 load_page_from_str(tab, err_pages[tab->code]);
308 ui_require_input(tab, tab->code == 11);
309 } else if (tab->code == 20) {
310 if (setup_parser_for(tab)) {
311 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
313 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
314 ui_yornp("Can't display page, wanna save?",
315 handle_maybe_save_page, tab);
317 } else if (tab->code < 40) { /* 3x */
318 tab->redirect_count++;
320 /* TODO: make customizable? */
321 if (tab->redirect_count > 5) {
322 load_page_from_str(tab,
323 err_pages[TOO_MUCH_REDIRECTS]);
325 do_load_url(tab, tab->meta);
326 } else { /* 4x, 5x & 6x */
327 load_page_from_str(tab, err_pages[tab->code]);
332 handle_maybe_save_page(int dosave, struct tab *tab)
335 ui_read("Save to path", handle_save_page_path, tab);
341 handle_save_page_path(const char *path, struct tab *tab)
348 tab->path = strdup(path);
350 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
354 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
361 tab = tab_by_id(imsg->hdr.peerid);
363 if (imsg->fd == -1) {
367 if (e[datalen-1] != '\0')
369 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
373 load_page_from_str(tab, page);
377 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
382 handle_imsg_buf(struct imsg *imsg, size_t datalen)
386 char *page, buf[FMT_SCALED_STRSIZE] = {0};
388 tab = tab_by_id(imsg->hdr.peerid);
390 tab->bytes += datalen;
392 if (!tab->buffer.page.parse(&tab->buffer.page,
393 imsg->data, datalen))
396 write(tab->fd, imsg->data, datalen);
397 fmt_scaled(tab->bytes, buf);
398 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
403 load_page_from_str(tab, page);
407 ui_on_tab_refresh(tab);
411 handle_imsg_eof(struct imsg *imsg, size_t datalen)
415 char *page, buf[FMT_SCALED_STRSIZE] = {0};
417 tab = tab_by_id(imsg->hdr.peerid);
420 if (!tab->buffer.page.free(&tab->buffer.page))
423 fmt_scaled(tab->bytes, buf);
424 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
429 load_page_from_str(tab, page);
438 ui_on_tab_refresh(tab);
439 ui_on_tab_loaded(tab);
443 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
447 if (datalen != sizeof(res))
450 memcpy(&res, imsg->data, sizeof(res));
452 message("Added to bookmarks!");
454 message("Failed to add to bookmarks: %s",
459 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
463 if (datalen != sizeof(res))
465 memcpy(&res, imsg->data, datalen);
467 message("Failed to save the cert for: %s",
472 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
476 if (datalen != sizeof(res))
478 memcpy(&res, imsg->data, datalen);
480 message("Failed to update the certificate");
484 handle_dispatch_imsg(int fd, short ev, void *d)
486 struct imsgev *iev = d;
487 dispatch_imsg(iev, ev, handlers, sizeof(handlers));
491 load_page_from_str(struct tab *tab, const char *page)
493 erase_buffer(&tab->buffer);
494 gemtext_initparser(&tab->buffer.page);
495 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
497 if (!tab->buffer.page.free(&tab->buffer.page))
499 ui_on_tab_refresh(tab);
500 ui_on_tab_loaded(tab);
504 load_about_url(struct tab *tab, const char *url)
506 tab->trust = TS_VERIFIED;
508 gemtext_initparser(&tab->buffer.page);
510 ui_send_fs(IMSG_GET, tab->id,
511 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
515 load_gemini_url(struct tab *tab, const char *url)
520 tab->id = tab_new_id();
522 memset(&req, 0, sizeof(req));
523 strlcpy(req.host, tab->uri.host, sizeof(req.host));
524 strlcpy(req.port, tab->uri.port, sizeof(req.host));
526 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
527 strlcat(req.req, "\r\n", sizeof(req.req));
529 req.proto = PROTO_GEMINI;
531 ui_send_net(IMSG_GET_RAW, tab->id,
536 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
541 tab->id = tab_new_id();
544 memset(&req, 0, sizeof(req));
545 strlcpy(req.host, p->host, sizeof(req.host));
546 strlcpy(req.port, p->port, sizeof(req.host));
548 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
549 strlcat(req.req, "\r\n", sizeof(req.req));
551 req.proto = p->proto;
553 ui_send_net(IMSG_GET_RAW, tab->id,
558 * Effectively load the given url in the given tab. Return 1 when
559 * loading the page asynchronously, and thus when an erase_buffer can
560 * be done right after this function return, or 0 when loading the
561 * page synchronously. In this last case, erase_buffer *MUST* be
562 * called by the handling function (such as load_page_from_str).
565 do_load_url(struct tab *tab, const char *url)
581 tab->trust = TS_UNKNOWN;
583 memcpy(&uri, &tab->uri, sizeof(tab->uri));
584 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
585 if (asprintf(&t, "#error loading %s\n>%s\n",
586 url, "Can't parse the URI") == -1)
588 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
589 load_page_from_str(tab, t);
594 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
595 sizeof(tab->hist_cur->h));
597 for (p = protos; p->schema != NULL; ++p) {
598 if (!strcmp(tab->uri.scheme, p->schema)) {
604 TAILQ_FOREACH(proxy, &proxies, proxies) {
605 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
606 load_via_proxy(tab, url, proxy);
611 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
616 * Load url in tab. If tab is marked as lazy, only prepare the url
617 * but don't load it. If tab is lazy and a url was already prepared,
621 load_url(struct tab *tab, const char *url)
625 lazy = tab->flags & TAB_LAZY;
627 if (lazy && tab->hist_cur != NULL) {
629 tab->flags &= ~TAB_LAZY;
632 if (!lazy || tab->hist_cur == NULL) {
633 if (tab->hist_cur != NULL)
634 hist_clear_forward(&tab->hist,
635 TAILQ_NEXT(tab->hist_cur, entries));
637 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
642 strlcpy(tab->buffer.page.title, url,
643 sizeof(tab->buffer.page.title));
644 hist_push(&tab->hist, tab->hist_cur);
647 strlcpy(tab->hist_cur->h, url,
648 sizeof(tab->hist_cur->h));
651 if (!lazy && do_load_url(tab, url))
652 erase_buffer(&tab->buffer);
656 load_previous_page(struct tab *tab)
660 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
663 do_load_url(tab, h->h);
668 load_next_page(struct tab *tab)
672 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
675 do_load_url(tab, h->h);
680 stop_tab(struct tab *tab)
682 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
689 load_page_from_str(tab, "Stopped.\n");
694 add_to_bookmarks(const char *str)
696 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
706 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
708 TAILQ_FOREACH(tab, &tabshead, tabs) {
710 if (tab == current_tab)
711 flags |= TAB_CURRENT;
712 ui_send_fs(IMSG_SESSION_TAB, flags,
713 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
716 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
720 * Parse a line of the session file. The format is:
725 parse_session_line(char *line, uint32_t *flags)
730 if ((s = strchr(line, ' ')) == NULL)
734 while ((ap = strsep(&s, ",")) != NULL) {
737 else if (!strcmp(ap, "current"))
738 *flags |= TAB_CURRENT;
740 message("unknown tab flag: %s", ap);
745 load_last_session(void)
747 char *nl, *line = NULL;
752 struct tab *tab, *curr;
754 if ((session = fopen(session_file, "r")) == NULL) {
756 current_tab = new_tab("about:help");
760 while ((linelen = getline(&line, &linesize, session)) != -1) {
761 if ((nl = strchr(line, '\n')) != NULL)
763 parse_session_line(line, &flags);
764 if ((tab = new_tab(line)) == NULL)
766 if (flags & TAB_CURRENT)
771 message("error reading %s: %s",
772 session_file, strerror(errno));
783 start_child(enum telescope_process p, const char *argv0, int fd)
789 switch (pid = fork()) {
799 if (dup2(fd, 3) == -1)
800 err(1, "cannot setup imsg fd");
802 argv[argc++] = argv0;
805 errx(1, "Can't start ui process");
807 argv[argc++] = "-Tf";
810 argv[argc++] = "-Tn";
815 execvp(argv0, (char *const *)argv);
816 err(1, "execvp(%s)", argv0);
820 ui_send_net(int type, uint32_t peerid, const void *data,
823 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
828 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
830 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
834 static void __attribute__((noreturn))
837 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
839 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
844 main(int argc, char * const *argv)
846 struct imsgev net_ibuf, fs_ibuf;
847 int pipe2net[2], pipe2fs[2];
848 int ch, configtest = 0, fail = 0;
853 const char *url = NEW_TAB_URL;
858 signal(SIGCHLD, SIG_IGN);
859 signal(SIGPIPE, SIG_IGN);
861 if (getenv("NO_COLOR") != NULL)
864 strlcpy(path, getenv("HOME"), sizeof(path));
865 strlcat(path, "/.telescope/config", sizeof(path));
867 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
870 exit(ui_print_colors());
873 strlcpy(path, optarg, sizeof(path));
889 errx(1, "invalid process spec %c",
894 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
908 else if (proc == PROC_FS)
910 else if (proc == PROC_NET)
911 return client_main();
921 /* setup keys before reading the config */
922 TAILQ_INIT(&global_map.m);
923 global_map.unhandled_input = global_key_unbound;
924 TAILQ_INIT(&minibuffer_map.m);
927 parseconfig(path, fail);
934 if ((sessionfd = lock_session()) == -1)
935 errx(1, "can't lock session, is another instance of "
936 "telescope already running?");
938 /* Start children. */
939 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
940 err(1, "socketpair");
941 start_child(PROC_FS, argv0, pipe2fs[1]);
942 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
944 iev_fs->handler = handle_dispatch_imsg;
946 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
947 err(1, "socketpair");
948 start_child(PROC_NET, argv0, pipe2net[1]);
949 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
951 iev_net->handler = handle_dispatch_imsg;
955 /* initialize tofu & load certificates */
956 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
961 /* Setup event handlers for pipes to fs/net */
962 iev_fs->events = EV_READ;
963 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
964 iev_fs->handler, iev_fs);
965 event_add(&iev_fs->ev, NULL);
967 iev_net->events = EV_READ;
968 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
969 iev_net->handler, iev_net);
970 event_add(&iev_net->ev, NULL);
974 if (has_url || TAILQ_EMPTY(&tabshead))
977 sandbox_ui_process();
982 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
983 ui_send_net(IMSG_QUIT, 0, NULL, 0);
984 imsg_flush(&iev_fs->ibuf);
985 imsg_flush(&iev_net->ibuf);