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 const 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_imsg_history(struct imsg *, size_t);
129 static void handle_dispatch_imsg(int, short, void *);
130 static int load_about_url(struct tab *, const char *);
131 static int load_file_url(struct tab *, const char *);
132 static int load_finger_url(struct tab *, const char *);
133 static int load_gemini_url(struct tab *, const char *);
134 static int load_gopher_url(struct tab *, const char *);
135 static int load_via_proxy(struct tab *, const char *,
136 struct proxy *);
137 static int make_request(struct tab *, struct get_req *, int,
138 const char *);
139 static int make_fs_request(struct tab *, int, const char *);
140 static int do_load_url(struct tab *, const char *, const char *, int);
141 static pid_t start_child(enum telescope_process, const char *, int);
142 static void send_url(const char *);
144 static const struct proto {
145 const char *schema;
146 const char *port;
147 int (*loadfn)(struct tab *, const char *);
148 } protos[] = {
149 {"about", NULL, load_about_url},
150 {"file", NULL, load_file_url},
151 {"finger", "79", load_finger_url},
152 {"gemini", "1965", load_gemini_url},
153 {"gopher", "70", load_gopher_url},
154 {NULL, NULL, NULL},
155 };
157 static imsg_handlerfn *handlers[] = {
158 [IMSG_ERR] = handle_imsg_err,
159 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
160 [IMSG_GOT_CODE] = handle_imsg_got_code,
161 [IMSG_GOT_META] = handle_imsg_got_meta,
162 [IMSG_BUF] = handle_imsg_buf,
163 [IMSG_EOF] = handle_imsg_eof,
164 [IMSG_TOFU] = handle_imsg_tofu,
165 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
166 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
167 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
168 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
169 [IMSG_SESSION_TAB] = handle_imsg_session,
170 [IMSG_SESSION_TAB_HIST] = handle_imsg_session,
171 [IMSG_SESSION_END] = handle_imsg_session,
172 [IMSG_HIST_ITEM] = handle_imsg_history,
173 [IMSG_HIST_END] = handle_imsg_history,
174 };
176 static struct ohash certs;
178 static void __attribute__((__noreturn__))
179 die(void)
181 abort(); /* TODO */
184 static struct tab *
185 tab_by_id(uint32_t id)
187 struct tab *t;
189 TAILQ_FOREACH(t, &tabshead, tabs) {
190 if (t->id == id)
191 return t;
194 return NULL;
197 static void
198 handle_imsg_err(struct imsg *imsg, size_t datalen)
200 struct tab *tab;
201 char *page;
203 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
204 return;
206 page = imsg->data;
207 page[datalen-1] = '\0';
209 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
210 tab->hist_cur->h, page) == -1)
211 die();
212 load_page_from_str(tab, page);
213 free(page);
216 static void
217 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
219 const char *hash, *host, *port;
220 int tofu_res;
221 struct tofu_entry *e;
222 struct tab *tab;
224 hash = imsg->data;
225 if (hash[datalen-1] != '\0')
226 abort();
228 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
229 return;
231 if (tab->proxy != NULL) {
232 host = tab->proxy->host;
233 port = tab->proxy->port;
234 } else {
235 host = tab->uri.host;
236 port = tab->uri.port;
239 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
240 /* TODO: an update in libressl/libretls changed
241 * significantly. Find a better approach at storing
242 * the certs! */
243 if (datalen > sizeof(e->hash))
244 abort();
246 tofu_res = 1; /* trust on first use */
247 if ((e = calloc(1, sizeof(*e))) == NULL)
248 abort();
249 strlcpy(e->domain, host, sizeof(e->domain));
250 if (*port != '\0' && strcmp(port, "1965")) {
251 strlcat(e->domain, ":", sizeof(e->domain));
252 strlcat(e->domain, port, sizeof(e->domain));
254 strlcpy(e->hash, hash, sizeof(e->hash));
255 tofu_add(&certs, e);
256 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
257 } else
258 tofu_res = !strcmp(hash, e->hash);
260 if (tofu_res) {
261 if (e->verified == -1)
262 tab->trust = TS_TEMP_TRUSTED;
263 else if (e->verified == 1)
264 tab->trust = TS_VERIFIED;
265 else
266 tab->trust = TS_TRUSTED;
268 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
269 &tofu_res, sizeof(tofu_res));
270 } else {
271 tab->trust = TS_UNTRUSTED;
272 load_page_from_str(tab, "# Certificate mismatch\n");
273 if ((tab->cert = strdup(hash)) == NULL)
274 die();
275 ui_yornp("Certificate mismatch. Proceed?",
276 handle_check_cert_user_choice, tab);
280 static void
281 handle_check_cert_user_choice(int accept, struct tab *tab)
283 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
284 sizeof(accept));
286 if (accept) {
287 /*
288 * trust the certificate for this session only. If
289 * the page results in a redirect while we're asking
290 * the user to save, we'll end up with an invalid
291 * tabid (one request == one tab id). It also makes
292 * sense to save it for the current session if the
293 * user accepted it.
294 */
295 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
296 tab->cert);
298 if (!safe_mode)
299 ui_yornp("Save the new certificate?",
300 handle_maybe_save_new_cert, tab);
301 else
302 message("Certificate temporarly trusted");
303 } else {
304 free(tab->cert);
305 tab->cert = NULL;
309 static void
310 handle_maybe_save_new_cert(int accept, struct tab *tab)
312 struct tofu_entry *e;
313 const char *host, *port;
315 if (tab->proxy != NULL) {
316 host = tab->proxy->host;
317 port = tab->proxy->port;
318 } else {
319 host = tab->uri.host;
320 port = tab->uri.port;
323 if (!accept)
324 goto end;
326 if ((e = calloc(1, sizeof(*e))) == NULL)
327 die();
329 strlcpy(e->domain, host, sizeof(e->domain));
330 if (*port != '\0' && strcmp(port, "1965")) {
331 strlcat(e->domain, ":", sizeof(e->domain));
332 strlcat(e->domain, port, sizeof(e->domain));
334 strlcpy(e->hash, tab->cert, sizeof(e->hash));
335 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
337 tofu_update(&certs, e);
339 tab->trust = TS_TRUSTED;
341 end:
342 free(tab->cert);
343 tab->cert = NULL;
346 static inline int
347 normalize_code(int n)
349 if (n < 20) {
350 if (n == 10 || n == 11)
351 return n;
352 return 10;
353 } else if (n < 30) {
354 return 20;
355 } else if (n < 40) {
356 if (n == 30 || n == 31)
357 return n;
358 return 30;
359 } else if (n < 50) {
360 if (n <= 44)
361 return n;
362 return 40;
363 } else if (n < 60) {
364 if (n <= 53 || n == 59)
365 return n;
366 return 50;
367 } else if (n < 70) {
368 if (n <= 62)
369 return n;
370 return 60;
371 } else
372 return MALFORMED_RESPONSE;
375 static void
376 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
378 struct tab *tab;
380 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
381 return;
383 if (sizeof(tab->code) != datalen)
384 die();
386 memcpy(&tab->code, imsg->data, sizeof(tab->code));
387 tab->code = normalize_code(tab->code);
388 if (tab->code != 30 && tab->code != 31)
389 tab->redirect_count = 0;
392 static void
393 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
395 struct tab *tab;
396 char buf[128];
398 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
399 return;
401 if (sizeof(tab->meta) <= datalen)
402 die();
404 memcpy(tab->meta, imsg->data, datalen);
406 if (tab->code < 10) { /* internal errors */
407 load_page_from_str(tab, err_pages[tab->code]);
408 } else if (tab->code < 20) { /* 1x */
409 free(tab->last_input_url);
410 tab->last_input_url = strdup(tab->hist_cur->h);
411 if (tab->last_input_url == NULL)
412 die();
414 load_page_from_str(tab, err_pages[tab->code]);
415 ui_require_input(tab, tab->code == 11, ir_select_gemini);
416 } else if (tab->code == 20) {
417 history_add(tab->hist_cur->h);
418 if (setup_parser_for(tab)) {
419 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
420 } else if (safe_mode) {
421 load_page_from_str(tab,
422 err_pages[UNKNOWN_TYPE_OR_CSET]);
423 } else {
424 struct hist *h;
426 if ((h = hist_pop(&tab->hist)) != NULL)
427 tab->hist_cur = h;
428 snprintf(buf, sizeof(buf),
429 "Can't display \"%s\", save it?", tab->meta);
430 ui_yornp(buf, handle_maybe_save_page, tab);
432 } else if (tab->code < 40) { /* 3x */
433 tab->redirect_count++;
435 /* TODO: make customizable? */
436 if (tab->redirect_count > 5) {
437 load_page_from_str(tab,
438 err_pages[TOO_MUCH_REDIRECTS]);
439 } else
440 do_load_url(tab, tab->meta, NULL, LU_MODE_NOCACHE);
441 } else { /* 4x, 5x & 6x */
442 load_page_from_str(tab, err_pages[tab->code]);
446 static void
447 handle_maybe_save_page(int dosave, struct tab *tab)
449 const char *f;
450 char input[PATH_MAX];
452 /* XXX: this print a message that is confusing */
453 ui_on_tab_loaded(tab);
455 if (!dosave) {
456 stop_tab(tab);
457 return;
460 if ((f = strrchr(tab->uri.path, '/')) == NULL)
461 f = "";
462 else
463 f++;
465 strlcpy(input, download_path, sizeof(input));
466 strlcat(input, f, sizeof(input));
468 ui_read("Save to path", handle_save_page_path, tab, input);
471 static void
472 handle_save_page_path(const char *path, struct tab *tab)
474 if (path == NULL) {
475 stop_tab(tab);
476 return;
479 ui_show_downloads_pane();
481 enqueue_download(tab->id, path, 0);
482 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
484 /*
485 * Change this tab id, the old one is associated with the
486 * download now.
487 */
488 tab->id = tab_new_id();
491 static void
492 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
494 struct download *d;
495 const char *e;
497 /*
498 * There are no reason we shouldn't be able to find the
499 * required download.
500 */
501 if ((d = download_by_id(imsg->hdr.peerid)) == NULL)
502 die();
504 if (imsg->fd == -1) {
505 e = imsg->data;
506 if (e[datalen-1] != '\0')
507 die();
508 message("Can't open file %s: %s", d->path, e);
509 } else if (d->buffer) {
510 FILE *fp;
511 int r;
513 if ((fp = fdopen(imsg->fd, "w")) != NULL) {
514 r = parser_serialize(current_tab, (printfn)fprintf,
515 fp);
516 if (!r)
517 message("Failed to save the page.");
518 fclose(fp);
521 dequeue_first_download();
522 }else {
523 d->fd = imsg->fd;
524 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
528 static void
529 handle_imsg_session(struct imsg *imsg, size_t datalen)
531 static struct tab *curr;
532 static struct tab *tab;
533 struct session_tab st;
534 struct session_tab_hist sth;
535 struct hist *h;
536 int first_time;
538 /*
539 * The fs process tried to send tabs after it has announced
540 * that he's done. Something fishy is going on, better die.
541 */
542 if (operating)
543 die();
545 switch (imsg->hdr.type) {
546 case IMSG_SESSION_TAB:
547 if (datalen != sizeof(st))
548 die();
550 memcpy(&st, imsg->data, sizeof(st));
551 if ((tab = new_tab(st.uri, NULL, NULL)) == NULL)
552 die();
553 tab->hist_cur->line_off = st.top_line;
554 tab->hist_cur->current_off = st.current_line;
555 strlcpy(tab->buffer.page.title, st.title,
556 sizeof(tab->buffer.page.title));
557 if (st.flags & TAB_CURRENT)
558 curr = tab;
559 if (st.flags & TAB_KILLED)
560 kill_tab(tab, 1);
561 break;
563 case IMSG_SESSION_TAB_HIST:
564 if (tab == NULL || datalen != sizeof(sth))
565 die();
567 memcpy(&sth, imsg->data, sizeof(sth));
568 if (sth.uri[sizeof(sth.uri)-1] != '\0')
569 die();
571 if ((h = calloc(1, sizeof(*h))) == NULL)
572 die();
573 strlcpy(h->h, sth.uri, sizeof(h->h));
575 if (sth.future)
576 hist_push(&tab->hist, h);
577 else
578 hist_add_before(&tab->hist, tab->hist_cur, h);
579 break;
581 case IMSG_SESSION_END:
582 if (datalen != sizeof(first_time))
583 die();
584 memcpy(&first_time, imsg->data, sizeof(first_time));
585 if (first_time) {
586 new_tab("about:new", NULL, NULL);
587 curr = new_tab("about:help", NULL, NULL);
590 operating = 1;
591 if (curr != NULL)
592 switch_to_tab(curr);
593 if (has_url || TAILQ_EMPTY(&tabshead))
594 new_tab(url, NULL, NULL);
595 ui_main_loop();
596 break;
598 default:
599 die();
603 static void
604 handle_imsg_history(struct imsg *imsg, size_t datalen)
606 struct histitem hi;
608 /*
609 * The fs process tried to send history item after it
610 * has announced that it's done. Something fishy is
611 * going on, better die
612 */
613 if (operating)
614 die();
616 switch (imsg->hdr.type) {
617 case IMSG_HIST_ITEM:
618 if (datalen != sizeof(hi))
619 die();
621 memcpy(&hi, imsg->data, sizeof(hi));
622 history_push(&hi);
623 break;
625 case IMSG_HIST_END:
626 history_sort();
627 break;
629 default:
630 die();
634 static void
635 handle_imsg_buf(struct imsg *imsg, size_t datalen)
637 struct tab *tab = NULL;
638 struct download *d = NULL;
640 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
641 (d = download_by_id(imsg->hdr.peerid)) == NULL)
642 return;
644 if (tab != NULL) {
645 if (!parser_parse(tab, imsg->data, datalen))
646 die();
647 ui_on_tab_refresh(tab);
648 } else {
649 d->bytes += datalen;
650 write(d->fd, imsg->data, datalen);
651 ui_on_download_refresh();
655 static void
656 handle_imsg_eof(struct imsg *imsg, size_t datalen)
658 struct tab *tab = NULL;
659 struct download *d = NULL;
661 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
662 (d = download_by_id(imsg->hdr.peerid)) == NULL)
663 return;
665 if (tab != NULL) {
666 if (!parser_free(tab))
667 die();
668 if (has_prefix(tab->hist_cur->h, "gemini://") ||
669 has_prefix(tab->hist_cur->h, "gopher://"))
670 mcache_tab(tab);
671 ui_on_tab_refresh(tab);
672 ui_on_tab_loaded(tab);
673 } else {
674 close(d->fd);
675 d->fd = -1;
676 ui_on_download_refresh();
680 static void
681 handle_imsg_tofu(struct imsg *imsg, size_t datalen)
683 struct tofu_entry *e;
685 if (operating)
686 die();
688 if ((e = calloc(1, sizeof(*e))) == NULL)
689 die();
691 if (datalen != sizeof(*e))
692 die();
693 memcpy(e, imsg->data, sizeof(*e));
694 if (e->domain[sizeof(e->domain)-1] != '\0' ||
695 e->hash[sizeof(e->hash)-1] != '\0')
696 die();
697 tofu_add(&certs, e);
700 static void
701 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
703 int res;
705 if (datalen != sizeof(res))
706 die();
708 memcpy(&res, imsg->data, sizeof(res));
709 if (res == 0)
710 message("Added to bookmarks!");
711 else
712 message("Failed to add to bookmarks: %s",
713 strerror(res));
716 static void
717 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
719 int res;
721 if (datalen != sizeof(res))
722 die();
723 memcpy(&res, imsg->data, datalen);
724 if (res != 0)
725 message("Failed to save the cert for: %s",
726 strerror(res));
729 static void
730 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
732 int res;
734 if (datalen != sizeof(res))
735 die();
736 memcpy(&res, imsg->data, datalen);
737 if (!res)
738 message("Failed to update the certificate");
741 static void
742 handle_dispatch_imsg(int fd, short ev, void *d)
744 struct imsgev *iev = d;
746 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
747 err(1, "connection closed");
750 static int
751 load_about_url(struct tab *tab, const char *url)
753 tab->trust = TS_UNKNOWN;
754 parser_init(tab, gemtext_initparser);
755 return make_fs_request(tab, IMSG_GET, url);
758 static int
759 load_file_url(struct tab *tab, const char *url)
761 tab->trust = TS_UNKNOWN;
762 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
765 static int
766 load_finger_url(struct tab *tab, const char *url)
768 struct get_req req;
769 size_t len;
770 char *at;
772 memset(&req, 0, sizeof(req));
773 strlcpy(req.port, tab->uri.port, sizeof(req.port));
775 /*
776 * Sometimes the finger url have the user as path component
777 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
778 * userinfo (e.g. finger://cobradile@finger.farm).
779 */
780 if ((at = strchr(tab->uri.host, '@')) != NULL) {
781 len = at - tab->uri.host;
782 memcpy(req.req, tab->uri.host, len);
784 if (len >= sizeof(req.req))
785 die();
786 req.req[len] = '\0';
788 strlcpy(req.host, at+1, sizeof(req.host));
789 } else {
790 strlcpy(req.host, tab->uri.host, sizeof(req.host));
792 /* +1 to skip the initial `/' */
793 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
795 strlcat(req.req, "\r\n", sizeof(req.req));
797 parser_init(tab, textplain_initparser);
798 return make_request(tab, &req, PROTO_FINGER, NULL);
801 static int
802 load_gemini_url(struct tab *tab, const char *url)
804 struct get_req req;
806 memset(&req, 0, sizeof(req));
807 strlcpy(req.host, tab->uri.host, sizeof(req.host));
808 strlcpy(req.port, tab->uri.port, sizeof(req.port));
810 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
813 static inline const char *
814 gopher_skip_selector(const char *path, int *ret_type)
816 *ret_type = 0;
818 if (!strcmp(path, "/") || *path == '\0') {
819 *ret_type = '1';
820 return path;
823 if (*path != '/')
824 return path;
825 path++;
827 switch (*ret_type = *path) {
828 case '0':
829 case '1':
830 case '7':
831 break;
833 default:
834 *ret_type = 0;
835 path -= 1;
836 return path;
839 return ++path;
842 static int
843 load_gopher_url(struct tab *tab, const char *url)
845 struct get_req req;
846 int type;
847 const char *path;
849 memset(&req, 0, sizeof(req));
850 strlcpy(req.host, tab->uri.host, sizeof(req.host));
851 strlcpy(req.port, tab->uri.port, sizeof(req.port));
853 path = gopher_skip_selector(tab->uri.path, &type);
854 switch (type) {
855 case '0':
856 parser_init(tab, textplain_initparser);
857 break;
858 case '1':
859 parser_init(tab, gophermap_initparser);
860 break;
861 case '7':
862 free(tab->last_input_url);
863 tab->last_input_url = strdup(url);
864 if (tab->last_input_url == NULL)
865 die();
866 ui_require_input(tab, 0, ir_select_gopher);
867 return load_page_from_str(tab, err_pages[10]);
868 default:
869 return load_page_from_str(tab, "Unknown gopher selector");
872 strlcpy(req.req, path, sizeof(req.req));
873 if (*tab->uri.query != '\0') {
874 strlcat(req.req, "?", sizeof(req.req));
875 strlcat(req.req, tab->uri.query, sizeof(req.req));
877 strlcat(req.req, "\r\n", sizeof(req.req));
879 return make_request(tab, &req, PROTO_GOPHER, NULL);
882 static int
883 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
885 struct get_req req;
887 memset(&req, 0, sizeof(req));
888 strlcpy(req.host, p->host, sizeof(req.host));
889 strlcpy(req.port, p->port, sizeof(req.port));
891 tab->proxy = p;
893 return make_request(tab, &req, p->proto, tab->hist_cur->h);
896 static int
897 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
899 stop_tab(tab);
900 tab->id = tab_new_id();
901 req->proto = proto;
903 if (r != NULL) {
904 strlcpy(req->req, r, sizeof(req->req));
905 strlcat(req->req, "\r\n", sizeof(req->req));
908 start_loading_anim(tab);
909 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
911 /*
912 * So the various load_*_url can `return make_request` and
913 * do_load_url is happy.
914 */
915 return 1;
918 static int
919 make_fs_request(struct tab *tab, int type, const char *r)
921 stop_tab(tab);
922 tab->id = tab_new_id();
924 ui_send_fs(type, tab->id, r, strlen(r)+1);
926 /*
927 * So load_{about,file}_url can `return make_fs_request` and
928 * do_load_url is happy.
929 */
930 return 1;
933 void
934 gopher_send_search_req(struct tab *tab, const char *text)
936 struct get_req req;
938 memset(&req, 0, sizeof(req));
939 strlcpy(req.host, tab->uri.host, sizeof(req.host));
940 strlcpy(req.port, tab->uri.port, sizeof(req.port));
942 /* +2 to skip /7 */
943 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
944 if (*tab->uri.query != '\0') {
945 strlcat(req.req, "?", sizeof(req.req));
946 strlcat(req.req, tab->uri.query, sizeof(req.req));
949 strlcat(req.req, "\t", sizeof(req.req));
950 strlcat(req.req, text, sizeof(req.req));
951 strlcat(req.req, "\r\n", sizeof(req.req));
953 erase_buffer(&tab->buffer);
954 parser_init(tab, gophermap_initparser);
956 make_request(tab, &req, PROTO_GOPHER, NULL);
959 int
960 load_page_from_str(struct tab *tab, const char *page)
962 parser_init(tab, gemtext_initparser);
963 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
964 abort();
965 if (!tab->buffer.page.free(&tab->buffer.page))
966 abort();
967 ui_on_tab_refresh(tab);
968 ui_on_tab_loaded(tab);
969 return 0;
972 /*
973 * Effectively load the given url in the given tab. Return 1 when
974 * loading the page asynchronously, and thus when an erase_buffer can
975 * be done right after this function return, or 0 when loading the
976 * page synchronously.
977 */
978 static int
979 do_load_url(struct tab *tab, const char *url, const char *base, int mode)
981 const struct proto *p;
982 struct phos_uri uri;
983 struct proxy *proxy;
984 int nocache = mode & LU_MODE_NOCACHE;
985 char *t;
987 tab->proxy = NULL;
988 tab->trust = TS_UNKNOWN;
990 if (base == NULL)
991 memcpy(&uri, &tab->uri, sizeof(tab->uri));
992 else
993 phos_parse_absolute_uri(base, &uri);
995 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
996 if (asprintf(&t, "#error loading %s\n>%s\n",
997 url, "Can't parse the URI") == -1)
998 die();
999 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
1000 load_page_from_str(tab, t);
1001 free(t);
1002 return 0;
1005 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
1006 sizeof(tab->hist_cur->h));
1008 if (!nocache && mcache_lookup(tab->hist_cur->h, tab)) {
1009 ui_on_tab_refresh(tab);
1010 ui_on_tab_loaded(tab);
1011 return 0;
1014 for (p = protos; p->schema != NULL; ++p) {
1015 if (!strcmp(tab->uri.scheme, p->schema)) {
1016 /* patch the port */
1017 if (*tab->uri.port == '\0' && p->port != NULL)
1018 strlcpy(tab->uri.port, p->port,
1019 sizeof(tab->uri.port));
1021 return p->loadfn(tab, tab->hist_cur->h);
1025 TAILQ_FOREACH(proxy, &proxies, proxies) {
1026 if (!strcmp(tab->uri.scheme, proxy->match_proto))
1027 return load_via_proxy(tab, url, proxy);
1030 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
1034 * Load url in tab and handle history. If a tab is marked as lazy, only
1035 * prepare the url but don't load it.
1037 void
1038 load_url(struct tab *tab, const char *url, const char *base, int mode)
1040 int lazy = tab->flags & TAB_LAZY;
1041 int nohist = mode & LU_MODE_NOHIST;
1043 if (operating && lazy) {
1044 tab->flags ^= TAB_LAZY;
1045 lazy = 0;
1046 } else if (tab->hist_cur != NULL)
1047 get_scroll_position(tab, &tab->hist_cur->line_off,
1048 &tab->hist_cur->current_off);
1050 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
1051 if (tab->hist_cur != NULL)
1052 hist_clear_forward(&tab->hist,
1053 TAILQ_NEXT(tab->hist_cur, entries));
1055 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
1056 == NULL) {
1057 event_loopbreak();
1058 return;
1061 strlcpy(tab->buffer.page.title, url,
1062 sizeof(tab->buffer.page.title));
1063 hist_push(&tab->hist, tab->hist_cur);
1065 if (lazy)
1066 strlcpy(tab->hist_cur->h, url,
1067 sizeof(tab->hist_cur->h));
1070 if (!lazy)
1071 do_load_url(tab, url, base, mode);
1074 void
1075 load_url_in_tab(struct tab *tab, const char *url, const char *base, int mode)
1077 if (operating) {
1078 autosave_hook();
1079 message("Loading %s...", url);
1082 load_url(tab, url, base, mode);
1085 int
1086 load_previous_page(struct tab *tab)
1088 struct hist *h;
1090 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
1091 return 0;
1092 tab->hist_cur = h;
1093 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
1094 return 1;
1097 int
1098 load_next_page(struct tab *tab)
1100 struct hist *h;
1102 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
1103 return 0;
1104 tab->hist_cur = h;
1105 do_load_url(tab, h->h, NULL, LU_MODE_NONE);
1106 return 1;
1109 void
1110 add_to_bookmarks(const char *str)
1112 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
1113 str, strlen(str)+1);
1116 void
1117 write_buffer(const char *path, struct tab *tab)
1119 if (path == NULL)
1120 return;
1122 enqueue_download(tab->id, path, 1);
1123 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
1127 * Given a user-entered URL, apply some heuristics to use it:
1129 * - if it's a proper url use it
1130 * - if it starts with a `./' or a `/' assume its a file:// url
1131 * - assume it's a gemini:// url
1133 * `ret' (of which len is the size) will be filled with the resulting
1134 * url.
1136 void
1137 humanify_url(const char *raw, char *ret, size_t len)
1139 struct phos_uri uri;
1140 char buf[PATH_MAX];
1142 if (phos_parse_absolute_uri(raw, &uri)) {
1143 strlcpy(ret, raw, len);
1144 return;
1147 if (has_prefix(raw, "./")) {
1148 strlcpy(ret, "file://", len);
1149 getcwd(buf, sizeof(buf));
1150 strlcat(ret, buf, len);
1151 strlcat(ret, "/", len);
1152 strlcat(ret, raw+2, len);
1153 return;
1156 if (*raw == '/') {
1157 strlcpy(ret, "file://", len);
1158 strlcat(ret, raw, len);
1159 return;
1162 strlcpy(ret, "gemini://", len);
1163 strlcat(ret, raw, len);
1166 static pid_t
1167 start_child(enum telescope_process p, const char *argv0, int fd)
1169 const char *argv[5];
1170 int argc = 0;
1171 pid_t pid;
1173 switch (pid = fork()) {
1174 case -1:
1175 die();
1176 case 0:
1177 break;
1178 default:
1179 close(fd);
1180 return pid;
1183 if (dup2(fd, 3) == -1)
1184 err(1, "cannot setup imsg fd");
1186 argv[argc++] = argv0;
1187 switch (p) {
1188 case PROC_UI:
1189 errx(1, "Can't start ui process");
1190 case PROC_FS:
1191 argv[argc++] = "-Tf";
1192 break;
1193 case PROC_NET:
1194 argv[argc++] = "-Tn";
1195 break;
1198 if (safe_mode)
1199 argv[argc++] = "-S";
1201 argv[argc++] = NULL;
1202 execvp(argv0, (char *const *)argv);
1203 err(1, "execvp(%s)", argv0);
1206 static void
1207 send_url(const char *url)
1209 struct sockaddr_un sun;
1210 struct imsgbuf ibuf;
1211 int ctl_sock;
1213 if ((ctl_sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
1214 err(1, "socket");
1216 memset(&sun, 0, sizeof(sun));
1217 sun.sun_family = AF_UNIX;
1218 strlcpy(sun.sun_path, ctlsock_path, sizeof(sun.sun_path));
1220 if (connect(ctl_sock, (struct sockaddr *)&sun, sizeof(sun)) == -1)
1221 err(1, "connect: %s", ctlsock_path);
1223 imsg_init(&ibuf, ctl_sock);
1224 imsg_compose(&ibuf, IMSG_CTL_OPEN_URL, 0, 0, -1, url,
1225 strlen(url) + 1);
1226 imsg_flush(&ibuf);
1227 close(ctl_sock);
1230 int
1231 ui_send_net(int type, uint32_t peerid, const void *data,
1232 uint16_t datalen)
1234 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1235 datalen);
1238 int
1239 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1241 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1242 datalen);
1245 static void __attribute__((noreturn))
1246 usage(int r)
1248 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1249 getprogname());
1250 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1251 exit(r);
1254 int
1255 main(int argc, char * const *argv)
1257 struct imsgev net_ibuf, fs_ibuf;
1258 pid_t pid;
1259 int control_fd;
1260 int pipe2net[2], pipe2fs[2];
1261 int ch, configtest = 0, fail = 0;
1262 int proc = -1;
1263 int sessionfd = -1;
1264 int status;
1265 const char *argv0;
1267 argv0 = argv[0];
1269 signal(SIGCHLD, SIG_IGN);
1270 signal(SIGPIPE, SIG_IGN);
1272 if (getenv("NO_COLOR") != NULL)
1273 enable_colors = 0;
1275 fs_init();
1277 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1278 switch (ch) {
1279 case 'C':
1280 exit(ui_print_colors());
1281 case 'c':
1282 fail = 1;
1283 strlcpy(config_path, optarg, sizeof(config_path));
1284 break;
1285 case 'n':
1286 configtest = 1;
1287 break;
1288 case 'h':
1289 usage(0);
1290 case 'S':
1291 safe_mode = 1;
1292 break;
1293 case 'T':
1294 switch (*optarg) {
1295 case 'f':
1296 proc = PROC_FS;
1297 break;
1298 case 'n':
1299 proc = PROC_NET;
1300 break;
1301 default:
1302 errx(1, "invalid process spec %c",
1303 *optarg);
1305 break;
1306 case 'v':
1307 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1308 exit(0);
1309 break;
1310 default:
1311 usage(1);
1315 argc -= optind;
1316 argv += optind;
1318 if (proc != -1) {
1319 if (argc > 0)
1320 usage(1);
1321 else if (proc == PROC_FS)
1322 return fs_main();
1323 else if (proc == PROC_NET)
1324 return net_main();
1325 else
1326 usage(1);
1329 if (argc != 0) {
1330 has_url = 1;
1331 humanify_url(argv[0], url, sizeof(url));
1334 /* setup keys before reading the config */
1335 TAILQ_INIT(&global_map.m);
1336 global_map.unhandled_input = global_key_unbound;
1337 TAILQ_INIT(&minibuffer_map.m);
1339 config_init();
1340 parseconfig(config_path, fail);
1341 if (configtest) {
1342 puts("config OK");
1343 exit(0);
1346 if (download_path == NULL &&
1347 (download_path = strdup("/tmp/")) == NULL)
1348 errx(1, "strdup");
1350 if (!safe_mode && (sessionfd = lock_session()) == -1) {
1351 if (has_url) {
1352 send_url(url);
1353 exit(0);
1356 errx(1, "can't lock session, is another instance of "
1357 "telescope already running?");
1360 /* Start children. */
1361 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1362 err(1, "socketpair");
1363 start_child(PROC_FS, argv0, pipe2fs[1]);
1364 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1365 iev_fs = &fs_ibuf;
1366 iev_fs->handler = handle_dispatch_imsg;
1368 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1369 err(1, "socketpair");
1370 start_child(PROC_NET, argv0, pipe2net[1]);
1371 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1372 iev_net = &net_ibuf;
1373 iev_net->handler = handle_dispatch_imsg;
1375 setproctitle("ui");
1377 /* initialize tofu store */
1378 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1380 event_init();
1382 if (!safe_mode) {
1383 if ((control_fd = control_init(ctlsock_path)) == -1)
1384 err(1, "control_init %s", ctlsock_path);
1385 control_listen(control_fd);
1388 /* initialize the in-memory cache store */
1389 mcache_init();
1391 /* Setup event handler for the autosave */
1392 autosave_init();
1394 /* Setup event handlers for pipes to fs/net */
1395 iev_fs->events = EV_READ;
1396 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1397 iev_fs->handler, iev_fs);
1398 event_add(&iev_fs->ev, NULL);
1400 iev_net->events = EV_READ;
1401 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1402 iev_net->handler, iev_net);
1403 event_add(&iev_net->ev, NULL);
1405 if (ui_init()) {
1406 sandbox_ui_process();
1407 ui_send_fs(IMSG_INIT, 0, NULL, 0);
1408 event_dispatch();
1409 ui_end();
1412 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1413 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1414 imsg_flush(&iev_fs->ibuf);
1415 imsg_flush(&iev_net->ibuf);
1417 /* wait for children to terminate */
1418 do {
1419 pid = wait(&status);
1420 if (pid == -1) {
1421 if (errno != EINTR && errno != ECHILD)
1422 err(1, "wait");
1423 } else if (WIFSIGNALED(status))
1424 warnx("child terminated; signal %d", WTERMSIG(status));
1425 } while (pid != -1 || (pid == -1 && errno == EINTR));
1427 if (!safe_mode && close(sessionfd) == -1)
1428 err(1, "close(sessionfd = %d)", sessionfd);
1430 return 0;