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>
21 #include <errno.h>
22 #include <getopt.h>
23 #include <limits.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 "telescope.h"
34 #include "ui.h"
36 static struct option longopts[] = {
37 {"colors", no_argument, NULL, 'c'},
38 {"help", no_argument, NULL, 'h'},
39 {"version", no_argument, NULL, 'v'},
40 {NULL, 0, NULL, 0},
41 };
43 static const char *opts = "Cc:hnT:v";
45 static struct imsgev *iev_fs, *iev_net;
47 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
48 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
50 enum telescope_process {
51 PROC_UI,
52 PROC_FS,
53 PROC_NET,
54 };
56 #define CANNOT_FETCH 0
57 #define TOO_MUCH_REDIRECTS 1
58 #define MALFORMED_RESPONSE 2
59 #define UNKNOWN_TYPE_OR_CSET 3
60 #define UNKNOWN_PROTOCOL 4
62 /* XXX: keep in sync with telescope.c:/^normalize_code/ */
63 const char *err_pages[70] = {
64 [CANNOT_FETCH] = "# Couldn't load the page\n",
65 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
66 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
67 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
68 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
70 [10] = "# Input required\n",
71 [11] = "# Input required\n",
72 [40] = "# Temporary failure\n",
73 [41] = "# Server unavailable\n",
74 [42] = "# CGI error\n",
75 [43] = "# Proxy error\n",
76 [44] = "# Slow down\n",
77 [50] = "# Permanent failure\n",
78 [51] = "# Not found\n",
79 [52] = "# Gone\n",
80 [53] = "# Proxy request refused\n",
81 [59] = "# Bad request\n",
82 [60] = "# Client certificate required\n",
83 [61] = "# Certificate not authorised\n",
84 [62] = "# Certificate not valid\n"
85 };
87 static void die(void) __attribute__((__noreturn__));
88 static struct tab *tab_by_id(uint32_t);
89 static void handle_imsg_err(struct imsg*, size_t);
90 static void handle_imsg_check_cert(struct imsg*, size_t);
91 static void handle_check_cert_user_choice(int, struct tab *);
92 static void handle_maybe_save_new_cert(int, struct tab *);
93 static void handle_imsg_got_code(struct imsg*, size_t);
94 static void handle_imsg_got_meta(struct imsg*, size_t);
95 static void handle_maybe_save_page(int, struct tab *);
96 static void handle_save_page_path(const char *, struct tab *);
97 static void handle_imsg_file_opened(struct imsg*, size_t);
98 static void handle_imsg_buf(struct imsg*, size_t);
99 static void handle_imsg_eof(struct imsg*, size_t);
100 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
101 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
102 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
103 static void handle_dispatch_imsg(int, short, void*);
104 static int load_page_from_str(struct tab*, const char*);
105 static int load_about_url(struct tab*, const char*);
106 static int load_finger_url(struct tab *, const char *);
107 static int load_gemini_url(struct tab*, const char*);
108 static int load_gopher_url(struct tab *, const char *);
109 static int load_via_proxy(struct tab *, const char *,
110 struct proxy *);
111 static int make_request(struct tab *, struct get_req *, int,
112 const char *);
113 static int make_fs_request(struct tab *, int, const char *);
114 static int do_load_url(struct tab*, const char *, const char *);
115 static void parse_session_line(char *, const char **, uint32_t *);
116 static void load_last_session(void);
117 static pid_t start_child(enum telescope_process, const char *, int);
118 static int ui_send_net(int, uint32_t, const void *, uint16_t);
119 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
121 static struct proto {
122 const char *schema;
123 const char *port;
124 int (*loadfn)(struct tab*, const char*);
125 } protos[] = {
126 {"about", NULL, load_about_url},
127 {"finger", "79", load_finger_url},
128 {"gemini", "1965", load_gemini_url},
129 {"gopher", "70", load_gopher_url},
130 {NULL, NULL, NULL},
131 };
133 static imsg_handlerfn *handlers[] = {
134 [IMSG_ERR] = handle_imsg_err,
135 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
136 [IMSG_GOT_CODE] = handle_imsg_got_code,
137 [IMSG_GOT_META] = handle_imsg_got_meta,
138 [IMSG_BUF] = handle_imsg_buf,
139 [IMSG_EOF] = handle_imsg_eof,
140 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
141 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
142 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
143 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
144 };
146 static struct ohash certs;
148 static void __attribute__((__noreturn__))
149 die(void)
151 abort(); /* TODO */
154 static struct tab *
155 tab_by_id(uint32_t id)
157 struct tab *t;
159 TAILQ_FOREACH(t, &tabshead, tabs) {
160 if (t->id == id)
161 return t;
164 return NULL;
167 static void
168 handle_imsg_err(struct imsg *imsg, size_t datalen)
170 struct tab *tab;
171 char *page;
173 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
174 return;
176 page = imsg->data;
177 page[datalen-1] = '\0';
179 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
180 tab->hist_cur->h, page) == -1)
181 die();
182 load_page_from_str(tab, page);
183 free(page);
186 static void
187 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
189 const char *hash, *host, *port;
190 int tofu_res;
191 struct tofu_entry *e;
192 struct tab *tab;
194 hash = imsg->data;
195 if (hash[datalen-1] != '\0')
196 abort();
198 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
199 return;
201 if (tab->proxy != NULL) {
202 host = tab->proxy->host;
203 port = tab->proxy->port;
204 } else {
205 host = tab->uri.host;
206 port = tab->uri.port;
209 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
210 /* TODO: an update in libressl/libretls changed
211 * significantly. Find a better approach at storing
212 * the certs! */
213 if (datalen > sizeof(e->hash))
214 abort();
216 tofu_res = 1; /* trust on first use */
217 if ((e = calloc(1, sizeof(*e))) == NULL)
218 abort();
219 strlcpy(e->domain, host, sizeof(e->domain));
220 if (*port != '\0' && strcmp(port, "1965")) {
221 strlcat(e->domain, ":", sizeof(e->domain));
222 strlcat(e->domain, port, sizeof(e->domain));
224 strlcpy(e->hash, hash, sizeof(e->hash));
225 tofu_add(&certs, e);
226 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
227 } else
228 tofu_res = !strcmp(hash, e->hash);
230 if (tofu_res) {
231 if (e->verified == -1)
232 tab->trust = TS_TEMP_TRUSTED;
233 else if (e->verified == 1)
234 tab->trust = TS_VERIFIED;
235 else
236 tab->trust = TS_TRUSTED;
238 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
239 &tofu_res, sizeof(tofu_res));
240 } else {
241 tab->trust = TS_UNTRUSTED;
242 load_page_from_str(tab, "# Certificate mismatch\n");
243 if ((tab->cert = strdup(hash)) == NULL)
244 die();
245 ui_yornp("Certificate mismatch. Proceed?",
246 handle_check_cert_user_choice, tab);
250 static void
251 handle_check_cert_user_choice(int accept, struct tab *tab)
253 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
254 sizeof(accept));
256 if (accept) {
257 /*
258 * trust the certificate for this session only. If
259 * the page results in a redirect while we're asking
260 * the user to save, we'll end up with an invalid
261 * tabid (one request == one tab id) and crash. It
262 * also makes sense to save it for the current session
263 * if the user accepted it.
264 */
265 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
267 ui_yornp("Save the new certificate?",
268 handle_maybe_save_new_cert, tab);
269 } else {
270 free(tab->cert);
271 tab->cert = NULL;
275 static void
276 handle_maybe_save_new_cert(int accept, struct tab *tab)
278 struct tofu_entry *e;
279 const char *host, *port;
281 if (tab->proxy != NULL) {
282 host = tab->proxy->host;
283 port = tab->proxy->port;
284 } else {
285 host = tab->uri.host;
286 port = tab->uri.port;
289 if (!accept)
290 goto end;
292 if ((e = calloc(1, sizeof(*e))) == NULL)
293 die();
295 strlcpy(e->domain, host, sizeof(e->domain));
296 if (*port != '\0' && strcmp(port, "1965")) {
297 strlcat(e->domain, ":", sizeof(e->domain));
298 strlcat(e->domain, port, sizeof(e->domain));
300 strlcpy(e->hash, tab->cert, sizeof(e->hash));
301 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
303 tofu_update(&certs, e);
305 tab->trust = TS_TRUSTED;
307 end:
308 free(tab->cert);
309 tab->cert = NULL;
312 static inline int
313 normalize_code(int n)
315 if (n < 20) {
316 if (n == 10 || n == 11)
317 return n;
318 return 10;
319 } else if (n < 30) {
320 return 20;
321 } else if (n < 40) {
322 if (n == 30 || n == 31)
323 return n;
324 return 30;
325 } else if (n < 50) {
326 if (n <= 44)
327 return n;
328 return 40;
329 } else if (n < 60) {
330 if (n <= 53 || n == 59)
331 return n;
332 return 50;
333 } else if (n < 70) {
334 if (n <= 62)
335 return n;
336 return 60;
337 } else
338 return MALFORMED_RESPONSE;
341 static void
342 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
344 struct tab *tab;
346 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
347 return;
349 if (sizeof(tab->code) != datalen)
350 die();
352 memcpy(&tab->code, imsg->data, sizeof(tab->code));
353 tab->code = normalize_code(tab->code);
354 if (tab->code != 30 && tab->code != 31)
355 tab->redirect_count = 0;
358 static void
359 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
361 struct tab *tab;
363 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
364 return;
366 if (sizeof(tab->meta) <= datalen)
367 die();
369 memcpy(tab->meta, imsg->data, datalen);
371 if (tab->code < 10) { /* internal errors */
372 load_page_from_str(tab, err_pages[tab->code]);
373 } else if (tab->code < 20) { /* 1x */
374 load_page_from_str(tab, err_pages[tab->code]);
375 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
376 } else if (tab->code == 20) {
377 if (setup_parser_for(tab)) {
378 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
379 } else {
380 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
381 ui_yornp("Can't display page, wanna save?",
382 handle_maybe_save_page, tab);
384 } else if (tab->code < 40) { /* 3x */
385 tab->redirect_count++;
387 /* TODO: make customizable? */
388 if (tab->redirect_count > 5) {
389 load_page_from_str(tab,
390 err_pages[TOO_MUCH_REDIRECTS]);
391 } else
392 do_load_url(tab, tab->meta, NULL);
393 } else { /* 4x, 5x & 6x */
394 load_page_from_str(tab, err_pages[tab->code]);
398 static void
399 handle_maybe_save_page(int dosave, struct tab *tab)
401 if (dosave)
402 ui_read("Save to path", handle_save_page_path, tab);
403 else
404 stop_tab(tab);
407 static void
408 handle_save_page_path(const char *path, struct tab *tab)
410 if (path == NULL) {
411 stop_tab(tab);
412 return;
415 tab->path = strdup(path);
417 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
420 static void
421 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
423 struct tab *tab;
424 char *page;
425 const char *e;
426 int l;
428 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
429 if (imsg->fd != -1)
430 close(imsg->fd);
431 return;
434 if (imsg->fd == -1) {
435 stop_tab(tab);
437 e = imsg->data;
438 if (e[datalen-1] != '\0')
439 die();
440 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
441 tab->path, e);
442 if (l == -1)
443 die();
444 load_page_from_str(tab, page);
445 free(page);
446 } else {
447 tab->fd = imsg->fd;
448 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
452 static void
453 handle_imsg_buf(struct imsg *imsg, size_t datalen)
455 struct tab *tab;
456 int l;
457 char *page, buf[FMT_SCALED_STRSIZE] = {0};
459 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
460 return;
462 tab->bytes += datalen;
463 if (tab->fd == -1) {
464 if (!parser_parse(tab, imsg->data, datalen))
465 die();
466 } else {
467 write(tab->fd, imsg->data, datalen);
468 fmt_scaled(tab->bytes, buf);
469 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
470 tab->path,
471 buf);
472 if (l == -1)
473 die();
474 load_page_from_str(tab, page);
475 free(page);
478 ui_on_tab_refresh(tab);
481 static void
482 handle_imsg_eof(struct imsg *imsg, size_t datalen)
484 struct tab *tab;
485 int l;
486 char *page, buf[FMT_SCALED_STRSIZE] = {0};
488 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
489 return;
491 if (tab->fd == -1) {
492 if (!parser_free(tab))
493 die();
494 } else {
495 fmt_scaled(tab->bytes, buf);
496 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
497 tab->path,
498 buf);
499 if (l == -1)
500 die();
501 load_page_from_str(tab, page);
502 free(page);
504 close(tab->fd);
505 tab->fd = -1;
506 free(tab->path);
507 tab->path = NULL;
510 ui_on_tab_refresh(tab);
511 ui_on_tab_loaded(tab);
514 static void
515 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
517 int res;
519 if (datalen != sizeof(res))
520 die();
522 memcpy(&res, imsg->data, sizeof(res));
523 if (res == 0)
524 message("Added to bookmarks!");
525 else
526 message("Failed to add to bookmarks: %s",
527 strerror(res));
530 static void
531 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
533 int res;
535 if (datalen != sizeof(res))
536 die();
537 memcpy(&res, imsg->data, datalen);
538 if (res != 0)
539 message("Failed to save the cert for: %s",
540 strerror(res));
543 static void
544 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
546 int res;
548 if (datalen != sizeof(res))
549 die();
550 memcpy(&res, imsg->data, datalen);
551 if (!res)
552 message("Failed to update the certificate");
555 static void
556 handle_dispatch_imsg(int fd, short ev, void *d)
558 struct imsgev *iev = d;
560 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
561 err(1, "connection closed");
564 static int
565 load_page_from_str(struct tab *tab, const char *page)
567 erase_buffer(&tab->buffer);
568 parser_init(tab, gemtext_initparser);
569 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
570 die();
571 if (!tab->buffer.page.free(&tab->buffer.page))
572 die();
573 ui_on_tab_refresh(tab);
574 ui_on_tab_loaded(tab);
575 return 0;
578 static int
579 load_about_url(struct tab *tab, const char *url)
581 tab->trust = TS_VERIFIED;
582 parser_init(tab, gemtext_initparser);
583 return make_fs_request(tab, IMSG_GET, url);
586 static int
587 load_finger_url(struct tab *tab, const char *url)
589 struct get_req req;
590 size_t len;
591 char *at;
593 memset(&req, 0, sizeof(req));
594 strlcpy(req.port, tab->uri.port, sizeof(req.port));
596 /*
597 * Sometimes the finger url have the user as path component
598 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
599 * userinfo (e.g. finger://cobradile@finger.farm).
600 */
601 if ((at = strchr(tab->uri.host, '@')) != NULL) {
602 len = at - tab->uri.host;
603 memcpy(req.req, tab->uri.host, len);
605 if (len >= sizeof(req.req))
606 die();
607 req.req[len] = '\0';
609 strlcpy(req.host, at+1, sizeof(req.host));
610 } else {
611 strlcpy(req.host, tab->uri.host, sizeof(req.host));
613 /* +1 to skip the initial `/' */
614 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
616 strlcat(req.req, "\r\n", sizeof(req.req));
618 parser_init(tab, textplain_initparser);
619 return make_request(tab, &req, PROTO_FINGER, NULL);
622 static int
623 load_gemini_url(struct tab *tab, const char *url)
625 struct get_req req;
627 memset(&req, 0, sizeof(req));
628 strlcpy(req.host, tab->uri.host, sizeof(req.host));
629 strlcpy(req.port, tab->uri.port, sizeof(req.host));
631 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
634 static int
635 load_gopher_url(struct tab *tab, const char *url)
637 struct get_req req;
638 const char *path;
640 memset(&req, 0, sizeof(req));
641 strlcpy(req.host, tab->uri.host, sizeof(req.host));
642 strlcpy(req.port, tab->uri.port, sizeof(req.host));
644 path = tab->uri.path;
645 if (!strcmp(path, "/") || *path == '\0') {
646 /* expect the top directory to be a gophermap */
647 parser_init(tab, gophermap_initparser);
648 } else if (has_prefix(path, "/1/")) {
649 /* gophermap menu/submenu */
650 parser_init(tab, gophermap_initparser);
651 path += 2;
652 } else if (has_prefix(path, "/0/")) {
653 parser_init(tab, textplain_initparser);
654 path += 2;
655 } else if (has_prefix(path, "/7/")) {
656 /* show input request if there is no query */
657 ui_require_input(tab, 0, PROTO_GOPHER);
658 return load_page_from_str(tab, err_pages[10]);
659 } else {
660 return 0;
663 strlcpy(req.req, path, sizeof(req.req));
664 if (*tab->uri.query != '\0') {
665 strlcat(req.req, "?", sizeof(req.req));
666 strlcat(req.req, tab->uri.query, sizeof(req.req));
668 strlcat(req.req, "\r\n", sizeof(req.req));
670 return make_request(tab, &req, PROTO_GOPHER, NULL);
673 static int
674 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
676 struct get_req req;
678 memset(&req, 0, sizeof(req));
679 strlcpy(req.host, p->host, sizeof(req.host));
680 strlcpy(req.port, p->port, sizeof(req.host));
682 tab->proxy = p;
684 return make_request(tab, &req, p->proto, tab->hist_cur->h);
687 static int
688 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
690 stop_tab(tab);
691 tab->id = tab_new_id();
692 req->proto = proto;
694 if (r != NULL) {
695 strlcpy(req->req, r, sizeof(req->req));
696 strlcat(req->req, "\r\n", sizeof(req->req));
699 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
701 /*
702 * So the various load_*_url can `return make_request` and
703 * do_load_url is happy.
704 */
705 return 1;
708 static int
709 make_fs_request(struct tab *tab, int type, const char *r)
711 stop_tab(tab);
712 tab->id = tab_new_id();
714 ui_send_fs(type, tab->id, r, strlen(r)+1);
716 /*
717 * So load_{about,file}_url can `return make_fs_request` and
718 * do_load_url is happy.
719 */
720 return 1;
723 void
724 gopher_send_search_req(struct tab *tab, const char *text)
726 struct get_req req;
728 start_loading_anim(tab);
730 memset(&req, 0, sizeof(req));
731 strlcpy(req.host, tab->uri.host, sizeof(req.host));
732 strlcpy(req.port, tab->uri.port, sizeof(req.host));
734 /* +2 to skip /7 */
735 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
736 if (*tab->uri.query != '\0') {
737 strlcat(req.req, "?", sizeof(req.req));
738 strlcat(req.req, tab->uri.query, sizeof(req.req));
741 strlcat(req.req, "\t", sizeof(req.req));
742 strlcat(req.req, text, sizeof(req.req));
743 strlcat(req.req, "\r\n", sizeof(req.req));
745 erase_buffer(&tab->buffer);
746 parser_init(tab, gophermap_initparser);
748 make_request(tab, &req, PROTO_GOPHER, NULL);
751 /*
752 * Effectively load the given url in the given tab. Return 1 when
753 * loading the page asynchronously, and thus when an erase_buffer can
754 * be done right after this function return, or 0 when loading the
755 * page synchronously. In this last case, erase_buffer *MUST* be
756 * called by the handling function (such as load_page_from_str).
757 */
758 static int
759 do_load_url(struct tab *tab, const char *url, const char *base)
761 struct phos_uri uri;
762 struct proto *p;
763 struct proxy *proxy;
764 char *t;
766 tab->proxy = NULL;
768 if (tab->fd != -1) {
769 close(tab->fd);
770 tab->fd = -1;
771 free(tab->path);
772 tab->path = NULL;
775 tab->trust = TS_UNKNOWN;
777 if (base == NULL)
778 memcpy(&uri, &tab->uri, sizeof(tab->uri));
779 else
780 phos_parse_absolute_uri(base, &uri);
782 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
783 if (asprintf(&t, "#error loading %s\n>%s\n",
784 url, "Can't parse the URI") == -1)
785 die();
786 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
787 load_page_from_str(tab, t);
788 free(t);
789 return 0;
792 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
793 sizeof(tab->hist_cur->h));
795 for (p = protos; p->schema != NULL; ++p) {
796 if (!strcmp(tab->uri.scheme, p->schema)) {
797 /* patch the port */
798 if (*tab->uri.port == '\0' && p->port != NULL)
799 strlcpy(tab->uri.port, p->port,
800 sizeof(tab->uri.port));
802 return p->loadfn(tab, url);
806 TAILQ_FOREACH(proxy, &proxies, proxies) {
807 if (!strcmp(tab->uri.scheme, proxy->match_proto))
808 return load_via_proxy(tab, url, proxy);
811 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
814 /*
815 * Load url in tab. If tab is marked as lazy, only prepare the url
816 * but don't load it. If tab is lazy and a url was already prepared,
817 * do load it!
818 */
819 void
820 load_url(struct tab *tab, const char *url, const char *base, int nohist)
822 int lazy;
824 lazy = tab->flags & TAB_LAZY;
826 if (lazy && tab->hist_cur != NULL) {
827 lazy = 0;
828 tab->flags &= ~TAB_LAZY;
831 /* can't have both nohist and lazy at the same time. */
832 if (nohist && lazy)
833 nohist = 0;
835 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
836 if (tab->hist_cur != NULL)
837 hist_clear_forward(&tab->hist,
838 TAILQ_NEXT(tab->hist_cur, entries));
840 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
841 event_loopbreak();
842 return;
845 strlcpy(tab->buffer.page.title, url,
846 sizeof(tab->buffer.page.title));
847 hist_push(&tab->hist, tab->hist_cur);
849 if (lazy)
850 strlcpy(tab->hist_cur->h, url,
851 sizeof(tab->hist_cur->h));
854 if (!lazy && do_load_url(tab, url, base))
855 erase_buffer(&tab->buffer);
858 int
859 load_previous_page(struct tab *tab)
861 struct hist *h;
863 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
864 return 0;
865 tab->hist_cur = h;
866 do_load_url(tab, h->h, NULL);
867 return 1;
870 int
871 load_next_page(struct tab *tab)
873 struct hist *h;
875 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
876 return 0;
877 tab->hist_cur = h;
878 do_load_url(tab, h->h, NULL);
879 return 1;
882 /*
883 * Free every resource linked to the tab, including the tab itself.
884 * Removes the tab from the tablist, but doesn't update the
885 * current_tab though.
886 */
887 void
888 free_tab(struct tab *tab)
890 stop_tab(tab);
892 if (evtimer_pending(&tab->loadingev, NULL))
893 evtimer_del(&tab->loadingev);
895 TAILQ_REMOVE(&tabshead, tab, tabs);
896 free(tab);
899 void
900 stop_tab(struct tab *tab)
902 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
904 if (tab->fd != -1) {
905 close(tab->fd);
906 tab->fd = -1;
907 free(tab->path);
908 tab->path = NULL;
909 load_page_from_str(tab, "Stopped.\n");
913 void
914 add_to_bookmarks(const char *str)
916 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
917 str, strlen(str)+1);
920 void
921 save_session(void)
923 struct tab *tab;
924 char *t;
925 int flags;
927 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
929 TAILQ_FOREACH(tab, &tabshead, tabs) {
930 flags = tab->flags;
931 if (tab == current_tab)
932 flags |= TAB_CURRENT;
934 t = tab->hist_cur->h;
935 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
937 t = tab->buffer.page.title;
938 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
941 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
944 /*
945 * Parse a line of the session file. The format is:
947 * URL [flags,...] [title]\n
948 */
949 static void
950 parse_session_line(char *line, const char **title, uint32_t *flags)
952 char *s, *t, *ap;
954 *title = "";
955 *flags = 0;
956 if ((s = strchr(line, ' ')) == NULL)
957 return;
959 *s++ = '\0';
961 if ((t = strchr(s, ' ')) != NULL) {
962 *t++ = '\0';
963 *title = t;
966 while ((ap = strsep(&s, ",")) != NULL) {
967 if (*ap == '\0')
969 else if (!strcmp(ap, "current"))
970 *flags |= TAB_CURRENT;
971 else
972 message("unknown tab flag: %s", ap);
976 static void
977 load_last_session(void)
979 const char *title;
980 char *nl, *line = NULL;
981 uint32_t flags;
982 size_t linesize = 0;
983 ssize_t linelen;
984 FILE *session;
985 struct tab *tab, *curr = NULL;
987 if ((session = fopen(session_file, "r")) == NULL) {
988 /* first time? */
989 new_tab("about:new", NULL, NULL);
990 switch_to_tab(new_tab("about:help", NULL, NULL));
991 return;
994 while ((linelen = getline(&line, &linesize, session)) != -1) {
995 if ((nl = strchr(line, '\n')) != NULL)
996 *nl = '\0';
997 parse_session_line(line, &title, &flags);
998 if ((tab = new_tab(line, NULL, NULL)) == NULL)
999 err(1, "new_tab");
1000 strlcpy(tab->buffer.page.title, title,
1001 sizeof(tab->buffer.page.title));
1002 if (flags & TAB_CURRENT)
1003 curr = tab;
1006 if (ferror(session))
1007 message("error reading %s: %s",
1008 session_file, strerror(errno));
1009 fclose(session);
1010 free(line);
1012 if (curr != NULL)
1013 switch_to_tab(curr);
1015 if (last_time_crashed())
1016 switch_to_tab(new_tab("about:crash", NULL, NULL));
1018 return;
1021 static pid_t
1022 start_child(enum telescope_process p, const char *argv0, int fd)
1024 const char *argv[4];
1025 int argc = 0;
1026 pid_t pid;
1028 switch (pid = fork()) {
1029 case -1:
1030 die();
1031 case 0:
1032 break;
1033 default:
1034 close(fd);
1035 return pid;
1038 if (dup2(fd, 3) == -1)
1039 err(1, "cannot setup imsg fd");
1041 argv[argc++] = argv0;
1042 switch (p) {
1043 case PROC_UI:
1044 errx(1, "Can't start ui process");
1045 case PROC_FS:
1046 argv[argc++] = "-Tf";
1047 break;
1048 case PROC_NET:
1049 argv[argc++] = "-Tn";
1050 break;
1053 argv[argc++] = NULL;
1054 execvp(argv0, (char *const *)argv);
1055 err(1, "execvp(%s)", argv0);
1058 static int
1059 ui_send_net(int type, uint32_t peerid, const void *data,
1060 uint16_t datalen)
1062 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1063 datalen);
1066 static int
1067 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1069 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1070 datalen);
1073 static void __attribute__((noreturn))
1074 usage(int r)
1076 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
1077 getprogname());
1078 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1079 exit(r);
1082 int
1083 main(int argc, char * const *argv)
1085 struct imsgev net_ibuf, fs_ibuf;
1086 int pipe2net[2], pipe2fs[2];
1087 int ch, configtest = 0, fail = 0;
1088 int has_url = 0;
1089 int proc = -1;
1090 int sessionfd;
1091 char path[PATH_MAX];
1092 const char *url = NEW_TAB_URL;
1093 const char *argv0;
1095 argv0 = argv[0];
1097 signal(SIGCHLD, SIG_IGN);
1098 signal(SIGPIPE, SIG_IGN);
1100 if (getenv("NO_COLOR") != NULL)
1101 enable_colors = 0;
1103 strlcpy(path, getenv("HOME"), sizeof(path));
1104 strlcat(path, "/.telescope/config", sizeof(path));
1106 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1107 switch (ch) {
1108 case 'C':
1109 exit(ui_print_colors());
1110 case 'c':
1111 fail = 1;
1112 strlcpy(path, optarg, sizeof(path));
1113 break;
1114 case 'n':
1115 configtest = 1;
1116 break;
1117 case 'h':
1118 usage(0);
1119 case 'T':
1120 switch (*optarg) {
1121 case 'f':
1122 proc = PROC_FS;
1123 break;
1124 case 'n':
1125 proc = PROC_NET;
1126 break;
1127 default:
1128 errx(1, "invalid process spec %c",
1129 *optarg);
1131 break;
1132 case 'v':
1133 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1134 exit(0);
1135 break;
1136 default:
1137 usage(1);
1141 argc -= optind;
1142 argv += optind;
1144 if (proc != -1) {
1145 if (argc > 0)
1146 usage(1);
1147 else if (proc == PROC_FS)
1148 return fs_main();
1149 else if (proc == PROC_NET)
1150 return net_main();
1151 else
1152 usage(1);
1155 if (argc != 0) {
1156 has_url = 1;
1157 url = argv[0];
1160 /* setup keys before reading the config */
1161 TAILQ_INIT(&global_map.m);
1162 global_map.unhandled_input = global_key_unbound;
1163 TAILQ_INIT(&minibuffer_map.m);
1165 config_init();
1166 parseconfig(path, fail);
1167 if (configtest){
1168 puts("config OK");
1169 exit(0);
1172 fs_init();
1173 if ((sessionfd = lock_session()) == -1)
1174 errx(1, "can't lock session, is another instance of "
1175 "telescope already running?");
1177 /* Start children. */
1178 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1179 err(1, "socketpair");
1180 start_child(PROC_FS, argv0, pipe2fs[1]);
1181 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1182 iev_fs = &fs_ibuf;
1183 iev_fs->handler = handle_dispatch_imsg;
1185 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1186 err(1, "socketpair");
1187 start_child(PROC_NET, argv0, pipe2net[1]);
1188 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1189 iev_net = &net_ibuf;
1190 iev_net->handler = handle_dispatch_imsg;
1192 setproctitle("ui");
1194 /* initialize tofu & load certificates */
1195 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1196 load_certs(&certs);
1198 event_init();
1200 /* Setup event handlers for pipes to fs/net */
1201 iev_fs->events = EV_READ;
1202 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1203 iev_fs->handler, iev_fs);
1204 event_add(&iev_fs->ev, NULL);
1206 iev_net->events = EV_READ;
1207 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1208 iev_net->handler, iev_net);
1209 event_add(&iev_net->ev, NULL);
1211 if (ui_init()) {
1212 load_last_session();
1213 if (has_url || TAILQ_EMPTY(&tabshead))
1214 new_tab(url, NULL, NULL);
1216 sandbox_ui_process();
1217 ui_main_loop();
1218 ui_end();
1221 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1222 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1223 imsg_flush(&iev_fs->ibuf);
1224 imsg_flush(&iev_net->ibuf);
1226 close(sessionfd);
1228 return 0;