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 "minibuffer.h"
32 #include "parser.h"
33 #include "session.h"
34 #include "telescope.h"
35 #include "ui.h"
37 static struct option longopts[] = {
38 {"colors", no_argument, NULL, 'c'},
39 {"help", no_argument, NULL, 'h'},
40 {"version", no_argument, NULL, 'v'},
41 {NULL, 0, NULL, 0},
42 };
44 static const char *opts = "Cc:hnT:v";
46 /*
47 * Used to know when we're finished loading.
48 */
49 int operating;
51 static struct imsgev *iev_fs, *iev_net;
53 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
54 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
56 enum telescope_process {
57 PROC_UI,
58 PROC_FS,
59 PROC_NET,
60 };
62 #define CANNOT_FETCH 0
63 #define TOO_MUCH_REDIRECTS 1
64 #define MALFORMED_RESPONSE 2
65 #define UNKNOWN_TYPE_OR_CSET 3
66 #define UNKNOWN_PROTOCOL 4
68 /* XXX: keep in sync with normalize_code */
69 const char *err_pages[70] = {
70 [CANNOT_FETCH] = "# Couldn't load the page\n",
71 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
72 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
73 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
74 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
76 [10] = "# Input required\n",
77 [11] = "# Input required\n",
78 [40] = "# Temporary failure\n",
79 [41] = "# Server unavailable\n",
80 [42] = "# CGI error\n",
81 [43] = "# Proxy error\n",
82 [44] = "# Slow down\n",
83 [50] = "# Permanent failure\n",
84 [51] = "# Not found\n",
85 [52] = "# Gone\n",
86 [53] = "# Proxy request refused\n",
87 [59] = "# Bad request\n",
88 [60] = "# Client certificate required\n",
89 [61] = "# Certificate not authorised\n",
90 [62] = "# Certificate not valid\n"
91 };
93 static void die(void) __attribute__((__noreturn__));
94 static struct tab *tab_by_id(uint32_t);
95 static void handle_imsg_err(struct imsg *, size_t);
96 static void handle_imsg_check_cert(struct imsg *, size_t);
97 static void handle_check_cert_user_choice(int, struct tab *);
98 static void handle_maybe_save_new_cert(int, struct tab *);
99 static void handle_imsg_got_code(struct imsg *, size_t);
100 static void handle_imsg_got_meta(struct imsg *, size_t);
101 static void handle_maybe_save_page(int, struct tab *);
102 static void handle_save_page_path(const char *, struct tab *);
103 static void handle_imsg_file_opened(struct imsg *, size_t);
104 static void handle_imsg_buf(struct imsg *, size_t);
105 static void handle_imsg_eof(struct imsg *, size_t);
106 static void handle_imsg_bookmark_ok(struct imsg *, size_t);
107 static void handle_imsg_save_cert_ok(struct imsg *, size_t);
108 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
109 static void handle_dispatch_imsg(int, short, void *);
110 static int load_about_url(struct tab *, const char *);
111 static int load_file_url(struct tab *, const char *);
112 static int load_finger_url(struct tab *, const char *);
113 static int load_gemini_url(struct tab *, const char *);
114 static int load_gopher_url(struct tab *, const char *);
115 static int load_via_proxy(struct tab *, const char *,
116 struct proxy *);
117 static int make_request(struct tab *, struct get_req *, int,
118 const char *);
119 static int make_fs_request(struct tab *, int, const char *);
120 static int do_load_url(struct tab *, const char *, const char *);
121 static pid_t start_child(enum telescope_process, const char *, int);
123 static struct proto {
124 const char *schema;
125 const char *port;
126 int (*loadfn)(struct tab *, const char *);
127 } protos[] = {
128 {"about", NULL, load_about_url},
129 {"file", NULL, load_file_url},
130 {"finger", "79", load_finger_url},
131 {"gemini", "1965", load_gemini_url},
132 {"gopher", "70", load_gopher_url},
133 {NULL, NULL, NULL},
134 };
136 static imsg_handlerfn *handlers[] = {
137 [IMSG_ERR] = handle_imsg_err,
138 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
139 [IMSG_GOT_CODE] = handle_imsg_got_code,
140 [IMSG_GOT_META] = handle_imsg_got_meta,
141 [IMSG_BUF] = handle_imsg_buf,
142 [IMSG_EOF] = handle_imsg_eof,
143 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
144 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
145 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
146 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
147 };
149 static struct ohash certs;
151 static void __attribute__((__noreturn__))
152 die(void)
154 abort(); /* TODO */
157 static struct tab *
158 tab_by_id(uint32_t id)
160 struct tab *t;
162 TAILQ_FOREACH(t, &tabshead, tabs) {
163 if (t->id == id)
164 return t;
167 return NULL;
170 static void
171 handle_imsg_err(struct imsg *imsg, size_t datalen)
173 struct tab *tab;
174 char *page;
176 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
177 return;
179 page = imsg->data;
180 page[datalen-1] = '\0';
182 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
183 tab->hist_cur->h, page) == -1)
184 die();
185 load_page_from_str(tab, page);
186 free(page);
189 static void
190 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
192 const char *hash, *host, *port;
193 int tofu_res;
194 struct tofu_entry *e;
195 struct tab *tab;
197 hash = imsg->data;
198 if (hash[datalen-1] != '\0')
199 abort();
201 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
202 return;
204 if (tab->proxy != NULL) {
205 host = tab->proxy->host;
206 port = tab->proxy->port;
207 } else {
208 host = tab->uri.host;
209 port = tab->uri.port;
212 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
213 /* TODO: an update in libressl/libretls changed
214 * significantly. Find a better approach at storing
215 * the certs! */
216 if (datalen > sizeof(e->hash))
217 abort();
219 tofu_res = 1; /* trust on first use */
220 if ((e = calloc(1, sizeof(*e))) == NULL)
221 abort();
222 strlcpy(e->domain, host, sizeof(e->domain));
223 if (*port != '\0' && strcmp(port, "1965")) {
224 strlcat(e->domain, ":", sizeof(e->domain));
225 strlcat(e->domain, port, sizeof(e->domain));
227 strlcpy(e->hash, hash, sizeof(e->hash));
228 tofu_add(&certs, e);
229 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
230 } else
231 tofu_res = !strcmp(hash, e->hash);
233 if (tofu_res) {
234 if (e->verified == -1)
235 tab->trust = TS_TEMP_TRUSTED;
236 else if (e->verified == 1)
237 tab->trust = TS_VERIFIED;
238 else
239 tab->trust = TS_TRUSTED;
241 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
242 &tofu_res, sizeof(tofu_res));
243 } else {
244 tab->trust = TS_UNTRUSTED;
245 load_page_from_str(tab, "# Certificate mismatch\n");
246 if ((tab->cert = strdup(hash)) == NULL)
247 die();
248 ui_yornp("Certificate mismatch. Proceed?",
249 handle_check_cert_user_choice, tab);
253 static void
254 handle_check_cert_user_choice(int accept, struct tab *tab)
256 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
257 sizeof(accept));
259 if (accept) {
260 /*
261 * trust the certificate for this session only. If
262 * the page results in a redirect while we're asking
263 * the user to save, we'll end up with an invalid
264 * tabid (one request == one tab id). It also makes
265 * sense to save it for the current session if the
266 * user accepted it.
267 */
268 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
269 tab->cert);
271 ui_yornp("Save the new certificate?",
272 handle_maybe_save_new_cert, tab);
273 } else {
274 free(tab->cert);
275 tab->cert = NULL;
279 static void
280 handle_maybe_save_new_cert(int accept, struct tab *tab)
282 struct tofu_entry *e;
283 const char *host, *port;
285 if (tab->proxy != NULL) {
286 host = tab->proxy->host;
287 port = tab->proxy->port;
288 } else {
289 host = tab->uri.host;
290 port = tab->uri.port;
293 if (!accept)
294 goto end;
296 if ((e = calloc(1, sizeof(*e))) == NULL)
297 die();
299 strlcpy(e->domain, host, sizeof(e->domain));
300 if (*port != '\0' && strcmp(port, "1965")) {
301 strlcat(e->domain, ":", sizeof(e->domain));
302 strlcat(e->domain, port, sizeof(e->domain));
304 strlcpy(e->hash, tab->cert, sizeof(e->hash));
305 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
307 tofu_update(&certs, e);
309 tab->trust = TS_TRUSTED;
311 end:
312 free(tab->cert);
313 tab->cert = NULL;
316 static inline int
317 normalize_code(int n)
319 if (n < 20) {
320 if (n == 10 || n == 11)
321 return n;
322 return 10;
323 } else if (n < 30) {
324 return 20;
325 } else if (n < 40) {
326 if (n == 30 || n == 31)
327 return n;
328 return 30;
329 } else if (n < 50) {
330 if (n <= 44)
331 return n;
332 return 40;
333 } else if (n < 60) {
334 if (n <= 53 || n == 59)
335 return n;
336 return 50;
337 } else if (n < 70) {
338 if (n <= 62)
339 return n;
340 return 60;
341 } else
342 return MALFORMED_RESPONSE;
345 static void
346 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
348 struct tab *tab;
350 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
351 return;
353 if (sizeof(tab->code) != datalen)
354 die();
356 memcpy(&tab->code, imsg->data, sizeof(tab->code));
357 tab->code = normalize_code(tab->code);
358 if (tab->code != 30 && tab->code != 31)
359 tab->redirect_count = 0;
362 static void
363 handle_imsg_got_meta(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->meta) <= datalen)
371 die();
373 memcpy(tab->meta, imsg->data, datalen);
375 if (tab->code < 10) { /* internal errors */
376 load_page_from_str(tab, err_pages[tab->code]);
377 } else if (tab->code < 20) { /* 1x */
378 load_page_from_str(tab, err_pages[tab->code]);
379 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
380 } else if (tab->code == 20) {
381 if (setup_parser_for(tab)) {
382 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
383 } else {
384 load_page_from_str(tab,
385 err_pages[UNKNOWN_TYPE_OR_CSET]);
386 ui_yornp("Can't display page, save it?",
387 handle_maybe_save_page, tab);
389 } else if (tab->code < 40) { /* 3x */
390 tab->redirect_count++;
392 /* TODO: make customizable? */
393 if (tab->redirect_count > 5) {
394 load_page_from_str(tab,
395 err_pages[TOO_MUCH_REDIRECTS]);
396 } else
397 do_load_url(tab, tab->meta, NULL);
398 } else { /* 4x, 5x & 6x */
399 load_page_from_str(tab, err_pages[tab->code]);
403 static void
404 handle_maybe_save_page(int dosave, struct tab *tab)
406 const char *f;
407 char input[PATH_MAX];
409 if (!dosave) {
410 stop_tab(tab);
411 return;
414 if ((f = strrchr(tab->uri.path, '/')) == NULL)
415 f = "";
416 else
417 f++;
419 strlcpy(input, download_path, sizeof(input));
420 strlcat(input, f, sizeof(input));
422 ui_read("Save to path", handle_save_page_path, tab, input);
425 static void
426 handle_save_page_path(const char *path, struct tab *tab)
428 if (path == NULL) {
429 stop_tab(tab);
430 return;
433 tab->path = strdup(path);
435 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
438 static void
439 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
441 struct tab *tab;
442 char *page;
443 const char *e;
444 int l;
446 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
447 if (imsg->fd != -1)
448 close(imsg->fd);
449 return;
452 if (imsg->fd == -1) {
453 stop_tab(tab);
455 e = imsg->data;
456 if (e[datalen-1] != '\0')
457 die();
458 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
459 tab->path, e);
460 if (l == -1)
461 die();
462 load_page_from_str(tab, page);
463 free(page);
464 } else {
465 tab->fd = imsg->fd;
466 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
470 static void
471 handle_imsg_buf(struct imsg *imsg, size_t datalen)
473 struct tab *tab;
474 int l;
475 char *page, buf[FMT_SCALED_STRSIZE] = {0};
477 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
478 return;
480 tab->bytes += datalen;
481 if (tab->fd == -1) {
482 if (!parser_parse(tab, imsg->data, datalen))
483 die();
484 } else {
485 write(tab->fd, imsg->data, datalen);
486 fmt_scaled(tab->bytes, buf);
487 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
488 tab->path,
489 buf);
490 if (l == -1)
491 die();
492 load_page_from_str(tab, page);
493 free(page);
496 ui_on_tab_refresh(tab);
499 static void
500 handle_imsg_eof(struct imsg *imsg, size_t datalen)
502 struct tab *tab;
503 int l;
504 char *page, buf[FMT_SCALED_STRSIZE] = {0};
506 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
507 return;
509 if (tab->fd == -1) {
510 if (!parser_free(tab))
511 die();
512 } else {
513 fmt_scaled(tab->bytes, buf);
514 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
515 tab->path,
516 buf);
517 if (l == -1)
518 die();
519 load_page_from_str(tab, page);
520 free(page);
522 close(tab->fd);
523 tab->fd = -1;
524 free(tab->path);
525 tab->path = NULL;
528 ui_on_tab_refresh(tab);
529 ui_on_tab_loaded(tab);
532 static void
533 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
535 int res;
537 if (datalen != sizeof(res))
538 die();
540 memcpy(&res, imsg->data, sizeof(res));
541 if (res == 0)
542 message("Added to bookmarks!");
543 else
544 message("Failed to add to bookmarks: %s",
545 strerror(res));
548 static void
549 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
551 int res;
553 if (datalen != sizeof(res))
554 die();
555 memcpy(&res, imsg->data, datalen);
556 if (res != 0)
557 message("Failed to save the cert for: %s",
558 strerror(res));
561 static void
562 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
564 int res;
566 if (datalen != sizeof(res))
567 die();
568 memcpy(&res, imsg->data, datalen);
569 if (!res)
570 message("Failed to update the certificate");
573 static void
574 handle_dispatch_imsg(int fd, short ev, void *d)
576 struct imsgev *iev = d;
578 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
579 err(1, "connection closed");
582 static int
583 load_about_url(struct tab *tab, const char *url)
585 tab->trust = TS_UNKNOWN;
586 parser_init(tab, gemtext_initparser);
587 return make_fs_request(tab, IMSG_GET, url);
590 static int
591 load_file_url(struct tab *tab, const char *url)
593 tab->trust = TS_UNKNOWN;
594 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
597 static int
598 load_finger_url(struct tab *tab, const char *url)
600 struct get_req req;
601 size_t len;
602 char *at;
604 memset(&req, 0, sizeof(req));
605 strlcpy(req.port, tab->uri.port, sizeof(req.port));
607 /*
608 * Sometimes the finger url have the user as path component
609 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
610 * userinfo (e.g. finger://cobradile@finger.farm).
611 */
612 if ((at = strchr(tab->uri.host, '@')) != NULL) {
613 len = at - tab->uri.host;
614 memcpy(req.req, tab->uri.host, len);
616 if (len >= sizeof(req.req))
617 die();
618 req.req[len] = '\0';
620 strlcpy(req.host, at+1, sizeof(req.host));
621 } else {
622 strlcpy(req.host, tab->uri.host, sizeof(req.host));
624 /* +1 to skip the initial `/' */
625 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
627 strlcat(req.req, "\r\n", sizeof(req.req));
629 parser_init(tab, textplain_initparser);
630 return make_request(tab, &req, PROTO_FINGER, NULL);
633 static int
634 load_gemini_url(struct tab *tab, const char *url)
636 struct get_req req;
638 memset(&req, 0, sizeof(req));
639 strlcpy(req.host, tab->uri.host, sizeof(req.host));
640 strlcpy(req.port, tab->uri.port, sizeof(req.host));
642 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
645 static inline const char *
646 gopher_skip_selector(const char *path, int *ret_type)
648 *ret_type = 0;
650 if (!strcmp(path, "/") || *path == '\0') {
651 *ret_type = '1';
652 return path;
655 if (*path != '/')
656 return path;
657 path++;
659 switch (*ret_type = *path) {
660 case '0':
661 case '1':
662 case '7':
663 break;
665 default:
666 *ret_type = 0;
667 path -= 1;
668 return path;
671 return ++path;
674 static int
675 load_gopher_url(struct tab *tab, const char *url)
677 struct get_req req;
678 int type;
679 const char *path;
681 memset(&req, 0, sizeof(req));
682 strlcpy(req.host, tab->uri.host, sizeof(req.host));
683 strlcpy(req.port, tab->uri.port, sizeof(req.host));
685 path = gopher_skip_selector(tab->uri.path, &type);
686 switch (type) {
687 case '0':
688 parser_init(tab, textplain_initparser);
689 break;
690 case '1':
691 parser_init(tab, gophermap_initparser);
692 break;
693 case '7':
694 ui_require_input(tab, 0, PROTO_GOPHER);
695 return load_page_from_str(tab, err_pages[10]);
696 default:
697 return load_page_from_str(tab, "Unknown gopher selector");
700 strlcpy(req.req, path, sizeof(req.req));
701 if (*tab->uri.query != '\0') {
702 strlcat(req.req, "?", sizeof(req.req));
703 strlcat(req.req, tab->uri.query, sizeof(req.req));
705 strlcat(req.req, "\r\n", sizeof(req.req));
707 return make_request(tab, &req, PROTO_GOPHER, NULL);
710 static int
711 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
713 struct get_req req;
715 memset(&req, 0, sizeof(req));
716 strlcpy(req.host, p->host, sizeof(req.host));
717 strlcpy(req.port, p->port, sizeof(req.host));
719 tab->proxy = p;
721 return make_request(tab, &req, p->proto, tab->hist_cur->h);
724 static int
725 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
727 stop_tab(tab);
728 tab->id = tab_new_id();
729 req->proto = proto;
731 if (r != NULL) {
732 strlcpy(req->req, r, sizeof(req->req));
733 strlcat(req->req, "\r\n", sizeof(req->req));
736 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
738 /*
739 * So the various load_*_url can `return make_request` and
740 * do_load_url is happy.
741 */
742 return 1;
745 static int
746 make_fs_request(struct tab *tab, int type, const char *r)
748 stop_tab(tab);
749 tab->id = tab_new_id();
751 ui_send_fs(type, tab->id, r, strlen(r)+1);
753 /*
754 * So load_{about,file}_url can `return make_fs_request` and
755 * do_load_url is happy.
756 */
757 return 1;
760 void
761 gopher_send_search_req(struct tab *tab, const char *text)
763 struct get_req req;
765 start_loading_anim(tab);
767 memset(&req, 0, sizeof(req));
768 strlcpy(req.host, tab->uri.host, sizeof(req.host));
769 strlcpy(req.port, tab->uri.port, sizeof(req.host));
771 /* +2 to skip /7 */
772 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
773 if (*tab->uri.query != '\0') {
774 strlcat(req.req, "?", sizeof(req.req));
775 strlcat(req.req, tab->uri.query, sizeof(req.req));
778 strlcat(req.req, "\t", sizeof(req.req));
779 strlcat(req.req, text, sizeof(req.req));
780 strlcat(req.req, "\r\n", sizeof(req.req));
782 erase_buffer(&tab->buffer);
783 parser_init(tab, gophermap_initparser);
785 make_request(tab, &req, PROTO_GOPHER, NULL);
788 /*
789 * Effectively load the given url in the given tab. Return 1 when
790 * loading the page asynchronously, and thus when an erase_buffer can
791 * be done right after this function return, or 0 when loading the
792 * page synchronously. In this last case, erase_buffer *MUST* be
793 * called by the handling function (such as load_page_from_str).
794 */
795 static int
796 do_load_url(struct tab *tab, const char *url, const char *base)
798 struct phos_uri uri;
799 struct proto *p;
800 struct proxy *proxy;
801 char *t;
803 tab->proxy = NULL;
805 if (tab->fd != -1) {
806 close(tab->fd);
807 tab->fd = -1;
808 free(tab->path);
809 tab->path = NULL;
812 tab->trust = TS_UNKNOWN;
814 if (base == NULL)
815 memcpy(&uri, &tab->uri, sizeof(tab->uri));
816 else
817 phos_parse_absolute_uri(base, &uri);
819 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
820 if (asprintf(&t, "#error loading %s\n>%s\n",
821 url, "Can't parse the URI") == -1)
822 die();
823 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
824 load_page_from_str(tab, t);
825 free(t);
826 return 0;
829 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
830 sizeof(tab->hist_cur->h));
832 for (p = protos; p->schema != NULL; ++p) {
833 if (!strcmp(tab->uri.scheme, p->schema)) {
834 /* patch the port */
835 if (*tab->uri.port == '\0' && p->port != NULL)
836 strlcpy(tab->uri.port, p->port,
837 sizeof(tab->uri.port));
839 return p->loadfn(tab, url);
843 TAILQ_FOREACH(proxy, &proxies, proxies) {
844 if (!strcmp(tab->uri.scheme, proxy->match_proto))
845 return load_via_proxy(tab, url, proxy);
848 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
851 /*
852 * Load url in tab. If tab is marked as lazy, only prepare the url
853 * but don't load it. If tab is lazy and a url was already prepared,
854 * do load it!
855 */
856 void
857 load_url(struct tab *tab, const char *url, const char *base, int nohist)
859 int lazy;
861 lazy = tab->flags & TAB_LAZY;
863 if (lazy && tab->hist_cur != NULL) {
864 lazy = 0;
865 tab->flags &= ~TAB_LAZY;
868 /* can't have both nohist and lazy at the same time. */
869 if (nohist && lazy)
870 nohist = 0;
872 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
873 if (tab->hist_cur != NULL)
874 hist_clear_forward(&tab->hist,
875 TAILQ_NEXT(tab->hist_cur, entries));
877 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
878 == NULL) {
879 event_loopbreak();
880 return;
883 strlcpy(tab->buffer.page.title, url,
884 sizeof(tab->buffer.page.title));
885 hist_push(&tab->hist, tab->hist_cur);
887 if (lazy)
888 strlcpy(tab->hist_cur->h, url,
889 sizeof(tab->hist_cur->h));
892 if (!lazy && do_load_url(tab, url, base))
893 erase_buffer(&tab->buffer);
896 void
897 load_url_in_tab(struct tab *tab, const char *url, const char *base, int nohist)
899 if (!operating) {
900 load_url(tab, url, base, nohist);
901 return;
904 autosave_hook();
906 message("Loading %s...", url);
907 start_loading_anim(tab);
908 load_url(tab, url, base, nohist);
911 int
912 load_previous_page(struct tab *tab)
914 struct hist *h;
916 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
917 return 0;
918 tab->hist_cur = h;
919 do_load_url(tab, h->h, NULL);
920 return 1;
923 int
924 load_next_page(struct tab *tab)
926 struct hist *h;
928 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
929 return 0;
930 tab->hist_cur = h;
931 do_load_url(tab, h->h, NULL);
932 return 1;
935 void
936 add_to_bookmarks(const char *str)
938 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
939 str, strlen(str)+1);
942 /*
943 * Given a user-entered URL, apply some heuristics to use it:
945 * - if it's a proper url use it
946 * - if it starts with a `./' or a `/' assume its a file:// url
947 * - assume it's a gemini:// url
949 * `ret' (of which len is the size) will be filled with the resulting
950 * url.
951 */
952 void
953 humanify_url(const char *raw, char *ret, size_t len)
955 struct phos_uri uri;
956 char buf[PATH_MAX];
958 if (phos_parse_absolute_uri(raw, &uri)) {
959 strlcpy(ret, raw, len);
960 return;
963 if (has_prefix(raw, "./")) {
964 strlcpy(ret, "file://", len);
965 getcwd(buf, sizeof(buf));
966 strlcat(ret, buf, len);
967 strlcat(ret, "/", len);
968 strlcat(ret, raw+2, len);
969 return;
972 if (*raw == '/') {
973 strlcpy(ret, "file://", len);
974 strlcat(ret, raw, len);
975 return;
978 strlcpy(ret, "gemini://", len);
979 strlcat(ret, raw, len);
982 static pid_t
983 start_child(enum telescope_process p, const char *argv0, int fd)
985 const char *argv[4];
986 int argc = 0;
987 pid_t pid;
989 switch (pid = fork()) {
990 case -1:
991 die();
992 case 0:
993 break;
994 default:
995 close(fd);
996 return pid;
999 if (dup2(fd, 3) == -1)
1000 err(1, "cannot setup imsg fd");
1002 argv[argc++] = argv0;
1003 switch (p) {
1004 case PROC_UI:
1005 errx(1, "Can't start ui process");
1006 case PROC_FS:
1007 argv[argc++] = "-Tf";
1008 break;
1009 case PROC_NET:
1010 argv[argc++] = "-Tn";
1011 break;
1014 argv[argc++] = NULL;
1015 execvp(argv0, (char *const *)argv);
1016 err(1, "execvp(%s)", argv0);
1019 int
1020 ui_send_net(int type, uint32_t peerid, const void *data,
1021 uint16_t datalen)
1023 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1024 datalen);
1027 int
1028 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1030 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1031 datalen);
1034 static void __attribute__((noreturn))
1035 usage(int r)
1037 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
1038 getprogname());
1039 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1040 exit(r);
1043 int
1044 main(int argc, char * const *argv)
1046 struct imsgev net_ibuf, fs_ibuf;
1047 pid_t pid;
1048 int pipe2net[2], pipe2fs[2];
1049 int ch, configtest = 0, fail = 0;
1050 int has_url = 0;
1051 int proc = -1;
1052 int sessionfd;
1053 int status;
1054 char path[PATH_MAX], url[GEMINI_URL_LEN+1];
1055 const char *argv0;
1057 argv0 = argv[0];
1059 signal(SIGCHLD, SIG_IGN);
1060 signal(SIGPIPE, SIG_IGN);
1062 if (getenv("NO_COLOR") != NULL)
1063 enable_colors = 0;
1065 strlcpy(path, getenv("HOME"), sizeof(path));
1066 strlcat(path, "/.telescope/config", sizeof(path));
1068 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1069 switch (ch) {
1070 case 'C':
1071 exit(ui_print_colors());
1072 case 'c':
1073 fail = 1;
1074 strlcpy(path, optarg, sizeof(path));
1075 break;
1076 case 'n':
1077 configtest = 1;
1078 break;
1079 case 'h':
1080 usage(0);
1081 case 'T':
1082 switch (*optarg) {
1083 case 'f':
1084 proc = PROC_FS;
1085 break;
1086 case 'n':
1087 proc = PROC_NET;
1088 break;
1089 default:
1090 errx(1, "invalid process spec %c",
1091 *optarg);
1093 break;
1094 case 'v':
1095 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1096 exit(0);
1097 break;
1098 default:
1099 usage(1);
1103 argc -= optind;
1104 argv += optind;
1106 if (proc != -1) {
1107 if (argc > 0)
1108 usage(1);
1109 else if (proc == PROC_FS)
1110 return fs_main();
1111 else if (proc == PROC_NET)
1112 return net_main();
1113 else
1114 usage(1);
1117 if (argc != 0) {
1118 has_url = 1;
1119 humanify_url(argv[0], url, sizeof(url));
1122 /* setup keys before reading the config */
1123 TAILQ_INIT(&global_map.m);
1124 global_map.unhandled_input = global_key_unbound;
1125 TAILQ_INIT(&minibuffer_map.m);
1127 config_init();
1128 parseconfig(path, fail);
1129 if (configtest) {
1130 puts("config OK");
1131 exit(0);
1134 if (download_path == NULL &&
1135 (download_path = strdup("/tmp/")) == NULL)
1136 errx(1, "strdup");
1138 fs_init();
1139 if ((sessionfd = lock_session()) == -1)
1140 errx(1, "can't lock session, is another instance of "
1141 "telescope already running?");
1143 /* Start children. */
1144 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1145 err(1, "socketpair");
1146 start_child(PROC_FS, argv0, pipe2fs[1]);
1147 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1148 iev_fs = &fs_ibuf;
1149 iev_fs->handler = handle_dispatch_imsg;
1151 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1152 err(1, "socketpair");
1153 start_child(PROC_NET, argv0, pipe2net[1]);
1154 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1155 iev_net = &net_ibuf;
1156 iev_net->handler = handle_dispatch_imsg;
1158 setproctitle("ui");
1160 /* initialize tofu & load certificates */
1161 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1162 load_certs(&certs);
1164 event_init();
1166 /* Setup event handler for the autosave */
1167 autosave_init();
1169 /* Setup event handlers for pipes to fs/net */
1170 iev_fs->events = EV_READ;
1171 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1172 iev_fs->handler, iev_fs);
1173 event_add(&iev_fs->ev, NULL);
1175 iev_net->events = EV_READ;
1176 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1177 iev_net->handler, iev_net);
1178 event_add(&iev_net->ev, NULL);
1180 if (ui_init()) {
1181 load_last_session();
1182 if (has_url || TAILQ_EMPTY(&tabshead))
1183 new_tab(url, NULL, NULL);
1185 sandbox_ui_process();
1186 operating = 1;
1187 ui_main_loop();
1188 ui_end();
1191 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1192 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1193 imsg_flush(&iev_fs->ibuf);
1194 imsg_flush(&iev_net->ibuf);
1196 /* wait for children to terminate */
1197 do {
1198 pid = wait(&status);
1199 if (pid == -1) {
1200 if (errno != EINTR && errno != ECHILD)
1201 err(1, "wait");
1202 } else if (WIFSIGNALED(status))
1203 warnx("child terminated; signal %d", WTERMSIG(status));
1204 } while (pid != -1 || (pid == -1 && errno == EINTR));
1206 close(sessionfd);
1208 return 0;