Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "compat.h"
19 #include <sys/socket.h>
20 #include <sys/wait.h>
22 #include <errno.h>
23 #include <getopt.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
30 #include "defaults.h"
31 #include "fs.h"
32 #include "minibuffer.h"
33 #include "parser.h"
34 #include "session.h"
35 #include "telescope.h"
36 #include "ui.h"
38 static struct option longopts[] = {
39 {"colors", no_argument, NULL, 'C'},
40 {"colours", no_argument, NULL, 'C'},
41 {"help", no_argument, NULL, 'h'},
42 {"safe", no_argument, NULL, 'S'},
43 {"version", no_argument, NULL, 'v'},
44 {NULL, 0, NULL, 0},
45 };
47 static const char *opts = "Cc:hnST:v";
49 static int has_url;
50 static char url[GEMINI_URL_LEN];
52 /*
53 * Used to know when we're finished loading.
54 */
55 int operating;
57 /*
58 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
59 * anything to the filesystem or execute external programs.
60 */
61 int safe_mode;
63 static struct imsgev *iev_fs, *iev_net;
65 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
66 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
68 enum telescope_process {
69 PROC_UI,
70 PROC_FS,
71 PROC_NET,
72 };
74 #define CANNOT_FETCH 0
75 #define TOO_MUCH_REDIRECTS 1
76 #define MALFORMED_RESPONSE 2
77 #define UNKNOWN_TYPE_OR_CSET 3
78 #define UNKNOWN_PROTOCOL 4
80 /* XXX: keep in sync with normalize_code */
81 const char *err_pages[70] = {
82 [CANNOT_FETCH] = "# Couldn't load the page\n",
83 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
84 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
85 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
86 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
88 [10] = "# Input required\n",
89 [11] = "# Input required\n",
90 [40] = "# Temporary failure\n",
91 [41] = "# Server unavailable\n",
92 [42] = "# CGI error\n",
93 [43] = "# Proxy error\n",
94 [44] = "# Slow down\n",
95 [50] = "# Permanent failure\n",
96 [51] = "# Not found\n",
97 [52] = "# Gone\n",
98 [53] = "# Proxy request refused\n",
99 [59] = "# Bad request\n",
100 [60] = "# Client certificate required\n",
101 [61] = "# Certificate not authorised\n",
102 [62] = "# Certificate not valid\n"
103 };
105 static void die(void) __attribute__((__noreturn__));
106 static struct tab *tab_by_id(uint32_t);
107 static void handle_imsg_err(struct imsg *, size_t);
108 static void handle_imsg_check_cert(struct imsg *, size_t);
109 static void handle_check_cert_user_choice(int, struct tab *);
110 static void handle_maybe_save_new_cert(int, struct tab *);
111 static void handle_imsg_got_code(struct imsg *, size_t);
112 static void handle_imsg_got_meta(struct imsg *, size_t);
113 static void handle_maybe_save_page(int, struct tab *);
114 static void handle_save_page_path(const char *, struct tab *);
115 static void handle_imsg_file_opened(struct imsg *, size_t);
116 static void handle_imsg_buf(struct imsg *, size_t);
117 static void handle_imsg_eof(struct imsg *, size_t);
118 static void handle_imsg_bookmark_ok(struct imsg *, size_t);
119 static void handle_imsg_save_cert_ok(struct imsg *, size_t);
120 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
121 static void handle_imsg_session(struct imsg *, size_t);
122 static void handle_dispatch_imsg(int, short, void *);
123 static int load_about_url(struct tab *, const char *);
124 static int load_file_url(struct tab *, const char *);
125 static int load_finger_url(struct tab *, const char *);
126 static int load_gemini_url(struct tab *, const char *);
127 static int load_gopher_url(struct tab *, const char *);
128 static int load_via_proxy(struct tab *, const char *,
129 struct proxy *);
130 static int make_request(struct tab *, struct get_req *, int,
131 const char *);
132 static int make_fs_request(struct tab *, int, const char *);
133 static int do_load_url(struct tab *, const char *, const char *);
134 static pid_t start_child(enum telescope_process, const char *, int);
136 static struct proto {
137 const char *schema;
138 const char *port;
139 int (*loadfn)(struct tab *, const char *);
140 } protos[] = {
141 {"about", NULL, load_about_url},
142 {"file", NULL, load_file_url},
143 {"finger", "79", load_finger_url},
144 {"gemini", "1965", load_gemini_url},
145 {"gopher", "70", load_gopher_url},
146 {NULL, NULL, NULL},
147 };
149 static imsg_handlerfn *handlers[] = {
150 [IMSG_ERR] = handle_imsg_err,
151 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
152 [IMSG_GOT_CODE] = handle_imsg_got_code,
153 [IMSG_GOT_META] = handle_imsg_got_meta,
154 [IMSG_BUF] = handle_imsg_buf,
155 [IMSG_EOF] = handle_imsg_eof,
156 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
157 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
158 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
159 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
160 [IMSG_SESSION_TAB] = handle_imsg_session,
161 [IMSG_SESSION_END] = handle_imsg_session,
162 };
164 static struct ohash certs;
166 static void __attribute__((__noreturn__))
167 die(void)
169 abort(); /* TODO */
172 static struct tab *
173 tab_by_id(uint32_t id)
175 struct tab *t;
177 TAILQ_FOREACH(t, &tabshead, tabs) {
178 if (t->id == id)
179 return t;
182 return NULL;
185 static void
186 handle_imsg_err(struct imsg *imsg, size_t datalen)
188 struct tab *tab;
189 char *page;
191 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
192 return;
194 page = imsg->data;
195 page[datalen-1] = '\0';
197 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
198 tab->hist_cur->h, page) == -1)
199 die();
200 load_page_from_str(tab, page);
201 free(page);
204 static void
205 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
207 const char *hash, *host, *port;
208 int tofu_res;
209 struct tofu_entry *e;
210 struct tab *tab;
212 hash = imsg->data;
213 if (hash[datalen-1] != '\0')
214 abort();
216 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
217 return;
219 if (tab->proxy != NULL) {
220 host = tab->proxy->host;
221 port = tab->proxy->port;
222 } else {
223 host = tab->uri.host;
224 port = tab->uri.port;
227 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
228 /* TODO: an update in libressl/libretls changed
229 * significantly. Find a better approach at storing
230 * the certs! */
231 if (datalen > sizeof(e->hash))
232 abort();
234 tofu_res = 1; /* trust on first use */
235 if ((e = calloc(1, sizeof(*e))) == NULL)
236 abort();
237 strlcpy(e->domain, host, sizeof(e->domain));
238 if (*port != '\0' && strcmp(port, "1965")) {
239 strlcat(e->domain, ":", sizeof(e->domain));
240 strlcat(e->domain, port, sizeof(e->domain));
242 strlcpy(e->hash, hash, sizeof(e->hash));
243 tofu_add(&certs, e);
244 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
245 } else
246 tofu_res = !strcmp(hash, e->hash);
248 if (tofu_res) {
249 if (e->verified == -1)
250 tab->trust = TS_TEMP_TRUSTED;
251 else if (e->verified == 1)
252 tab->trust = TS_VERIFIED;
253 else
254 tab->trust = TS_TRUSTED;
256 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
257 &tofu_res, sizeof(tofu_res));
258 } else {
259 tab->trust = TS_UNTRUSTED;
260 load_page_from_str(tab, "# Certificate mismatch\n");
261 if ((tab->cert = strdup(hash)) == NULL)
262 die();
263 ui_yornp("Certificate mismatch. Proceed?",
264 handle_check_cert_user_choice, tab);
268 static void
269 handle_check_cert_user_choice(int accept, struct tab *tab)
271 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
272 sizeof(accept));
274 if (accept) {
275 /*
276 * trust the certificate for this session only. If
277 * the page results in a redirect while we're asking
278 * the user to save, we'll end up with an invalid
279 * tabid (one request == one tab id). It also makes
280 * sense to save it for the current session if the
281 * user accepted it.
282 */
283 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
284 tab->cert);
286 if (!safe_mode)
287 ui_yornp("Save the new certificate?",
288 handle_maybe_save_new_cert, tab);
289 else
290 message("Certificate temporarly trusted");
291 } else {
292 free(tab->cert);
293 tab->cert = NULL;
297 static void
298 handle_maybe_save_new_cert(int accept, struct tab *tab)
300 struct tofu_entry *e;
301 const char *host, *port;
303 if (tab->proxy != NULL) {
304 host = tab->proxy->host;
305 port = tab->proxy->port;
306 } else {
307 host = tab->uri.host;
308 port = tab->uri.port;
311 if (!accept)
312 goto end;
314 if ((e = calloc(1, sizeof(*e))) == NULL)
315 die();
317 strlcpy(e->domain, host, sizeof(e->domain));
318 if (*port != '\0' && strcmp(port, "1965")) {
319 strlcat(e->domain, ":", sizeof(e->domain));
320 strlcat(e->domain, port, sizeof(e->domain));
322 strlcpy(e->hash, tab->cert, sizeof(e->hash));
323 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
325 tofu_update(&certs, e);
327 tab->trust = TS_TRUSTED;
329 end:
330 free(tab->cert);
331 tab->cert = NULL;
334 static inline int
335 normalize_code(int n)
337 if (n < 20) {
338 if (n == 10 || n == 11)
339 return n;
340 return 10;
341 } else if (n < 30) {
342 return 20;
343 } else if (n < 40) {
344 if (n == 30 || n == 31)
345 return n;
346 return 30;
347 } else if (n < 50) {
348 if (n <= 44)
349 return n;
350 return 40;
351 } else if (n < 60) {
352 if (n <= 53 || n == 59)
353 return n;
354 return 50;
355 } else if (n < 70) {
356 if (n <= 62)
357 return n;
358 return 60;
359 } else
360 return MALFORMED_RESPONSE;
363 static void
364 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
366 struct tab *tab;
368 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
369 return;
371 if (sizeof(tab->code) != datalen)
372 die();
374 memcpy(&tab->code, imsg->data, sizeof(tab->code));
375 tab->code = normalize_code(tab->code);
376 if (tab->code != 30 && tab->code != 31)
377 tab->redirect_count = 0;
380 static void
381 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
383 struct tab *tab;
384 char buf[128];
386 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
387 return;
389 if (sizeof(tab->meta) <= datalen)
390 die();
392 memcpy(tab->meta, imsg->data, datalen);
394 if (tab->code < 10) { /* internal errors */
395 load_page_from_str(tab, err_pages[tab->code]);
396 } else if (tab->code < 20) { /* 1x */
397 load_page_from_str(tab, err_pages[tab->code]);
398 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
399 } else if (tab->code == 20) {
400 if (setup_parser_for(tab)) {
401 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
402 } else if (safe_mode) {
403 load_page_from_str(tab,
404 err_pages[UNKNOWN_TYPE_OR_CSET]);
405 } else {
406 struct hist *h;
408 if ((h = hist_pop(&tab->hist)) != NULL)
409 tab->hist_cur = h;
410 snprintf(buf, sizeof(buf),
411 "Can't display \"%s\", save it?", tab->meta);
412 ui_yornp(buf, handle_maybe_save_page, tab);
414 } else if (tab->code < 40) { /* 3x */
415 tab->redirect_count++;
417 /* TODO: make customizable? */
418 if (tab->redirect_count > 5) {
419 load_page_from_str(tab,
420 err_pages[TOO_MUCH_REDIRECTS]);
421 } else
422 do_load_url(tab, tab->meta, NULL);
423 } else { /* 4x, 5x & 6x */
424 load_page_from_str(tab, err_pages[tab->code]);
428 static void
429 handle_maybe_save_page(int dosave, struct tab *tab)
431 const char *f;
432 char input[PATH_MAX];
434 /* XXX: this print a message that is confusing */
435 ui_on_tab_loaded(tab);
437 if (!dosave) {
438 stop_tab(tab);
439 return;
442 if ((f = strrchr(tab->uri.path, '/')) == NULL)
443 f = "";
444 else
445 f++;
447 strlcpy(input, download_path, sizeof(input));
448 strlcat(input, f, sizeof(input));
450 ui_read("Save to path", handle_save_page_path, tab, input);
453 static void
454 handle_save_page_path(const char *path, struct tab *tab)
456 if (path == NULL) {
457 stop_tab(tab);
458 return;
461 ui_show_downloads_pane();
463 enqueue_download(tab->id, path);
464 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
466 /*
467 * Change this tab id, the old one is associated with the
468 * download now.
469 */
470 tab->id = tab_new_id();
473 static void
474 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
476 struct download *d;
477 const char *e;
479 /*
480 * There are no reason we shouldn't be able to find the
481 * required download.
482 */
483 if ((d = download_by_id(imsg->hdr.peerid)) == NULL)
484 die();
486 if (imsg->fd == -1) {
487 e = imsg->data;
488 if (e[datalen-1] != '\0')
489 die();
490 message("Can't open file %s: %s", d->path, e);
491 } else {
492 d->fd = imsg->fd;
493 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
497 static void
498 handle_imsg_session(struct imsg *imsg, size_t datalen)
500 static struct tab *curr;
501 struct session_tab st;
502 struct tab *tab;
503 int first_time;
505 /*
506 * The fs process tried to send tabs after it has announced
507 * that he's done. Something fishy is going on, better die.
508 */
509 if (operating)
510 die();
512 if (imsg->hdr.type == IMSG_SESSION_END) {
513 if (datalen != sizeof(first_time))
514 die();
515 memcpy(&first_time, imsg->data, sizeof(first_time));
516 if (first_time) {
517 new_tab("about:new", NULL, NULL);
518 curr = new_tab("about:help", NULL, NULL);
521 operating = 1;
522 if (curr != NULL)
523 switch_to_tab(curr);
524 if (has_url || TAILQ_EMPTY(&tabshead))
525 new_tab(url, NULL, NULL);
526 ui_main_loop();
527 return;
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 strlcpy(tab->buffer.page.title, st.title,
537 sizeof(tab->buffer.page.title));
538 if (st.flags & TAB_CURRENT)
539 curr = tab;
542 static void
543 handle_imsg_buf(struct imsg *imsg, size_t datalen)
545 struct tab *tab = NULL;
546 struct download *d = NULL;
548 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
549 (d = download_by_id(imsg->hdr.peerid)) == NULL)
550 return;
552 if (tab != NULL) {
553 if (!parser_parse(tab, imsg->data, datalen))
554 die();
555 ui_on_tab_refresh(tab);
556 } else {
557 d->bytes += datalen;
558 write(d->fd, imsg->data, datalen);
559 ui_on_download_refresh();
563 static void
564 handle_imsg_eof(struct imsg *imsg, size_t datalen)
566 struct tab *tab = NULL;
567 struct download *d = NULL;
569 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
570 (d = download_by_id(imsg->hdr.peerid)) == NULL)
571 return;
573 if (tab != NULL) {
574 if (!parser_free(tab))
575 die();
576 ui_on_tab_refresh(tab);
577 ui_on_tab_loaded(tab);
578 } else {
579 close(d->fd);
580 d->fd = -1;
581 ui_on_download_refresh();
585 static void
586 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
588 int res;
590 if (datalen != sizeof(res))
591 die();
593 memcpy(&res, imsg->data, sizeof(res));
594 if (res == 0)
595 message("Added to bookmarks!");
596 else
597 message("Failed to add to bookmarks: %s",
598 strerror(res));
601 static void
602 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
604 int res;
606 if (datalen != sizeof(res))
607 die();
608 memcpy(&res, imsg->data, datalen);
609 if (res != 0)
610 message("Failed to save the cert for: %s",
611 strerror(res));
614 static void
615 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
617 int res;
619 if (datalen != sizeof(res))
620 die();
621 memcpy(&res, imsg->data, datalen);
622 if (!res)
623 message("Failed to update the certificate");
626 static void
627 handle_dispatch_imsg(int fd, short ev, void *d)
629 struct imsgev *iev = d;
631 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
632 err(1, "connection closed");
635 static int
636 load_about_url(struct tab *tab, const char *url)
638 tab->trust = TS_UNKNOWN;
639 parser_init(tab, gemtext_initparser);
640 return make_fs_request(tab, IMSG_GET, url);
643 static int
644 load_file_url(struct tab *tab, const char *url)
646 tab->trust = TS_UNKNOWN;
647 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
650 static int
651 load_finger_url(struct tab *tab, const char *url)
653 struct get_req req;
654 size_t len;
655 char *at;
657 memset(&req, 0, sizeof(req));
658 strlcpy(req.port, tab->uri.port, sizeof(req.port));
660 /*
661 * Sometimes the finger url have the user as path component
662 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
663 * userinfo (e.g. finger://cobradile@finger.farm).
664 */
665 if ((at = strchr(tab->uri.host, '@')) != NULL) {
666 len = at - tab->uri.host;
667 memcpy(req.req, tab->uri.host, len);
669 if (len >= sizeof(req.req))
670 die();
671 req.req[len] = '\0';
673 strlcpy(req.host, at+1, sizeof(req.host));
674 } else {
675 strlcpy(req.host, tab->uri.host, sizeof(req.host));
677 /* +1 to skip the initial `/' */
678 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
680 strlcat(req.req, "\r\n", sizeof(req.req));
682 parser_init(tab, textplain_initparser);
683 return make_request(tab, &req, PROTO_FINGER, NULL);
686 static int
687 load_gemini_url(struct tab *tab, const char *url)
689 struct get_req req;
691 memset(&req, 0, sizeof(req));
692 strlcpy(req.host, tab->uri.host, sizeof(req.host));
693 strlcpy(req.port, tab->uri.port, sizeof(req.port));
695 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
698 static inline const char *
699 gopher_skip_selector(const char *path, int *ret_type)
701 *ret_type = 0;
703 if (!strcmp(path, "/") || *path == '\0') {
704 *ret_type = '1';
705 return path;
708 if (*path != '/')
709 return path;
710 path++;
712 switch (*ret_type = *path) {
713 case '0':
714 case '1':
715 case '7':
716 break;
718 default:
719 *ret_type = 0;
720 path -= 1;
721 return path;
724 return ++path;
727 static int
728 load_gopher_url(struct tab *tab, const char *url)
730 struct get_req req;
731 int type;
732 const char *path;
734 memset(&req, 0, sizeof(req));
735 strlcpy(req.host, tab->uri.host, sizeof(req.host));
736 strlcpy(req.port, tab->uri.port, sizeof(req.port));
738 path = gopher_skip_selector(tab->uri.path, &type);
739 switch (type) {
740 case '0':
741 parser_init(tab, textplain_initparser);
742 break;
743 case '1':
744 parser_init(tab, gophermap_initparser);
745 break;
746 case '7':
747 ui_require_input(tab, 0, PROTO_GOPHER);
748 return load_page_from_str(tab, err_pages[10]);
749 default:
750 return load_page_from_str(tab, "Unknown gopher selector");
753 strlcpy(req.req, path, sizeof(req.req));
754 if (*tab->uri.query != '\0') {
755 strlcat(req.req, "?", sizeof(req.req));
756 strlcat(req.req, tab->uri.query, sizeof(req.req));
758 strlcat(req.req, "\r\n", sizeof(req.req));
760 return make_request(tab, &req, PROTO_GOPHER, NULL);
763 static int
764 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
766 struct get_req req;
768 memset(&req, 0, sizeof(req));
769 strlcpy(req.host, p->host, sizeof(req.host));
770 strlcpy(req.port, p->port, sizeof(req.port));
772 tab->proxy = p;
774 return make_request(tab, &req, p->proto, tab->hist_cur->h);
777 static int
778 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
780 stop_tab(tab);
781 tab->id = tab_new_id();
782 req->proto = proto;
784 if (r != NULL) {
785 strlcpy(req->req, r, sizeof(req->req));
786 strlcat(req->req, "\r\n", sizeof(req->req));
789 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
791 /*
792 * So the various load_*_url can `return make_request` and
793 * do_load_url is happy.
794 */
795 return 1;
798 static int
799 make_fs_request(struct tab *tab, int type, const char *r)
801 stop_tab(tab);
802 tab->id = tab_new_id();
804 ui_send_fs(type, tab->id, r, strlen(r)+1);
806 /*
807 * So load_{about,file}_url can `return make_fs_request` and
808 * do_load_url is happy.
809 */
810 return 1;
813 void
814 gopher_send_search_req(struct tab *tab, const char *text)
816 struct get_req req;
818 start_loading_anim(tab);
820 memset(&req, 0, sizeof(req));
821 strlcpy(req.host, tab->uri.host, sizeof(req.host));
822 strlcpy(req.port, tab->uri.port, sizeof(req.port));
824 /* +2 to skip /7 */
825 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
826 if (*tab->uri.query != '\0') {
827 strlcat(req.req, "?", sizeof(req.req));
828 strlcat(req.req, tab->uri.query, sizeof(req.req));
831 strlcat(req.req, "\t", sizeof(req.req));
832 strlcat(req.req, text, sizeof(req.req));
833 strlcat(req.req, "\r\n", sizeof(req.req));
835 erase_buffer(&tab->buffer);
836 parser_init(tab, gophermap_initparser);
838 make_request(tab, &req, PROTO_GOPHER, NULL);
841 /*
842 * Effectively load the given url in the given tab. Return 1 when
843 * loading the page asynchronously, and thus when an erase_buffer can
844 * be done right after this function return, or 0 when loading the
845 * page synchronously.
846 */
847 static int
848 do_load_url(struct tab *tab, const char *url, const char *base)
850 struct phos_uri uri;
851 struct proto *p;
852 struct proxy *proxy;
853 char *t;
855 tab->proxy = NULL;
857 tab->trust = TS_UNKNOWN;
859 if (base == NULL)
860 memcpy(&uri, &tab->uri, sizeof(tab->uri));
861 else
862 phos_parse_absolute_uri(base, &uri);
864 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
865 if (asprintf(&t, "#error loading %s\n>%s\n",
866 url, "Can't parse the URI") == -1)
867 die();
868 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
869 load_page_from_str(tab, t);
870 free(t);
871 return 0;
874 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
875 sizeof(tab->hist_cur->h));
877 for (p = protos; p->schema != NULL; ++p) {
878 if (!strcmp(tab->uri.scheme, p->schema)) {
879 /* patch the port */
880 if (*tab->uri.port == '\0' && p->port != NULL)
881 strlcpy(tab->uri.port, p->port,
882 sizeof(tab->uri.port));
884 return p->loadfn(tab, url);
888 TAILQ_FOREACH(proxy, &proxies, proxies) {
889 if (!strcmp(tab->uri.scheme, proxy->match_proto))
890 return load_via_proxy(tab, url, proxy);
893 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
896 /*
897 * Load url in tab. If tab is marked as lazy, only prepare the url
898 * but don't load it. If tab is lazy and a url was already prepared,
899 * do load it!
900 */
901 void
902 load_url(struct tab *tab, const char *url, const char *base, int nohist)
904 int lazy;
906 lazy = tab->flags & TAB_LAZY;
908 if (lazy && tab->hist_cur != NULL) {
909 lazy = 0;
910 tab->flags &= ~TAB_LAZY;
913 /* can't have both nohist and lazy at the same time. */
914 if (nohist && lazy)
915 nohist = 0;
917 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
918 if (tab->hist_cur != NULL)
919 hist_clear_forward(&tab->hist,
920 TAILQ_NEXT(tab->hist_cur, entries));
922 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
923 == NULL) {
924 event_loopbreak();
925 return;
928 strlcpy(tab->buffer.page.title, url,
929 sizeof(tab->buffer.page.title));
930 hist_push(&tab->hist, tab->hist_cur);
932 if (lazy)
933 strlcpy(tab->hist_cur->h, url,
934 sizeof(tab->hist_cur->h));
937 if (!lazy)
938 do_load_url(tab, url, base);
941 void
942 load_url_in_tab(struct tab *tab, const char *url, const char *base, int nohist)
944 if (!operating) {
945 load_url(tab, url, base, nohist);
946 return;
949 autosave_hook();
951 message("Loading %s...", url);
952 start_loading_anim(tab);
953 load_url(tab, url, base, nohist);
956 int
957 load_previous_page(struct tab *tab)
959 struct hist *h;
961 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
962 return 0;
963 tab->hist_cur = h;
964 do_load_url(tab, h->h, NULL);
965 return 1;
968 int
969 load_next_page(struct tab *tab)
971 struct hist *h;
973 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
974 return 0;
975 tab->hist_cur = h;
976 do_load_url(tab, h->h, NULL);
977 return 1;
980 void
981 add_to_bookmarks(const char *str)
983 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
984 str, strlen(str)+1);
987 /*
988 * Given a user-entered URL, apply some heuristics to use it:
990 * - if it's a proper url use it
991 * - if it starts with a `./' or a `/' assume its a file:// url
992 * - assume it's a gemini:// url
994 * `ret' (of which len is the size) will be filled with the resulting
995 * url.
996 */
997 void
998 humanify_url(const char *raw, char *ret, size_t len)
1000 struct phos_uri uri;
1001 char buf[PATH_MAX];
1003 if (phos_parse_absolute_uri(raw, &uri)) {
1004 strlcpy(ret, raw, len);
1005 return;
1008 if (has_prefix(raw, "./")) {
1009 strlcpy(ret, "file://", len);
1010 getcwd(buf, sizeof(buf));
1011 strlcat(ret, buf, len);
1012 strlcat(ret, "/", len);
1013 strlcat(ret, raw+2, len);
1014 return;
1017 if (*raw == '/') {
1018 strlcpy(ret, "file://", len);
1019 strlcat(ret, raw, len);
1020 return;
1023 strlcpy(ret, "gemini://", len);
1024 strlcat(ret, raw, len);
1027 static pid_t
1028 start_child(enum telescope_process p, const char *argv0, int fd)
1030 const char *argv[5];
1031 int argc = 0;
1032 pid_t pid;
1034 switch (pid = fork()) {
1035 case -1:
1036 die();
1037 case 0:
1038 break;
1039 default:
1040 close(fd);
1041 return pid;
1044 if (dup2(fd, 3) == -1)
1045 err(1, "cannot setup imsg fd");
1047 argv[argc++] = argv0;
1048 switch (p) {
1049 case PROC_UI:
1050 errx(1, "Can't start ui process");
1051 case PROC_FS:
1052 argv[argc++] = "-Tf";
1053 break;
1054 case PROC_NET:
1055 argv[argc++] = "-Tn";
1056 break;
1059 if (safe_mode)
1060 argv[argc++] = "-S";
1062 argv[argc++] = NULL;
1063 execvp(argv0, (char *const *)argv);
1064 err(1, "execvp(%s)", argv0);
1067 int
1068 ui_send_net(int type, uint32_t peerid, const void *data,
1069 uint16_t datalen)
1071 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1072 datalen);
1075 int
1076 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1078 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1079 datalen);
1082 static void __attribute__((noreturn))
1083 usage(int r)
1085 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1086 getprogname());
1087 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1088 exit(r);
1091 int
1092 main(int argc, char * const *argv)
1094 struct imsgev net_ibuf, fs_ibuf;
1095 pid_t pid;
1096 int pipe2net[2], pipe2fs[2];
1097 int ch, configtest = 0, fail = 0;
1098 int proc = -1;
1099 int sessionfd = -1;
1100 int status;
1101 const char *argv0;
1103 argv0 = argv[0];
1105 signal(SIGCHLD, SIG_IGN);
1106 signal(SIGPIPE, SIG_IGN);
1108 if (getenv("NO_COLOR") != NULL)
1109 enable_colors = 0;
1111 fs_init();
1113 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1114 switch (ch) {
1115 case 'C':
1116 exit(ui_print_colors());
1117 case 'c':
1118 fail = 1;
1119 strlcpy(config_path, optarg, sizeof(config_path));
1120 break;
1121 case 'n':
1122 configtest = 1;
1123 break;
1124 case 'h':
1125 usage(0);
1126 case 'S':
1127 safe_mode = 1;
1128 break;
1129 case 'T':
1130 switch (*optarg) {
1131 case 'f':
1132 proc = PROC_FS;
1133 break;
1134 case 'n':
1135 proc = PROC_NET;
1136 break;
1137 default:
1138 errx(1, "invalid process spec %c",
1139 *optarg);
1141 break;
1142 case 'v':
1143 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1144 exit(0);
1145 break;
1146 default:
1147 usage(1);
1151 argc -= optind;
1152 argv += optind;
1154 if (proc != -1) {
1155 if (argc > 0)
1156 usage(1);
1157 else if (proc == PROC_FS)
1158 return fs_main();
1159 else if (proc == PROC_NET)
1160 return net_main();
1161 else
1162 usage(1);
1165 if (argc != 0) {
1166 has_url = 1;
1167 humanify_url(argv[0], url, sizeof(url));
1170 /* setup keys before reading the config */
1171 TAILQ_INIT(&global_map.m);
1172 global_map.unhandled_input = global_key_unbound;
1173 TAILQ_INIT(&minibuffer_map.m);
1175 config_init();
1176 parseconfig(config_path, fail);
1177 if (configtest) {
1178 puts("config OK");
1179 exit(0);
1182 if (download_path == NULL &&
1183 (download_path = strdup("/tmp/")) == NULL)
1184 errx(1, "strdup");
1186 if (!safe_mode && (sessionfd = lock_session()) == -1)
1187 errx(1, "can't lock session, is another instance of "
1188 "telescope already running?");
1190 /* Start children. */
1191 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1192 err(1, "socketpair");
1193 start_child(PROC_FS, argv0, pipe2fs[1]);
1194 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1195 iev_fs = &fs_ibuf;
1196 iev_fs->handler = handle_dispatch_imsg;
1198 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1199 err(1, "socketpair");
1200 start_child(PROC_NET, argv0, pipe2net[1]);
1201 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1202 iev_net = &net_ibuf;
1203 iev_net->handler = handle_dispatch_imsg;
1205 setproctitle("ui");
1207 /* initialize tofu & load certificates */
1208 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1209 load_certs(&certs);
1211 event_init();
1213 /* Setup event handler for the autosave */
1214 autosave_init();
1216 /* Setup event handlers for pipes to fs/net */
1217 iev_fs->events = EV_READ;
1218 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1219 iev_fs->handler, iev_fs);
1220 event_add(&iev_fs->ev, NULL);
1222 iev_net->events = EV_READ;
1223 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1224 iev_net->handler, iev_net);
1225 event_add(&iev_net->ev, NULL);
1227 if (ui_init()) {
1228 sandbox_ui_process();
1229 event_dispatch();
1230 ui_end();
1233 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1234 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1235 imsg_flush(&iev_fs->ibuf);
1236 imsg_flush(&iev_net->ibuf);
1238 /* wait for children to terminate */
1239 do {
1240 pid = wait(&status);
1241 if (pid == -1) {
1242 if (errno != EINTR && errno != ECHILD)
1243 err(1, "wait");
1244 } else if (WIFSIGNALED(status))
1245 warnx("child terminated; signal %d", WTERMSIG(status));
1246 } while (pid != -1 || (pid == -1 && errno == EINTR));
1248 if (!safe_mode && close(sessionfd) == -1)
1249 err(1, "close(sessionfd = %d)", sessionfd);
1251 return 0;