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 {"help", no_argument, NULL, 'h'},
41 {"safe", no_argument, NULL, 'S'},
42 {"version", no_argument, NULL, 'v'},
43 {NULL, 0, NULL, 0},
44 };
46 static const char *opts = "Cc:hnST:v";
48 static int has_url;
49 static char url[GEMINI_URL_LEN];
51 /*
52 * Used to know when we're finished loading.
53 */
54 int operating;
56 /*
57 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
58 * anything to the filesystem or execute external programs.
59 */
60 int safe_mode;
62 static struct imsgev *iev_fs, *iev_net;
64 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
65 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
67 enum telescope_process {
68 PROC_UI,
69 PROC_FS,
70 PROC_NET,
71 };
73 #define CANNOT_FETCH 0
74 #define TOO_MUCH_REDIRECTS 1
75 #define MALFORMED_RESPONSE 2
76 #define UNKNOWN_TYPE_OR_CSET 3
77 #define UNKNOWN_PROTOCOL 4
79 /* XXX: keep in sync with normalize_code */
80 const char *err_pages[70] = {
81 [CANNOT_FETCH] = "# Couldn't load the page\n",
82 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
83 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
84 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
85 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
87 [10] = "# Input required\n",
88 [11] = "# Input required\n",
89 [40] = "# Temporary failure\n",
90 [41] = "# Server unavailable\n",
91 [42] = "# CGI error\n",
92 [43] = "# Proxy error\n",
93 [44] = "# Slow down\n",
94 [50] = "# Permanent failure\n",
95 [51] = "# Not found\n",
96 [52] = "# Gone\n",
97 [53] = "# Proxy request refused\n",
98 [59] = "# Bad request\n",
99 [60] = "# Client certificate required\n",
100 [61] = "# Certificate not authorised\n",
101 [62] = "# Certificate not valid\n"
102 };
104 static void die(void) __attribute__((__noreturn__));
105 static struct tab *tab_by_id(uint32_t);
106 static void handle_imsg_err(struct imsg *, size_t);
107 static void handle_imsg_check_cert(struct imsg *, size_t);
108 static void handle_check_cert_user_choice(int, struct tab *);
109 static void handle_maybe_save_new_cert(int, struct tab *);
110 static void handle_imsg_got_code(struct imsg *, size_t);
111 static void handle_imsg_got_meta(struct imsg *, size_t);
112 static void handle_maybe_save_page(int, struct tab *);
113 static void handle_save_page_path(const char *, struct tab *);
114 static void handle_imsg_file_opened(struct imsg *, size_t);
115 static void handle_imsg_buf(struct imsg *, size_t);
116 static void handle_imsg_eof(struct imsg *, size_t);
117 static void handle_imsg_bookmark_ok(struct imsg *, size_t);
118 static void handle_imsg_save_cert_ok(struct imsg *, size_t);
119 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
120 static void handle_imsg_session(struct imsg *, size_t);
121 static void handle_dispatch_imsg(int, short, void *);
122 static int load_about_url(struct tab *, const char *);
123 static int load_file_url(struct tab *, const char *);
124 static int load_finger_url(struct tab *, const char *);
125 static int load_gemini_url(struct tab *, const char *);
126 static int load_gopher_url(struct tab *, const char *);
127 static int load_via_proxy(struct tab *, const char *,
128 struct proxy *);
129 static int make_request(struct tab *, struct get_req *, int,
130 const char *);
131 static int make_fs_request(struct tab *, int, const char *);
132 static int do_load_url(struct tab *, const char *, const char *);
133 static pid_t start_child(enum telescope_process, const char *, int);
135 static struct proto {
136 const char *schema;
137 const char *port;
138 int (*loadfn)(struct tab *, const char *);
139 } protos[] = {
140 {"about", NULL, load_about_url},
141 {"file", NULL, load_file_url},
142 {"finger", "79", load_finger_url},
143 {"gemini", "1965", load_gemini_url},
144 {"gopher", "70", load_gopher_url},
145 {NULL, NULL, NULL},
146 };
148 static imsg_handlerfn *handlers[] = {
149 [IMSG_ERR] = handle_imsg_err,
150 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
151 [IMSG_GOT_CODE] = handle_imsg_got_code,
152 [IMSG_GOT_META] = handle_imsg_got_meta,
153 [IMSG_BUF] = handle_imsg_buf,
154 [IMSG_EOF] = handle_imsg_eof,
155 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
156 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
157 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
158 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
159 [IMSG_SESSION_TAB] = handle_imsg_session,
160 [IMSG_SESSION_END] = handle_imsg_session,
161 };
163 static struct ohash certs;
165 static void __attribute__((__noreturn__))
166 die(void)
168 abort(); /* TODO */
171 static struct tab *
172 tab_by_id(uint32_t id)
174 struct tab *t;
176 TAILQ_FOREACH(t, &tabshead, tabs) {
177 if (t->id == id)
178 return t;
181 return NULL;
184 static void
185 handle_imsg_err(struct imsg *imsg, size_t datalen)
187 struct tab *tab;
188 char *page;
190 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
191 return;
193 page = imsg->data;
194 page[datalen-1] = '\0';
196 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
197 tab->hist_cur->h, page) == -1)
198 die();
199 load_page_from_str(tab, page);
200 free(page);
203 static void
204 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
206 const char *hash, *host, *port;
207 int tofu_res;
208 struct tofu_entry *e;
209 struct tab *tab;
211 hash = imsg->data;
212 if (hash[datalen-1] != '\0')
213 abort();
215 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
216 return;
218 if (tab->proxy != NULL) {
219 host = tab->proxy->host;
220 port = tab->proxy->port;
221 } else {
222 host = tab->uri.host;
223 port = tab->uri.port;
226 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
227 /* TODO: an update in libressl/libretls changed
228 * significantly. Find a better approach at storing
229 * the certs! */
230 if (datalen > sizeof(e->hash))
231 abort();
233 tofu_res = 1; /* trust on first use */
234 if ((e = calloc(1, sizeof(*e))) == NULL)
235 abort();
236 strlcpy(e->domain, host, sizeof(e->domain));
237 if (*port != '\0' && strcmp(port, "1965")) {
238 strlcat(e->domain, ":", sizeof(e->domain));
239 strlcat(e->domain, port, sizeof(e->domain));
241 strlcpy(e->hash, hash, sizeof(e->hash));
242 tofu_add(&certs, e);
243 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
244 } else
245 tofu_res = !strcmp(hash, e->hash);
247 if (tofu_res) {
248 if (e->verified == -1)
249 tab->trust = TS_TEMP_TRUSTED;
250 else if (e->verified == 1)
251 tab->trust = TS_VERIFIED;
252 else
253 tab->trust = TS_TRUSTED;
255 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
256 &tofu_res, sizeof(tofu_res));
257 } else {
258 tab->trust = TS_UNTRUSTED;
259 load_page_from_str(tab, "# Certificate mismatch\n");
260 if ((tab->cert = strdup(hash)) == NULL)
261 die();
262 ui_yornp("Certificate mismatch. Proceed?",
263 handle_check_cert_user_choice, tab);
267 static void
268 handle_check_cert_user_choice(int accept, struct tab *tab)
270 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
271 sizeof(accept));
273 if (accept) {
274 /*
275 * trust the certificate for this session only. If
276 * the page results in a redirect while we're asking
277 * the user to save, we'll end up with an invalid
278 * tabid (one request == one tab id). It also makes
279 * sense to save it for the current session if the
280 * user accepted it.
281 */
282 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
283 tab->cert);
285 if (!safe_mode)
286 ui_yornp("Save the new certificate?",
287 handle_maybe_save_new_cert, tab);
288 else
289 message("Certificate temporarly trusted");
290 } else {
291 free(tab->cert);
292 tab->cert = NULL;
296 static void
297 handle_maybe_save_new_cert(int accept, struct tab *tab)
299 struct tofu_entry *e;
300 const char *host, *port;
302 if (tab->proxy != NULL) {
303 host = tab->proxy->host;
304 port = tab->proxy->port;
305 } else {
306 host = tab->uri.host;
307 port = tab->uri.port;
310 if (!accept)
311 goto end;
313 if ((e = calloc(1, sizeof(*e))) == NULL)
314 die();
316 strlcpy(e->domain, host, sizeof(e->domain));
317 if (*port != '\0' && strcmp(port, "1965")) {
318 strlcat(e->domain, ":", sizeof(e->domain));
319 strlcat(e->domain, port, sizeof(e->domain));
321 strlcpy(e->hash, tab->cert, sizeof(e->hash));
322 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
324 tofu_update(&certs, e);
326 tab->trust = TS_TRUSTED;
328 end:
329 free(tab->cert);
330 tab->cert = NULL;
333 static inline int
334 normalize_code(int n)
336 if (n < 20) {
337 if (n == 10 || n == 11)
338 return n;
339 return 10;
340 } else if (n < 30) {
341 return 20;
342 } else if (n < 40) {
343 if (n == 30 || n == 31)
344 return n;
345 return 30;
346 } else if (n < 50) {
347 if (n <= 44)
348 return n;
349 return 40;
350 } else if (n < 60) {
351 if (n <= 53 || n == 59)
352 return n;
353 return 50;
354 } else if (n < 70) {
355 if (n <= 62)
356 return n;
357 return 60;
358 } else
359 return MALFORMED_RESPONSE;
362 static void
363 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
365 struct tab *tab;
367 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
368 return;
370 if (sizeof(tab->code) != datalen)
371 die();
373 memcpy(&tab->code, imsg->data, sizeof(tab->code));
374 tab->code = normalize_code(tab->code);
375 if (tab->code != 30 && tab->code != 31)
376 tab->redirect_count = 0;
379 static void
380 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
382 struct tab *tab;
383 char buf[128];
385 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
386 return;
388 if (sizeof(tab->meta) <= datalen)
389 die();
391 memcpy(tab->meta, imsg->data, datalen);
393 if (tab->code < 10) { /* internal errors */
394 load_page_from_str(tab, err_pages[tab->code]);
395 } else if (tab->code < 20) { /* 1x */
396 load_page_from_str(tab, err_pages[tab->code]);
397 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
398 } else if (tab->code == 20) {
399 if (setup_parser_for(tab)) {
400 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
401 } else if (safe_mode) {
402 load_page_from_str(tab,
403 err_pages[UNKNOWN_TYPE_OR_CSET]);
404 } else {
405 struct hist *h;
407 if ((h = hist_pop(&tab->hist)) != NULL)
408 tab->hist_cur = h;
409 snprintf(buf, sizeof(buf),
410 "Can't display \"%s\", save it?", tab->meta);
411 ui_yornp(buf, handle_maybe_save_page, tab);
413 } else if (tab->code < 40) { /* 3x */
414 tab->redirect_count++;
416 /* TODO: make customizable? */
417 if (tab->redirect_count > 5) {
418 load_page_from_str(tab,
419 err_pages[TOO_MUCH_REDIRECTS]);
420 } else
421 do_load_url(tab, tab->meta, NULL);
422 } else { /* 4x, 5x & 6x */
423 load_page_from_str(tab, err_pages[tab->code]);
427 static void
428 handle_maybe_save_page(int dosave, struct tab *tab)
430 const char *f;
431 char input[PATH_MAX];
433 /* XXX: this print a message that is confusing */
434 ui_on_tab_loaded(tab);
436 if (!dosave) {
437 stop_tab(tab);
438 return;
441 if ((f = strrchr(tab->uri.path, '/')) == NULL)
442 f = "";
443 else
444 f++;
446 strlcpy(input, download_path, sizeof(input));
447 strlcat(input, f, sizeof(input));
449 ui_read("Save to path", handle_save_page_path, tab, input);
452 static void
453 handle_save_page_path(const char *path, struct tab *tab)
455 if (path == NULL) {
456 stop_tab(tab);
457 return;
460 ui_show_downloads_pane();
462 enqueue_download(tab->id, path);
463 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
465 /*
466 * Change this tab id, the old one is associated with the
467 * download now.
468 */
469 tab->id = tab_new_id();
472 static void
473 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
475 struct download *d;
476 const char *e;
478 /*
479 * There are no reason we shouldn't be able to find the
480 * required download.
481 */
482 if ((d = download_by_id(imsg->hdr.peerid)) == NULL)
483 die();
485 if (imsg->fd == -1) {
486 e = imsg->data;
487 if (e[datalen-1] != '\0')
488 die();
489 message("Can't open file %s: %s", d->path, e);
490 } else {
491 d->fd = imsg->fd;
492 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
496 static void
497 handle_imsg_session(struct imsg *imsg, size_t datalen)
499 static struct tab *curr;
500 struct session_tab st;
501 struct tab *tab;
502 int first_time;
504 /*
505 * The fs process tried to send tabs after it has announced
506 * that he's done. Something fishy is going on, better die.
507 */
508 if (operating)
509 die();
511 if (imsg->hdr.type == IMSG_SESSION_END) {
512 if (datalen != sizeof(first_time))
513 die();
514 memcpy(&first_time, imsg->data, sizeof(first_time));
515 if (first_time) {
516 new_tab("about:new", NULL, NULL);
517 curr = new_tab("about:help", NULL, NULL);
520 operating = 1;
521 if (curr != NULL)
522 switch_to_tab(curr);
523 if (has_url || TAILQ_EMPTY(&tabshead))
524 new_tab(url, NULL, NULL);
525 ui_main_loop();
526 return;
529 if (datalen != sizeof(st))
530 die();
532 memcpy(&st, imsg->data, sizeof(st));
533 if ((tab = new_tab(st.uri, NULL, NULL)) == NULL)
534 die();
535 strlcpy(tab->buffer.page.title, st.title,
536 sizeof(tab->buffer.page.title));
537 if (st.flags & TAB_CURRENT)
538 curr = tab;
541 static void
542 handle_imsg_buf(struct imsg *imsg, size_t datalen)
544 struct tab *tab = NULL;
545 struct download *d = NULL;
547 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
548 (d = download_by_id(imsg->hdr.peerid)) == NULL)
549 return;
551 if (tab != NULL) {
552 if (!parser_parse(tab, imsg->data, datalen))
553 die();
554 ui_on_tab_refresh(tab);
555 } else {
556 d->bytes += datalen;
557 write(d->fd, imsg->data, datalen);
558 ui_on_download_refresh();
562 static void
563 handle_imsg_eof(struct imsg *imsg, size_t datalen)
565 struct tab *tab = NULL;
566 struct download *d = NULL;
568 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
569 (d = download_by_id(imsg->hdr.peerid)) == NULL)
570 return;
572 if (tab != NULL) {
573 if (!parser_free(tab))
574 die();
575 ui_on_tab_refresh(tab);
576 ui_on_tab_loaded(tab);
577 } else {
578 close(d->fd);
579 d->fd = -1;
580 ui_on_download_refresh();
584 static void
585 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
587 int res;
589 if (datalen != sizeof(res))
590 die();
592 memcpy(&res, imsg->data, sizeof(res));
593 if (res == 0)
594 message("Added to bookmarks!");
595 else
596 message("Failed to add to bookmarks: %s",
597 strerror(res));
600 static void
601 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
603 int res;
605 if (datalen != sizeof(res))
606 die();
607 memcpy(&res, imsg->data, datalen);
608 if (res != 0)
609 message("Failed to save the cert for: %s",
610 strerror(res));
613 static void
614 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
616 int res;
618 if (datalen != sizeof(res))
619 die();
620 memcpy(&res, imsg->data, datalen);
621 if (!res)
622 message("Failed to update the certificate");
625 static void
626 handle_dispatch_imsg(int fd, short ev, void *d)
628 struct imsgev *iev = d;
630 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
631 err(1, "connection closed");
634 static int
635 load_about_url(struct tab *tab, const char *url)
637 tab->trust = TS_UNKNOWN;
638 parser_init(tab, gemtext_initparser);
639 return make_fs_request(tab, IMSG_GET, url);
642 static int
643 load_file_url(struct tab *tab, const char *url)
645 tab->trust = TS_UNKNOWN;
646 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
649 static int
650 load_finger_url(struct tab *tab, const char *url)
652 struct get_req req;
653 size_t len;
654 char *at;
656 memset(&req, 0, sizeof(req));
657 strlcpy(req.port, tab->uri.port, sizeof(req.port));
659 /*
660 * Sometimes the finger url have the user as path component
661 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
662 * userinfo (e.g. finger://cobradile@finger.farm).
663 */
664 if ((at = strchr(tab->uri.host, '@')) != NULL) {
665 len = at - tab->uri.host;
666 memcpy(req.req, tab->uri.host, len);
668 if (len >= sizeof(req.req))
669 die();
670 req.req[len] = '\0';
672 strlcpy(req.host, at+1, sizeof(req.host));
673 } else {
674 strlcpy(req.host, tab->uri.host, sizeof(req.host));
676 /* +1 to skip the initial `/' */
677 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
679 strlcat(req.req, "\r\n", sizeof(req.req));
681 parser_init(tab, textplain_initparser);
682 return make_request(tab, &req, PROTO_FINGER, NULL);
685 static int
686 load_gemini_url(struct tab *tab, const char *url)
688 struct get_req req;
690 memset(&req, 0, sizeof(req));
691 strlcpy(req.host, tab->uri.host, sizeof(req.host));
692 strlcpy(req.port, tab->uri.port, sizeof(req.port));
694 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
697 static inline const char *
698 gopher_skip_selector(const char *path, int *ret_type)
700 *ret_type = 0;
702 if (!strcmp(path, "/") || *path == '\0') {
703 *ret_type = '1';
704 return path;
707 if (*path != '/')
708 return path;
709 path++;
711 switch (*ret_type = *path) {
712 case '0':
713 case '1':
714 case '7':
715 break;
717 default:
718 *ret_type = 0;
719 path -= 1;
720 return path;
723 return ++path;
726 static int
727 load_gopher_url(struct tab *tab, const char *url)
729 struct get_req req;
730 int type;
731 const char *path;
733 memset(&req, 0, sizeof(req));
734 strlcpy(req.host, tab->uri.host, sizeof(req.host));
735 strlcpy(req.port, tab->uri.port, sizeof(req.port));
737 path = gopher_skip_selector(tab->uri.path, &type);
738 switch (type) {
739 case '0':
740 parser_init(tab, textplain_initparser);
741 break;
742 case '1':
743 parser_init(tab, gophermap_initparser);
744 break;
745 case '7':
746 ui_require_input(tab, 0, PROTO_GOPHER);
747 return load_page_from_str(tab, err_pages[10]);
748 default:
749 return load_page_from_str(tab, "Unknown gopher selector");
752 strlcpy(req.req, path, sizeof(req.req));
753 if (*tab->uri.query != '\0') {
754 strlcat(req.req, "?", sizeof(req.req));
755 strlcat(req.req, tab->uri.query, sizeof(req.req));
757 strlcat(req.req, "\r\n", sizeof(req.req));
759 return make_request(tab, &req, PROTO_GOPHER, NULL);
762 static int
763 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
765 struct get_req req;
767 memset(&req, 0, sizeof(req));
768 strlcpy(req.host, p->host, sizeof(req.host));
769 strlcpy(req.port, p->port, sizeof(req.port));
771 tab->proxy = p;
773 return make_request(tab, &req, p->proto, tab->hist_cur->h);
776 static int
777 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
779 stop_tab(tab);
780 tab->id = tab_new_id();
781 req->proto = proto;
783 if (r != NULL) {
784 strlcpy(req->req, r, sizeof(req->req));
785 strlcat(req->req, "\r\n", sizeof(req->req));
788 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
790 /*
791 * So the various load_*_url can `return make_request` and
792 * do_load_url is happy.
793 */
794 return 1;
797 static int
798 make_fs_request(struct tab *tab, int type, const char *r)
800 stop_tab(tab);
801 tab->id = tab_new_id();
803 ui_send_fs(type, tab->id, r, strlen(r)+1);
805 /*
806 * So load_{about,file}_url can `return make_fs_request` and
807 * do_load_url is happy.
808 */
809 return 1;
812 void
813 gopher_send_search_req(struct tab *tab, const char *text)
815 struct get_req req;
817 start_loading_anim(tab);
819 memset(&req, 0, sizeof(req));
820 strlcpy(req.host, tab->uri.host, sizeof(req.host));
821 strlcpy(req.port, tab->uri.port, sizeof(req.port));
823 /* +2 to skip /7 */
824 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
825 if (*tab->uri.query != '\0') {
826 strlcat(req.req, "?", sizeof(req.req));
827 strlcat(req.req, tab->uri.query, sizeof(req.req));
830 strlcat(req.req, "\t", sizeof(req.req));
831 strlcat(req.req, text, sizeof(req.req));
832 strlcat(req.req, "\r\n", sizeof(req.req));
834 erase_buffer(&tab->buffer);
835 parser_init(tab, gophermap_initparser);
837 make_request(tab, &req, PROTO_GOPHER, NULL);
840 /*
841 * Effectively load the given url in the given tab. Return 1 when
842 * loading the page asynchronously, and thus when an erase_buffer can
843 * be done right after this function return, or 0 when loading the
844 * page synchronously.
845 */
846 static int
847 do_load_url(struct tab *tab, const char *url, const char *base)
849 struct phos_uri uri;
850 struct proto *p;
851 struct proxy *proxy;
852 char *t;
854 tab->proxy = NULL;
856 tab->trust = TS_UNKNOWN;
858 if (base == NULL)
859 memcpy(&uri, &tab->uri, sizeof(tab->uri));
860 else
861 phos_parse_absolute_uri(base, &uri);
863 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
864 if (asprintf(&t, "#error loading %s\n>%s\n",
865 url, "Can't parse the URI") == -1)
866 die();
867 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
868 load_page_from_str(tab, t);
869 free(t);
870 return 0;
873 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
874 sizeof(tab->hist_cur->h));
876 for (p = protos; p->schema != NULL; ++p) {
877 if (!strcmp(tab->uri.scheme, p->schema)) {
878 /* patch the port */
879 if (*tab->uri.port == '\0' && p->port != NULL)
880 strlcpy(tab->uri.port, p->port,
881 sizeof(tab->uri.port));
883 return p->loadfn(tab, url);
887 TAILQ_FOREACH(proxy, &proxies, proxies) {
888 if (!strcmp(tab->uri.scheme, proxy->match_proto))
889 return load_via_proxy(tab, url, proxy);
892 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
895 /*
896 * Load url in tab. If tab is marked as lazy, only prepare the url
897 * but don't load it. If tab is lazy and a url was already prepared,
898 * do load it!
899 */
900 void
901 load_url(struct tab *tab, const char *url, const char *base, int nohist)
903 int lazy;
905 lazy = tab->flags & TAB_LAZY;
907 if (lazy && tab->hist_cur != NULL) {
908 lazy = 0;
909 tab->flags &= ~TAB_LAZY;
912 /* can't have both nohist and lazy at the same time. */
913 if (nohist && lazy)
914 nohist = 0;
916 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
917 if (tab->hist_cur != NULL)
918 hist_clear_forward(&tab->hist,
919 TAILQ_NEXT(tab->hist_cur, entries));
921 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
922 == NULL) {
923 event_loopbreak();
924 return;
927 strlcpy(tab->buffer.page.title, url,
928 sizeof(tab->buffer.page.title));
929 hist_push(&tab->hist, tab->hist_cur);
931 if (lazy)
932 strlcpy(tab->hist_cur->h, url,
933 sizeof(tab->hist_cur->h));
936 if (!lazy)
937 do_load_url(tab, url, base);
940 void
941 load_url_in_tab(struct tab *tab, const char *url, const char *base, int nohist)
943 if (!operating) {
944 load_url(tab, url, base, nohist);
945 return;
948 autosave_hook();
950 message("Loading %s...", url);
951 start_loading_anim(tab);
952 load_url(tab, url, base, nohist);
955 int
956 load_previous_page(struct tab *tab)
958 struct hist *h;
960 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
961 return 0;
962 tab->hist_cur = h;
963 do_load_url(tab, h->h, NULL);
964 return 1;
967 int
968 load_next_page(struct tab *tab)
970 struct hist *h;
972 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
973 return 0;
974 tab->hist_cur = h;
975 do_load_url(tab, h->h, NULL);
976 return 1;
979 void
980 add_to_bookmarks(const char *str)
982 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
983 str, strlen(str)+1);
986 /*
987 * Given a user-entered URL, apply some heuristics to use it:
989 * - if it's a proper url use it
990 * - if it starts with a `./' or a `/' assume its a file:// url
991 * - assume it's a gemini:// url
993 * `ret' (of which len is the size) will be filled with the resulting
994 * url.
995 */
996 void
997 humanify_url(const char *raw, char *ret, size_t len)
999 struct phos_uri uri;
1000 char buf[PATH_MAX];
1002 if (phos_parse_absolute_uri(raw, &uri)) {
1003 strlcpy(ret, raw, len);
1004 return;
1007 if (has_prefix(raw, "./")) {
1008 strlcpy(ret, "file://", len);
1009 getcwd(buf, sizeof(buf));
1010 strlcat(ret, buf, len);
1011 strlcat(ret, "/", len);
1012 strlcat(ret, raw+2, len);
1013 return;
1016 if (*raw == '/') {
1017 strlcpy(ret, "file://", len);
1018 strlcat(ret, raw, len);
1019 return;
1022 strlcpy(ret, "gemini://", len);
1023 strlcat(ret, raw, len);
1026 static pid_t
1027 start_child(enum telescope_process p, const char *argv0, int fd)
1029 const char *argv[5];
1030 int argc = 0;
1031 pid_t pid;
1033 switch (pid = fork()) {
1034 case -1:
1035 die();
1036 case 0:
1037 break;
1038 default:
1039 close(fd);
1040 return pid;
1043 if (dup2(fd, 3) == -1)
1044 err(1, "cannot setup imsg fd");
1046 argv[argc++] = argv0;
1047 switch (p) {
1048 case PROC_UI:
1049 errx(1, "Can't start ui process");
1050 case PROC_FS:
1051 argv[argc++] = "-Tf";
1052 break;
1053 case PROC_NET:
1054 argv[argc++] = "-Tn";
1055 break;
1058 if (safe_mode)
1059 argv[argc++] = "-S";
1061 argv[argc++] = NULL;
1062 execvp(argv0, (char *const *)argv);
1063 err(1, "execvp(%s)", argv0);
1066 int
1067 ui_send_net(int type, uint32_t peerid, const void *data,
1068 uint16_t datalen)
1070 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1071 datalen);
1074 int
1075 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1077 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1078 datalen);
1081 static void __attribute__((noreturn))
1082 usage(int r)
1084 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1085 getprogname());
1086 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1087 exit(r);
1090 int
1091 main(int argc, char * const *argv)
1093 struct imsgev net_ibuf, fs_ibuf;
1094 pid_t pid;
1095 int pipe2net[2], pipe2fs[2];
1096 int ch, configtest = 0, fail = 0;
1097 int proc = -1;
1098 int sessionfd = -1;
1099 int status;
1100 const char *argv0;
1102 argv0 = argv[0];
1104 signal(SIGCHLD, SIG_IGN);
1105 signal(SIGPIPE, SIG_IGN);
1107 if (getenv("NO_COLOR") != NULL)
1108 enable_colors = 0;
1110 fs_init();
1112 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1113 switch (ch) {
1114 case 'C':
1115 exit(ui_print_colors());
1116 case 'c':
1117 fail = 1;
1118 strlcpy(config_path, optarg, sizeof(config_path));
1119 break;
1120 case 'n':
1121 configtest = 1;
1122 break;
1123 case 'h':
1124 usage(0);
1125 case 'S':
1126 safe_mode = 1;
1127 break;
1128 case 'T':
1129 switch (*optarg) {
1130 case 'f':
1131 proc = PROC_FS;
1132 break;
1133 case 'n':
1134 proc = PROC_NET;
1135 break;
1136 default:
1137 errx(1, "invalid process spec %c",
1138 *optarg);
1140 break;
1141 case 'v':
1142 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1143 exit(0);
1144 break;
1145 default:
1146 usage(1);
1150 argc -= optind;
1151 argv += optind;
1153 if (proc != -1) {
1154 if (argc > 0)
1155 usage(1);
1156 else if (proc == PROC_FS)
1157 return fs_main();
1158 else if (proc == PROC_NET)
1159 return net_main();
1160 else
1161 usage(1);
1164 if (argc != 0) {
1165 has_url = 1;
1166 humanify_url(argv[0], url, sizeof(url));
1169 /* setup keys before reading the config */
1170 TAILQ_INIT(&global_map.m);
1171 global_map.unhandled_input = global_key_unbound;
1172 TAILQ_INIT(&minibuffer_map.m);
1174 config_init();
1175 parseconfig(config_path, fail);
1176 if (configtest) {
1177 puts("config OK");
1178 exit(0);
1181 if (download_path == NULL &&
1182 (download_path = strdup("/tmp/")) == NULL)
1183 errx(1, "strdup");
1185 if (!safe_mode && (sessionfd = lock_session()) == -1)
1186 errx(1, "can't lock session, is another instance of "
1187 "telescope already running?");
1189 /* Start children. */
1190 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1191 err(1, "socketpair");
1192 start_child(PROC_FS, argv0, pipe2fs[1]);
1193 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1194 iev_fs = &fs_ibuf;
1195 iev_fs->handler = handle_dispatch_imsg;
1197 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1198 err(1, "socketpair");
1199 start_child(PROC_NET, argv0, pipe2net[1]);
1200 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1201 iev_net = &net_ibuf;
1202 iev_net->handler = handle_dispatch_imsg;
1204 setproctitle("ui");
1206 /* initialize tofu & load certificates */
1207 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1208 load_certs(&certs);
1210 event_init();
1212 /* Setup event handler for the autosave */
1213 autosave_init();
1215 /* Setup event handlers for pipes to fs/net */
1216 iev_fs->events = EV_READ;
1217 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1218 iev_fs->handler, iev_fs);
1219 event_add(&iev_fs->ev, NULL);
1221 iev_net->events = EV_READ;
1222 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1223 iev_net->handler, iev_net);
1224 event_add(&iev_net->ev, NULL);
1226 if (ui_init()) {
1227 sandbox_ui_process();
1228 event_dispatch();
1229 ui_end();
1232 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1233 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1234 imsg_flush(&iev_fs->ibuf);
1235 imsg_flush(&iev_net->ibuf);
1237 /* wait for children to terminate */
1238 do {
1239 pid = wait(&status);
1240 if (pid == -1) {
1241 if (errno != EINTR && errno != ECHILD)
1242 err(1, "wait");
1243 } else if (WIFSIGNALED(status))
1244 warnx("child terminated; signal %d", WTERMSIG(status));
1245 } while (pid != -1 || (pid == -1 && errno == EINTR));
1247 if (!safe_mode && close(sessionfd) == -1)
1248 err(1, "close(sessionfd = %d)", sessionfd);
1250 return 0;