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 static struct event autosaveev;
49 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
50 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
52 enum telescope_process {
53 PROC_UI,
54 PROC_FS,
55 PROC_NET,
56 };
58 #define CANNOT_FETCH 0
59 #define TOO_MUCH_REDIRECTS 1
60 #define MALFORMED_RESPONSE 2
61 #define UNKNOWN_TYPE_OR_CSET 3
62 #define UNKNOWN_PROTOCOL 4
64 /* XXX: keep in sync with telescope.c:/^normalize_code/ */
65 const char *err_pages[70] = {
66 [CANNOT_FETCH] = "# Couldn't load the page\n",
67 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
68 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
69 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
70 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
72 [10] = "# Input required\n",
73 [11] = "# Input required\n",
74 [40] = "# Temporary failure\n",
75 [41] = "# Server unavailable\n",
76 [42] = "# CGI error\n",
77 [43] = "# Proxy error\n",
78 [44] = "# Slow down\n",
79 [50] = "# Permanent failure\n",
80 [51] = "# Not found\n",
81 [52] = "# Gone\n",
82 [53] = "# Proxy request refused\n",
83 [59] = "# Bad request\n",
84 [60] = "# Client certificate required\n",
85 [61] = "# Certificate not authorised\n",
86 [62] = "# Certificate not valid\n"
87 };
89 static void die(void) __attribute__((__noreturn__));
90 static struct tab *tab_by_id(uint32_t);
91 static void handle_imsg_err(struct imsg*, size_t);
92 static void handle_imsg_check_cert(struct imsg*, size_t);
93 static void handle_check_cert_user_choice(int, struct tab *);
94 static void handle_maybe_save_new_cert(int, struct tab *);
95 static void handle_imsg_got_code(struct imsg*, size_t);
96 static void handle_imsg_got_meta(struct imsg*, size_t);
97 static void handle_maybe_save_page(int, struct tab *);
98 static void handle_save_page_path(const char *, struct tab *);
99 static void handle_imsg_file_opened(struct imsg*, size_t);
100 static void handle_imsg_buf(struct imsg*, size_t);
101 static void handle_imsg_eof(struct imsg*, size_t);
102 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
103 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
104 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
105 static void handle_dispatch_imsg(int, short, void*);
106 static int load_page_from_str(struct tab*, const char*);
107 static int load_about_url(struct tab*, const char*);
108 static int load_file_url(struct tab *, const char *);
109 static int load_finger_url(struct tab *, const char *);
110 static int load_gemini_url(struct tab*, const char*);
111 static int load_gopher_url(struct tab *, const char *);
112 static int load_via_proxy(struct tab *, const char *,
113 struct proxy *);
114 static int make_request(struct tab *, struct get_req *, int,
115 const char *);
116 static int make_fs_request(struct tab *, int, const char *);
117 static int do_load_url(struct tab*, const char *, const char *);
118 static void autosave_timer(int, short, void *);
119 static void parse_session_line(char *, const char **, uint32_t *);
120 static void load_last_session(void);
121 static pid_t start_child(enum telescope_process, const char *, int);
122 static int ui_send_net(int, uint32_t, const void *, uint16_t);
123 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
125 static struct proto {
126 const char *schema;
127 const char *port;
128 int (*loadfn)(struct tab*, const char*);
129 } protos[] = {
130 {"about", NULL, load_about_url},
131 {"file", NULL, load_file_url},
132 {"finger", "79", load_finger_url},
133 {"gemini", "1965", load_gemini_url},
134 {"gopher", "70", load_gopher_url},
135 {NULL, NULL, NULL},
136 };
138 static imsg_handlerfn *handlers[] = {
139 [IMSG_ERR] = handle_imsg_err,
140 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
141 [IMSG_GOT_CODE] = handle_imsg_got_code,
142 [IMSG_GOT_META] = handle_imsg_got_meta,
143 [IMSG_BUF] = handle_imsg_buf,
144 [IMSG_EOF] = handle_imsg_eof,
145 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
146 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
147 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
148 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
149 };
151 static struct ohash certs;
153 static void __attribute__((__noreturn__))
154 die(void)
156 abort(); /* TODO */
159 static struct tab *
160 tab_by_id(uint32_t id)
162 struct tab *t;
164 TAILQ_FOREACH(t, &tabshead, tabs) {
165 if (t->id == id)
166 return t;
169 return NULL;
172 static void
173 handle_imsg_err(struct imsg *imsg, size_t datalen)
175 struct tab *tab;
176 char *page;
178 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
179 return;
181 page = imsg->data;
182 page[datalen-1] = '\0';
184 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
185 tab->hist_cur->h, page) == -1)
186 die();
187 load_page_from_str(tab, page);
188 free(page);
191 static void
192 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
194 const char *hash, *host, *port;
195 int tofu_res;
196 struct tofu_entry *e;
197 struct tab *tab;
199 hash = imsg->data;
200 if (hash[datalen-1] != '\0')
201 abort();
203 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
204 return;
206 if (tab->proxy != NULL) {
207 host = tab->proxy->host;
208 port = tab->proxy->port;
209 } else {
210 host = tab->uri.host;
211 port = tab->uri.port;
214 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
215 /* TODO: an update in libressl/libretls changed
216 * significantly. Find a better approach at storing
217 * the certs! */
218 if (datalen > sizeof(e->hash))
219 abort();
221 tofu_res = 1; /* trust on first use */
222 if ((e = calloc(1, sizeof(*e))) == NULL)
223 abort();
224 strlcpy(e->domain, host, sizeof(e->domain));
225 if (*port != '\0' && strcmp(port, "1965")) {
226 strlcat(e->domain, ":", sizeof(e->domain));
227 strlcat(e->domain, port, sizeof(e->domain));
229 strlcpy(e->hash, hash, sizeof(e->hash));
230 tofu_add(&certs, e);
231 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
232 } else
233 tofu_res = !strcmp(hash, e->hash);
235 if (tofu_res) {
236 if (e->verified == -1)
237 tab->trust = TS_TEMP_TRUSTED;
238 else if (e->verified == 1)
239 tab->trust = TS_VERIFIED;
240 else
241 tab->trust = TS_TRUSTED;
243 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
244 &tofu_res, sizeof(tofu_res));
245 } else {
246 tab->trust = TS_UNTRUSTED;
247 load_page_from_str(tab, "# Certificate mismatch\n");
248 if ((tab->cert = strdup(hash)) == NULL)
249 die();
250 ui_yornp("Certificate mismatch. Proceed?",
251 handle_check_cert_user_choice, tab);
255 static void
256 handle_check_cert_user_choice(int accept, struct tab *tab)
258 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
259 sizeof(accept));
261 if (accept) {
262 /*
263 * trust the certificate for this session only. If
264 * the page results in a redirect while we're asking
265 * the user to save, we'll end up with an invalid
266 * tabid (one request == one tab id) and crash. It
267 * also makes sense to save it for the current session
268 * if the user accepted it.
269 */
270 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
272 ui_yornp("Save the new certificate?",
273 handle_maybe_save_new_cert, tab);
274 } else {
275 free(tab->cert);
276 tab->cert = NULL;
280 static void
281 handle_maybe_save_new_cert(int accept, struct tab *tab)
283 struct tofu_entry *e;
284 const char *host, *port;
286 if (tab->proxy != NULL) {
287 host = tab->proxy->host;
288 port = tab->proxy->port;
289 } else {
290 host = tab->uri.host;
291 port = tab->uri.port;
294 if (!accept)
295 goto end;
297 if ((e = calloc(1, sizeof(*e))) == NULL)
298 die();
300 strlcpy(e->domain, host, sizeof(e->domain));
301 if (*port != '\0' && strcmp(port, "1965")) {
302 strlcat(e->domain, ":", sizeof(e->domain));
303 strlcat(e->domain, port, sizeof(e->domain));
305 strlcpy(e->hash, tab->cert, sizeof(e->hash));
306 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
308 tofu_update(&certs, e);
310 tab->trust = TS_TRUSTED;
312 end:
313 free(tab->cert);
314 tab->cert = NULL;
317 static inline int
318 normalize_code(int n)
320 if (n < 20) {
321 if (n == 10 || n == 11)
322 return n;
323 return 10;
324 } else if (n < 30) {
325 return 20;
326 } else if (n < 40) {
327 if (n == 30 || n == 31)
328 return n;
329 return 30;
330 } else if (n < 50) {
331 if (n <= 44)
332 return n;
333 return 40;
334 } else if (n < 60) {
335 if (n <= 53 || n == 59)
336 return n;
337 return 50;
338 } else if (n < 70) {
339 if (n <= 62)
340 return n;
341 return 60;
342 } else
343 return MALFORMED_RESPONSE;
346 static void
347 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
349 struct tab *tab;
351 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
352 return;
354 if (sizeof(tab->code) != datalen)
355 die();
357 memcpy(&tab->code, imsg->data, sizeof(tab->code));
358 tab->code = normalize_code(tab->code);
359 if (tab->code != 30 && tab->code != 31)
360 tab->redirect_count = 0;
363 static void
364 handle_imsg_got_meta(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->meta) <= datalen)
372 die();
374 memcpy(tab->meta, imsg->data, datalen);
376 if (tab->code < 10) { /* internal errors */
377 load_page_from_str(tab, err_pages[tab->code]);
378 } else if (tab->code < 20) { /* 1x */
379 load_page_from_str(tab, err_pages[tab->code]);
380 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
381 } else if (tab->code == 20) {
382 if (setup_parser_for(tab)) {
383 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
384 } else {
385 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
386 ui_yornp("Can't display page, wanna save?",
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 if (dosave)
407 ui_read("Save to path", handle_save_page_path, tab);
408 else
409 stop_tab(tab);
412 static void
413 handle_save_page_path(const char *path, struct tab *tab)
415 if (path == NULL) {
416 stop_tab(tab);
417 return;
420 tab->path = strdup(path);
422 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
425 static void
426 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
428 struct tab *tab;
429 char *page;
430 const char *e;
431 int l;
433 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
434 if (imsg->fd != -1)
435 close(imsg->fd);
436 return;
439 if (imsg->fd == -1) {
440 stop_tab(tab);
442 e = imsg->data;
443 if (e[datalen-1] != '\0')
444 die();
445 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
446 tab->path, e);
447 if (l == -1)
448 die();
449 load_page_from_str(tab, page);
450 free(page);
451 } else {
452 tab->fd = imsg->fd;
453 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
457 static void
458 handle_imsg_buf(struct imsg *imsg, size_t datalen)
460 struct tab *tab;
461 int l;
462 char *page, buf[FMT_SCALED_STRSIZE] = {0};
464 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
465 return;
467 tab->bytes += datalen;
468 if (tab->fd == -1) {
469 if (!parser_parse(tab, imsg->data, datalen))
470 die();
471 } else {
472 write(tab->fd, imsg->data, datalen);
473 fmt_scaled(tab->bytes, buf);
474 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
475 tab->path,
476 buf);
477 if (l == -1)
478 die();
479 load_page_from_str(tab, page);
480 free(page);
483 ui_on_tab_refresh(tab);
486 static void
487 handle_imsg_eof(struct imsg *imsg, size_t datalen)
489 struct tab *tab;
490 int l;
491 char *page, buf[FMT_SCALED_STRSIZE] = {0};
493 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
494 return;
496 if (tab->fd == -1) {
497 if (!parser_free(tab))
498 die();
499 } else {
500 fmt_scaled(tab->bytes, buf);
501 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
502 tab->path,
503 buf);
504 if (l == -1)
505 die();
506 load_page_from_str(tab, page);
507 free(page);
509 close(tab->fd);
510 tab->fd = -1;
511 free(tab->path);
512 tab->path = NULL;
515 ui_on_tab_refresh(tab);
516 ui_on_tab_loaded(tab);
519 static void
520 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
522 int res;
524 if (datalen != sizeof(res))
525 die();
527 memcpy(&res, imsg->data, sizeof(res));
528 if (res == 0)
529 message("Added to bookmarks!");
530 else
531 message("Failed to add to bookmarks: %s",
532 strerror(res));
535 static void
536 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
538 int res;
540 if (datalen != sizeof(res))
541 die();
542 memcpy(&res, imsg->data, datalen);
543 if (res != 0)
544 message("Failed to save the cert for: %s",
545 strerror(res));
548 static void
549 handle_imsg_update_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)
557 message("Failed to update the certificate");
560 static void
561 handle_dispatch_imsg(int fd, short ev, void *d)
563 struct imsgev *iev = d;
565 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
566 err(1, "connection closed");
569 static int
570 load_page_from_str(struct tab *tab, const char *page)
572 erase_buffer(&tab->buffer);
573 parser_init(tab, gemtext_initparser);
574 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
575 die();
576 if (!tab->buffer.page.free(&tab->buffer.page))
577 die();
578 ui_on_tab_refresh(tab);
579 ui_on_tab_loaded(tab);
580 return 0;
583 static int
584 load_about_url(struct tab *tab, const char *url)
586 tab->trust = TS_UNKNOWN;
587 parser_init(tab, gemtext_initparser);
588 return make_fs_request(tab, IMSG_GET, url);
591 static int
592 load_file_url(struct tab *tab, const char *url)
594 tab->trust = TS_UNKNOWN;
595 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
598 static int
599 load_finger_url(struct tab *tab, const char *url)
601 struct get_req req;
602 size_t len;
603 char *at;
605 memset(&req, 0, sizeof(req));
606 strlcpy(req.port, tab->uri.port, sizeof(req.port));
608 /*
609 * Sometimes the finger url have the user as path component
610 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
611 * userinfo (e.g. finger://cobradile@finger.farm).
612 */
613 if ((at = strchr(tab->uri.host, '@')) != NULL) {
614 len = at - tab->uri.host;
615 memcpy(req.req, tab->uri.host, len);
617 if (len >= sizeof(req.req))
618 die();
619 req.req[len] = '\0';
621 strlcpy(req.host, at+1, sizeof(req.host));
622 } else {
623 strlcpy(req.host, tab->uri.host, sizeof(req.host));
625 /* +1 to skip the initial `/' */
626 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
628 strlcat(req.req, "\r\n", sizeof(req.req));
630 parser_init(tab, textplain_initparser);
631 return make_request(tab, &req, PROTO_FINGER, NULL);
634 static int
635 load_gemini_url(struct tab *tab, const char *url)
637 struct get_req req;
639 memset(&req, 0, sizeof(req));
640 strlcpy(req.host, tab->uri.host, sizeof(req.host));
641 strlcpy(req.port, tab->uri.port, sizeof(req.host));
643 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
646 static inline const char *
647 gopher_skip_selector(const char *path, int *ret_type)
649 *ret_type = 0;
651 if (!strcmp(path, "/") || *path == '\0') {
652 *ret_type = '1';
653 return path;
656 if (*path != '/')
657 return path;
658 path++;
660 switch (*ret_type = *path) {
661 case '0':
662 case '1':
663 case '7':
664 break;
666 default:
667 *ret_type = 0;
668 path -= 1;
669 return path;
672 path++;
673 if (*path == '/')
674 path++;
676 return path;
679 static int
680 load_gopher_url(struct tab *tab, const char *url)
682 struct get_req req;
683 int type;
684 const char *path;
686 memset(&req, 0, sizeof(req));
687 strlcpy(req.host, tab->uri.host, sizeof(req.host));
688 strlcpy(req.port, tab->uri.port, sizeof(req.host));
690 path = gopher_skip_selector(tab->uri.path, &type);
691 switch (type) {
692 case '0':
693 parser_init(tab, textplain_initparser);
694 break;
695 case '1':
696 parser_init(tab, gophermap_initparser);
697 break;
698 case '7':
699 ui_require_input(tab, 0, PROTO_GOPHER);
700 return load_page_from_str(tab, err_pages[10]);
701 default:
702 return load_page_from_str(tab, "Unknown gopher selector");
705 strlcpy(req.req, path, sizeof(req.req));
706 if (*tab->uri.query != '\0') {
707 strlcat(req.req, "?", sizeof(req.req));
708 strlcat(req.req, tab->uri.query, sizeof(req.req));
710 strlcat(req.req, "\r\n", sizeof(req.req));
712 return make_request(tab, &req, PROTO_GOPHER, NULL);
715 static int
716 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
718 struct get_req req;
720 memset(&req, 0, sizeof(req));
721 strlcpy(req.host, p->host, sizeof(req.host));
722 strlcpy(req.port, p->port, sizeof(req.host));
724 tab->proxy = p;
726 return make_request(tab, &req, p->proto, tab->hist_cur->h);
729 static int
730 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
732 stop_tab(tab);
733 tab->id = tab_new_id();
734 req->proto = proto;
736 if (r != NULL) {
737 strlcpy(req->req, r, sizeof(req->req));
738 strlcat(req->req, "\r\n", sizeof(req->req));
741 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
743 /*
744 * So the various load_*_url can `return make_request` and
745 * do_load_url is happy.
746 */
747 return 1;
750 static int
751 make_fs_request(struct tab *tab, int type, const char *r)
753 stop_tab(tab);
754 tab->id = tab_new_id();
756 ui_send_fs(type, tab->id, r, strlen(r)+1);
758 /*
759 * So load_{about,file}_url can `return make_fs_request` and
760 * do_load_url is happy.
761 */
762 return 1;
765 void
766 gopher_send_search_req(struct tab *tab, const char *text)
768 struct get_req req;
770 start_loading_anim(tab);
772 memset(&req, 0, sizeof(req));
773 strlcpy(req.host, tab->uri.host, sizeof(req.host));
774 strlcpy(req.port, tab->uri.port, sizeof(req.host));
776 /* +2 to skip /7 */
777 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
778 if (*tab->uri.query != '\0') {
779 strlcat(req.req, "?", sizeof(req.req));
780 strlcat(req.req, tab->uri.query, sizeof(req.req));
783 strlcat(req.req, "\t", sizeof(req.req));
784 strlcat(req.req, text, sizeof(req.req));
785 strlcat(req.req, "\r\n", sizeof(req.req));
787 erase_buffer(&tab->buffer);
788 parser_init(tab, gophermap_initparser);
790 make_request(tab, &req, PROTO_GOPHER, NULL);
793 /*
794 * Effectively load the given url in the given tab. Return 1 when
795 * loading the page asynchronously, and thus when an erase_buffer can
796 * be done right after this function return, or 0 when loading the
797 * page synchronously. In this last case, erase_buffer *MUST* be
798 * called by the handling function (such as load_page_from_str).
799 */
800 static int
801 do_load_url(struct tab *tab, const char *url, const char *base)
803 struct phos_uri uri;
804 struct proto *p;
805 struct proxy *proxy;
806 char *t;
808 tab->proxy = NULL;
810 if (tab->fd != -1) {
811 close(tab->fd);
812 tab->fd = -1;
813 free(tab->path);
814 tab->path = NULL;
817 tab->trust = TS_UNKNOWN;
819 if (base == NULL)
820 memcpy(&uri, &tab->uri, sizeof(tab->uri));
821 else
822 phos_parse_absolute_uri(base, &uri);
824 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
825 if (asprintf(&t, "#error loading %s\n>%s\n",
826 url, "Can't parse the URI") == -1)
827 die();
828 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
829 load_page_from_str(tab, t);
830 free(t);
831 return 0;
834 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
835 sizeof(tab->hist_cur->h));
837 for (p = protos; p->schema != NULL; ++p) {
838 if (!strcmp(tab->uri.scheme, p->schema)) {
839 /* patch the port */
840 if (*tab->uri.port == '\0' && p->port != NULL)
841 strlcpy(tab->uri.port, p->port,
842 sizeof(tab->uri.port));
844 return p->loadfn(tab, url);
848 TAILQ_FOREACH(proxy, &proxies, proxies) {
849 if (!strcmp(tab->uri.scheme, proxy->match_proto))
850 return load_via_proxy(tab, url, proxy);
853 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
856 /*
857 * Load url in tab. If tab is marked as lazy, only prepare the url
858 * but don't load it. If tab is lazy and a url was already prepared,
859 * do load it!
860 */
861 void
862 load_url(struct tab *tab, const char *url, const char *base, int nohist)
864 int lazy;
866 lazy = tab->flags & TAB_LAZY;
868 if (lazy && tab->hist_cur != NULL) {
869 lazy = 0;
870 tab->flags &= ~TAB_LAZY;
873 /* can't have both nohist and lazy at the same time. */
874 if (nohist && lazy)
875 nohist = 0;
877 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
878 if (tab->hist_cur != NULL)
879 hist_clear_forward(&tab->hist,
880 TAILQ_NEXT(tab->hist_cur, entries));
882 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
883 event_loopbreak();
884 return;
887 strlcpy(tab->buffer.page.title, url,
888 sizeof(tab->buffer.page.title));
889 hist_push(&tab->hist, tab->hist_cur);
891 if (lazy)
892 strlcpy(tab->hist_cur->h, url,
893 sizeof(tab->hist_cur->h));
896 if (!lazy && do_load_url(tab, url, base))
897 erase_buffer(&tab->buffer);
900 int
901 load_previous_page(struct tab *tab)
903 struct hist *h;
905 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
906 return 0;
907 tab->hist_cur = h;
908 do_load_url(tab, h->h, NULL);
909 return 1;
912 int
913 load_next_page(struct tab *tab)
915 struct hist *h;
917 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
918 return 0;
919 tab->hist_cur = h;
920 do_load_url(tab, h->h, NULL);
921 return 1;
924 /*
925 * Free every resource linked to the tab, including the tab itself.
926 * Removes the tab from the tablist, but doesn't update the
927 * current_tab though.
928 */
929 void
930 free_tab(struct tab *tab)
932 stop_tab(tab);
934 autosave_hook();
936 if (evtimer_pending(&tab->loadingev, NULL))
937 evtimer_del(&tab->loadingev);
939 TAILQ_REMOVE(&tabshead, tab, tabs);
940 free(tab);
943 void
944 stop_tab(struct tab *tab)
946 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
948 if (tab->fd != -1) {
949 close(tab->fd);
950 tab->fd = -1;
951 free(tab->path);
952 tab->path = NULL;
953 load_page_from_str(tab, "Stopped.\n");
957 void
958 add_to_bookmarks(const char *str)
960 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
961 str, strlen(str)+1);
964 void
965 save_session(void)
967 struct tab *tab;
968 char *t;
969 int flags;
971 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
973 TAILQ_FOREACH(tab, &tabshead, tabs) {
974 flags = tab->flags;
975 if (tab == current_tab)
976 flags |= TAB_CURRENT;
978 t = tab->hist_cur->h;
979 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
981 t = tab->buffer.page.title;
982 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
985 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
988 static void
989 autosave_timer(int fd, short event, void *data)
991 save_session();
994 /*
995 * Function to be called in "interesting" places where we may want to
996 * schedule an autosave (like on new tab or before loading an url.)
997 */
998 void
999 autosave_hook(void)
1001 struct timeval tv;
1003 if (autosave <= 0)
1004 return;
1006 if (!evtimer_pending(&autosaveev, NULL)) {
1007 tv.tv_sec = autosave;
1008 tv.tv_usec = 0;
1010 evtimer_add(&autosaveev, &tv);
1015 * Parse a line of the session file. The format is:
1017 * URL [flags,...] [title]\n
1019 static void
1020 parse_session_line(char *line, const char **title, uint32_t *flags)
1022 char *s, *t, *ap;
1024 *title = "";
1025 *flags = 0;
1026 if ((s = strchr(line, ' ')) == NULL)
1027 return;
1029 *s++ = '\0';
1031 if ((t = strchr(s, ' ')) != NULL) {
1032 *t++ = '\0';
1033 *title = t;
1036 while ((ap = strsep(&s, ",")) != NULL) {
1037 if (*ap == '\0')
1039 else if (!strcmp(ap, "current"))
1040 *flags |= TAB_CURRENT;
1041 else
1042 message("unknown tab flag: %s", ap);
1046 static void
1047 load_last_session(void)
1049 const char *title;
1050 char *nl, *line = NULL;
1051 uint32_t flags;
1052 size_t linesize = 0;
1053 ssize_t linelen;
1054 FILE *session;
1055 struct tab *tab, *curr = NULL;
1057 if ((session = fopen(session_file, "r")) == NULL) {
1058 /* first time? */
1059 new_tab("about:new", NULL, NULL);
1060 switch_to_tab(new_tab("about:help", NULL, NULL));
1061 return;
1064 while ((linelen = getline(&line, &linesize, session)) != -1) {
1065 if ((nl = strchr(line, '\n')) != NULL)
1066 *nl = '\0';
1067 parse_session_line(line, &title, &flags);
1068 if ((tab = new_tab(line, NULL, NULL)) == NULL)
1069 err(1, "new_tab");
1070 strlcpy(tab->buffer.page.title, title,
1071 sizeof(tab->buffer.page.title));
1072 if (flags & TAB_CURRENT)
1073 curr = tab;
1076 if (ferror(session))
1077 message("error reading %s: %s",
1078 session_file, strerror(errno));
1079 fclose(session);
1080 free(line);
1082 if (curr != NULL)
1083 switch_to_tab(curr);
1085 if (last_time_crashed())
1086 switch_to_tab(new_tab("about:crash", NULL, NULL));
1088 return;
1091 static pid_t
1092 start_child(enum telescope_process p, const char *argv0, int fd)
1094 const char *argv[4];
1095 int argc = 0;
1096 pid_t pid;
1098 switch (pid = fork()) {
1099 case -1:
1100 die();
1101 case 0:
1102 break;
1103 default:
1104 close(fd);
1105 return pid;
1108 if (dup2(fd, 3) == -1)
1109 err(1, "cannot setup imsg fd");
1111 argv[argc++] = argv0;
1112 switch (p) {
1113 case PROC_UI:
1114 errx(1, "Can't start ui process");
1115 case PROC_FS:
1116 argv[argc++] = "-Tf";
1117 break;
1118 case PROC_NET:
1119 argv[argc++] = "-Tn";
1120 break;
1123 argv[argc++] = NULL;
1124 execvp(argv0, (char *const *)argv);
1125 err(1, "execvp(%s)", argv0);
1128 static int
1129 ui_send_net(int type, uint32_t peerid, const void *data,
1130 uint16_t datalen)
1132 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1133 datalen);
1136 static int
1137 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1139 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1140 datalen);
1143 static void __attribute__((noreturn))
1144 usage(int r)
1146 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
1147 getprogname());
1148 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1149 exit(r);
1152 int
1153 main(int argc, char * const *argv)
1155 struct imsgev net_ibuf, fs_ibuf;
1156 int pipe2net[2], pipe2fs[2];
1157 int ch, configtest = 0, fail = 0;
1158 int has_url = 0;
1159 int proc = -1;
1160 int sessionfd;
1161 char path[PATH_MAX];
1162 const char *url = NEW_TAB_URL;
1163 const char *argv0;
1165 argv0 = argv[0];
1167 signal(SIGCHLD, SIG_IGN);
1168 signal(SIGPIPE, SIG_IGN);
1170 if (getenv("NO_COLOR") != NULL)
1171 enable_colors = 0;
1173 strlcpy(path, getenv("HOME"), sizeof(path));
1174 strlcat(path, "/.telescope/config", sizeof(path));
1176 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1177 switch (ch) {
1178 case 'C':
1179 exit(ui_print_colors());
1180 case 'c':
1181 fail = 1;
1182 strlcpy(path, optarg, sizeof(path));
1183 break;
1184 case 'n':
1185 configtest = 1;
1186 break;
1187 case 'h':
1188 usage(0);
1189 case 'T':
1190 switch (*optarg) {
1191 case 'f':
1192 proc = PROC_FS;
1193 break;
1194 case 'n':
1195 proc = PROC_NET;
1196 break;
1197 default:
1198 errx(1, "invalid process spec %c",
1199 *optarg);
1201 break;
1202 case 'v':
1203 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1204 exit(0);
1205 break;
1206 default:
1207 usage(1);
1211 argc -= optind;
1212 argv += optind;
1214 if (proc != -1) {
1215 if (argc > 0)
1216 usage(1);
1217 else if (proc == PROC_FS)
1218 return fs_main();
1219 else if (proc == PROC_NET)
1220 return net_main();
1221 else
1222 usage(1);
1225 if (argc != 0) {
1226 has_url = 1;
1227 url = argv[0];
1230 /* setup keys before reading the config */
1231 TAILQ_INIT(&global_map.m);
1232 global_map.unhandled_input = global_key_unbound;
1233 TAILQ_INIT(&minibuffer_map.m);
1235 config_init();
1236 parseconfig(path, fail);
1237 if (configtest){
1238 puts("config OK");
1239 exit(0);
1242 fs_init();
1243 if ((sessionfd = lock_session()) == -1)
1244 errx(1, "can't lock session, is another instance of "
1245 "telescope already running?");
1247 /* Start children. */
1248 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1249 err(1, "socketpair");
1250 start_child(PROC_FS, argv0, pipe2fs[1]);
1251 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1252 iev_fs = &fs_ibuf;
1253 iev_fs->handler = handle_dispatch_imsg;
1255 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1256 err(1, "socketpair");
1257 start_child(PROC_NET, argv0, pipe2net[1]);
1258 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1259 iev_net = &net_ibuf;
1260 iev_net->handler = handle_dispatch_imsg;
1262 setproctitle("ui");
1264 /* initialize tofu & load certificates */
1265 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1266 load_certs(&certs);
1268 event_init();
1270 /* Setup event handler for the autosave */
1271 evtimer_set(&autosaveev, autosave_timer, NULL);
1273 /* Setup event handlers for pipes to fs/net */
1274 iev_fs->events = EV_READ;
1275 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1276 iev_fs->handler, iev_fs);
1277 event_add(&iev_fs->ev, NULL);
1279 iev_net->events = EV_READ;
1280 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1281 iev_net->handler, iev_net);
1282 event_add(&iev_net->ev, NULL);
1284 if (ui_init()) {
1285 load_last_session();
1286 if (has_url || TAILQ_EMPTY(&tabshead))
1287 new_tab(url, NULL, NULL);
1289 sandbox_ui_process();
1290 ui_main_loop();
1291 ui_end();
1294 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1295 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1296 imsg_flush(&iev_fs->ibuf);
1297 imsg_flush(&iev_net->ibuf);
1299 close(sessionfd);
1301 return 0;