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 /*
46 * Used to know when we're finished loading.
47 */
48 static int operating;
50 static struct imsgev *iev_fs, *iev_net;
52 static struct event autosaveev;
54 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
55 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
57 enum telescope_process {
58 PROC_UI,
59 PROC_FS,
60 PROC_NET,
61 };
63 #define CANNOT_FETCH 0
64 #define TOO_MUCH_REDIRECTS 1
65 #define MALFORMED_RESPONSE 2
66 #define UNKNOWN_TYPE_OR_CSET 3
67 #define UNKNOWN_PROTOCOL 4
69 /* XXX: keep in sync with telescope.c:/^normalize_code/ */
70 const char *err_pages[70] = {
71 [CANNOT_FETCH] = "# Couldn't load the page\n",
72 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
73 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
74 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
75 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
77 [10] = "# Input required\n",
78 [11] = "# Input required\n",
79 [40] = "# Temporary failure\n",
80 [41] = "# Server unavailable\n",
81 [42] = "# CGI error\n",
82 [43] = "# Proxy error\n",
83 [44] = "# Slow down\n",
84 [50] = "# Permanent failure\n",
85 [51] = "# Not found\n",
86 [52] = "# Gone\n",
87 [53] = "# Proxy request refused\n",
88 [59] = "# Bad request\n",
89 [60] = "# Client certificate required\n",
90 [61] = "# Certificate not authorised\n",
91 [62] = "# Certificate not valid\n"
92 };
94 static void die(void) __attribute__((__noreturn__));
95 static struct tab *tab_by_id(uint32_t);
96 static void handle_imsg_err(struct imsg*, size_t);
97 static void handle_imsg_check_cert(struct imsg*, size_t);
98 static void handle_check_cert_user_choice(int, struct tab *);
99 static void handle_maybe_save_new_cert(int, struct tab *);
100 static void handle_imsg_got_code(struct imsg*, size_t);
101 static void handle_imsg_got_meta(struct imsg*, size_t);
102 static void handle_maybe_save_page(int, struct tab *);
103 static void handle_save_page_path(const char *, struct tab *);
104 static void handle_imsg_file_opened(struct imsg*, size_t);
105 static void handle_imsg_buf(struct imsg*, size_t);
106 static void handle_imsg_eof(struct imsg*, size_t);
107 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
108 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
109 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
110 static void handle_dispatch_imsg(int, short, void*);
111 static int load_page_from_str(struct tab*, const char*);
112 static int load_about_url(struct tab*, const char*);
113 static int load_file_url(struct tab *, const char *);
114 static int load_finger_url(struct tab *, const char *);
115 static int load_gemini_url(struct tab*, const char*);
116 static int load_gopher_url(struct tab *, const char *);
117 static int load_via_proxy(struct tab *, const char *,
118 struct proxy *);
119 static int make_request(struct tab *, struct get_req *, int,
120 const char *);
121 static int make_fs_request(struct tab *, int, const char *);
122 static int do_load_url(struct tab*, const char *, const char *);
123 static void autosave_timer(int, short, void *);
124 static void parse_session_line(char *, const char **, uint32_t *);
125 static void load_last_session(void);
126 static pid_t start_child(enum telescope_process, const char *, int);
127 static int ui_send_net(int, uint32_t, const void *, uint16_t);
128 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
130 static struct proto {
131 const char *schema;
132 const char *port;
133 int (*loadfn)(struct tab*, const char*);
134 } protos[] = {
135 {"about", NULL, load_about_url},
136 {"file", NULL, load_file_url},
137 {"finger", "79", load_finger_url},
138 {"gemini", "1965", load_gemini_url},
139 {"gopher", "70", load_gopher_url},
140 {NULL, NULL, NULL},
141 };
143 static imsg_handlerfn *handlers[] = {
144 [IMSG_ERR] = handle_imsg_err,
145 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
146 [IMSG_GOT_CODE] = handle_imsg_got_code,
147 [IMSG_GOT_META] = handle_imsg_got_meta,
148 [IMSG_BUF] = handle_imsg_buf,
149 [IMSG_EOF] = handle_imsg_eof,
150 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
151 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
152 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
153 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
154 };
156 static struct ohash certs;
158 static void __attribute__((__noreturn__))
159 die(void)
161 abort(); /* TODO */
164 static struct tab *
165 tab_by_id(uint32_t id)
167 struct tab *t;
169 TAILQ_FOREACH(t, &tabshead, tabs) {
170 if (t->id == id)
171 return t;
174 return NULL;
177 static void
178 handle_imsg_err(struct imsg *imsg, size_t datalen)
180 struct tab *tab;
181 char *page;
183 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
184 return;
186 page = imsg->data;
187 page[datalen-1] = '\0';
189 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
190 tab->hist_cur->h, page) == -1)
191 die();
192 load_page_from_str(tab, page);
193 free(page);
196 static void
197 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
199 const char *hash, *host, *port;
200 int tofu_res;
201 struct tofu_entry *e;
202 struct tab *tab;
204 hash = imsg->data;
205 if (hash[datalen-1] != '\0')
206 abort();
208 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
209 return;
211 if (tab->proxy != NULL) {
212 host = tab->proxy->host;
213 port = tab->proxy->port;
214 } else {
215 host = tab->uri.host;
216 port = tab->uri.port;
219 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
220 /* TODO: an update in libressl/libretls changed
221 * significantly. Find a better approach at storing
222 * the certs! */
223 if (datalen > sizeof(e->hash))
224 abort();
226 tofu_res = 1; /* trust on first use */
227 if ((e = calloc(1, sizeof(*e))) == NULL)
228 abort();
229 strlcpy(e->domain, host, sizeof(e->domain));
230 if (*port != '\0' && strcmp(port, "1965")) {
231 strlcat(e->domain, ":", sizeof(e->domain));
232 strlcat(e->domain, port, sizeof(e->domain));
234 strlcpy(e->hash, hash, sizeof(e->hash));
235 tofu_add(&certs, e);
236 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
237 } else
238 tofu_res = !strcmp(hash, e->hash);
240 if (tofu_res) {
241 if (e->verified == -1)
242 tab->trust = TS_TEMP_TRUSTED;
243 else if (e->verified == 1)
244 tab->trust = TS_VERIFIED;
245 else
246 tab->trust = TS_TRUSTED;
248 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
249 &tofu_res, sizeof(tofu_res));
250 } else {
251 tab->trust = TS_UNTRUSTED;
252 load_page_from_str(tab, "# Certificate mismatch\n");
253 if ((tab->cert = strdup(hash)) == NULL)
254 die();
255 ui_yornp("Certificate mismatch. Proceed?",
256 handle_check_cert_user_choice, tab);
260 static void
261 handle_check_cert_user_choice(int accept, struct tab *tab)
263 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
264 sizeof(accept));
266 if (accept) {
267 /*
268 * trust the certificate for this session only. If
269 * the page results in a redirect while we're asking
270 * the user to save, we'll end up with an invalid
271 * tabid (one request == one tab id) and crash. It
272 * also makes sense to save it for the current session
273 * if the user accepted it.
274 */
275 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
277 ui_yornp("Save the new certificate?",
278 handle_maybe_save_new_cert, tab);
279 } else {
280 free(tab->cert);
281 tab->cert = NULL;
285 static void
286 handle_maybe_save_new_cert(int accept, struct tab *tab)
288 struct tofu_entry *e;
289 const char *host, *port;
291 if (tab->proxy != NULL) {
292 host = tab->proxy->host;
293 port = tab->proxy->port;
294 } else {
295 host = tab->uri.host;
296 port = tab->uri.port;
299 if (!accept)
300 goto end;
302 if ((e = calloc(1, sizeof(*e))) == NULL)
303 die();
305 strlcpy(e->domain, host, sizeof(e->domain));
306 if (*port != '\0' && strcmp(port, "1965")) {
307 strlcat(e->domain, ":", sizeof(e->domain));
308 strlcat(e->domain, port, sizeof(e->domain));
310 strlcpy(e->hash, tab->cert, sizeof(e->hash));
311 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
313 tofu_update(&certs, e);
315 tab->trust = TS_TRUSTED;
317 end:
318 free(tab->cert);
319 tab->cert = NULL;
322 static inline int
323 normalize_code(int n)
325 if (n < 20) {
326 if (n == 10 || n == 11)
327 return n;
328 return 10;
329 } else if (n < 30) {
330 return 20;
331 } else if (n < 40) {
332 if (n == 30 || n == 31)
333 return n;
334 return 30;
335 } else if (n < 50) {
336 if (n <= 44)
337 return n;
338 return 40;
339 } else if (n < 60) {
340 if (n <= 53 || n == 59)
341 return n;
342 return 50;
343 } else if (n < 70) {
344 if (n <= 62)
345 return n;
346 return 60;
347 } else
348 return MALFORMED_RESPONSE;
351 static void
352 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
354 struct tab *tab;
356 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
357 return;
359 if (sizeof(tab->code) != datalen)
360 die();
362 memcpy(&tab->code, imsg->data, sizeof(tab->code));
363 tab->code = normalize_code(tab->code);
364 if (tab->code != 30 && tab->code != 31)
365 tab->redirect_count = 0;
368 static void
369 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
371 struct tab *tab;
373 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
374 return;
376 if (sizeof(tab->meta) <= datalen)
377 die();
379 memcpy(tab->meta, imsg->data, datalen);
381 if (tab->code < 10) { /* internal errors */
382 load_page_from_str(tab, err_pages[tab->code]);
383 } else if (tab->code < 20) { /* 1x */
384 load_page_from_str(tab, err_pages[tab->code]);
385 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
386 } else if (tab->code == 20) {
387 if (setup_parser_for(tab)) {
388 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
389 } else {
390 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
391 ui_yornp("Can't display page, wanna save?",
392 handle_maybe_save_page, tab);
394 } else if (tab->code < 40) { /* 3x */
395 tab->redirect_count++;
397 /* TODO: make customizable? */
398 if (tab->redirect_count > 5) {
399 load_page_from_str(tab,
400 err_pages[TOO_MUCH_REDIRECTS]);
401 } else
402 do_load_url(tab, tab->meta, NULL);
403 } else { /* 4x, 5x & 6x */
404 load_page_from_str(tab, err_pages[tab->code]);
408 static void
409 handle_maybe_save_page(int dosave, struct tab *tab)
411 if (dosave)
412 ui_read("Save to path", handle_save_page_path, tab);
413 else
414 stop_tab(tab);
417 static void
418 handle_save_page_path(const char *path, struct tab *tab)
420 if (path == NULL) {
421 stop_tab(tab);
422 return;
425 tab->path = strdup(path);
427 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
430 static void
431 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
433 struct tab *tab;
434 char *page;
435 const char *e;
436 int l;
438 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
439 if (imsg->fd != -1)
440 close(imsg->fd);
441 return;
444 if (imsg->fd == -1) {
445 stop_tab(tab);
447 e = imsg->data;
448 if (e[datalen-1] != '\0')
449 die();
450 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
451 tab->path, e);
452 if (l == -1)
453 die();
454 load_page_from_str(tab, page);
455 free(page);
456 } else {
457 tab->fd = imsg->fd;
458 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
462 static void
463 handle_imsg_buf(struct imsg *imsg, size_t datalen)
465 struct tab *tab;
466 int l;
467 char *page, buf[FMT_SCALED_STRSIZE] = {0};
469 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
470 return;
472 tab->bytes += datalen;
473 if (tab->fd == -1) {
474 if (!parser_parse(tab, imsg->data, datalen))
475 die();
476 } else {
477 write(tab->fd, imsg->data, datalen);
478 fmt_scaled(tab->bytes, buf);
479 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
480 tab->path,
481 buf);
482 if (l == -1)
483 die();
484 load_page_from_str(tab, page);
485 free(page);
488 ui_on_tab_refresh(tab);
491 static void
492 handle_imsg_eof(struct imsg *imsg, size_t datalen)
494 struct tab *tab;
495 int l;
496 char *page, buf[FMT_SCALED_STRSIZE] = {0};
498 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
499 return;
501 if (tab->fd == -1) {
502 if (!parser_free(tab))
503 die();
504 } else {
505 fmt_scaled(tab->bytes, buf);
506 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
507 tab->path,
508 buf);
509 if (l == -1)
510 die();
511 load_page_from_str(tab, page);
512 free(page);
514 close(tab->fd);
515 tab->fd = -1;
516 free(tab->path);
517 tab->path = NULL;
520 ui_on_tab_refresh(tab);
521 ui_on_tab_loaded(tab);
524 static void
525 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
527 int res;
529 if (datalen != sizeof(res))
530 die();
532 memcpy(&res, imsg->data, sizeof(res));
533 if (res == 0)
534 message("Added to bookmarks!");
535 else
536 message("Failed to add to bookmarks: %s",
537 strerror(res));
540 static void
541 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
543 int res;
545 if (datalen != sizeof(res))
546 die();
547 memcpy(&res, imsg->data, datalen);
548 if (res != 0)
549 message("Failed to save the cert for: %s",
550 strerror(res));
553 static void
554 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
556 int res;
558 if (datalen != sizeof(res))
559 die();
560 memcpy(&res, imsg->data, datalen);
561 if (!res)
562 message("Failed to update the certificate");
565 static void
566 handle_dispatch_imsg(int fd, short ev, void *d)
568 struct imsgev *iev = d;
570 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
571 err(1, "connection closed");
574 static int
575 load_page_from_str(struct tab *tab, const char *page)
577 erase_buffer(&tab->buffer);
578 parser_init(tab, gemtext_initparser);
579 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
580 die();
581 if (!tab->buffer.page.free(&tab->buffer.page))
582 die();
583 ui_on_tab_refresh(tab);
584 ui_on_tab_loaded(tab);
585 return 0;
588 static int
589 load_about_url(struct tab *tab, const char *url)
591 tab->trust = TS_UNKNOWN;
592 parser_init(tab, gemtext_initparser);
593 return make_fs_request(tab, IMSG_GET, url);
596 static int
597 load_file_url(struct tab *tab, const char *url)
599 tab->trust = TS_UNKNOWN;
600 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
603 static int
604 load_finger_url(struct tab *tab, const char *url)
606 struct get_req req;
607 size_t len;
608 char *at;
610 memset(&req, 0, sizeof(req));
611 strlcpy(req.port, tab->uri.port, sizeof(req.port));
613 /*
614 * Sometimes the finger url have the user as path component
615 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
616 * userinfo (e.g. finger://cobradile@finger.farm).
617 */
618 if ((at = strchr(tab->uri.host, '@')) != NULL) {
619 len = at - tab->uri.host;
620 memcpy(req.req, tab->uri.host, len);
622 if (len >= sizeof(req.req))
623 die();
624 req.req[len] = '\0';
626 strlcpy(req.host, at+1, sizeof(req.host));
627 } else {
628 strlcpy(req.host, tab->uri.host, sizeof(req.host));
630 /* +1 to skip the initial `/' */
631 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
633 strlcat(req.req, "\r\n", sizeof(req.req));
635 parser_init(tab, textplain_initparser);
636 return make_request(tab, &req, PROTO_FINGER, NULL);
639 static int
640 load_gemini_url(struct tab *tab, const char *url)
642 struct get_req req;
644 memset(&req, 0, sizeof(req));
645 strlcpy(req.host, tab->uri.host, sizeof(req.host));
646 strlcpy(req.port, tab->uri.port, sizeof(req.host));
648 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
651 static inline const char *
652 gopher_skip_selector(const char *path, int *ret_type)
654 *ret_type = 0;
656 if (!strcmp(path, "/") || *path == '\0') {
657 *ret_type = '1';
658 return path;
661 if (*path != '/')
662 return path;
663 path++;
665 switch (*ret_type = *path) {
666 case '0':
667 case '1':
668 case '7':
669 break;
671 default:
672 *ret_type = 0;
673 path -= 1;
674 return path;
677 path++;
678 if (*path == '/')
679 path++;
681 return path;
684 static int
685 load_gopher_url(struct tab *tab, const char *url)
687 struct get_req req;
688 int type;
689 const char *path;
691 memset(&req, 0, sizeof(req));
692 strlcpy(req.host, tab->uri.host, sizeof(req.host));
693 strlcpy(req.port, tab->uri.port, sizeof(req.host));
695 path = gopher_skip_selector(tab->uri.path, &type);
696 switch (type) {
697 case '0':
698 parser_init(tab, textplain_initparser);
699 break;
700 case '1':
701 parser_init(tab, gophermap_initparser);
702 break;
703 case '7':
704 ui_require_input(tab, 0, PROTO_GOPHER);
705 return load_page_from_str(tab, err_pages[10]);
706 default:
707 return load_page_from_str(tab, "Unknown gopher selector");
710 strlcpy(req.req, path, sizeof(req.req));
711 if (*tab->uri.query != '\0') {
712 strlcat(req.req, "?", sizeof(req.req));
713 strlcat(req.req, tab->uri.query, sizeof(req.req));
715 strlcat(req.req, "\r\n", sizeof(req.req));
717 return make_request(tab, &req, PROTO_GOPHER, NULL);
720 static int
721 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
723 struct get_req req;
725 memset(&req, 0, sizeof(req));
726 strlcpy(req.host, p->host, sizeof(req.host));
727 strlcpy(req.port, p->port, sizeof(req.host));
729 tab->proxy = p;
731 return make_request(tab, &req, p->proto, tab->hist_cur->h);
734 static int
735 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
737 stop_tab(tab);
738 tab->id = tab_new_id();
739 req->proto = proto;
741 if (r != NULL) {
742 strlcpy(req->req, r, sizeof(req->req));
743 strlcat(req->req, "\r\n", sizeof(req->req));
746 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
748 /*
749 * So the various load_*_url can `return make_request` and
750 * do_load_url is happy.
751 */
752 return 1;
755 static int
756 make_fs_request(struct tab *tab, int type, const char *r)
758 stop_tab(tab);
759 tab->id = tab_new_id();
761 ui_send_fs(type, tab->id, r, strlen(r)+1);
763 /*
764 * So load_{about,file}_url can `return make_fs_request` and
765 * do_load_url is happy.
766 */
767 return 1;
770 void
771 gopher_send_search_req(struct tab *tab, const char *text)
773 struct get_req req;
775 start_loading_anim(tab);
777 memset(&req, 0, sizeof(req));
778 strlcpy(req.host, tab->uri.host, sizeof(req.host));
779 strlcpy(req.port, tab->uri.port, sizeof(req.host));
781 /* +2 to skip /7 */
782 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
783 if (*tab->uri.query != '\0') {
784 strlcat(req.req, "?", sizeof(req.req));
785 strlcat(req.req, tab->uri.query, sizeof(req.req));
788 strlcat(req.req, "\t", sizeof(req.req));
789 strlcat(req.req, text, sizeof(req.req));
790 strlcat(req.req, "\r\n", sizeof(req.req));
792 erase_buffer(&tab->buffer);
793 parser_init(tab, gophermap_initparser);
795 make_request(tab, &req, PROTO_GOPHER, NULL);
798 /*
799 * Effectively load the given url in the given tab. Return 1 when
800 * loading the page asynchronously, and thus when an erase_buffer can
801 * be done right after this function return, or 0 when loading the
802 * page synchronously. In this last case, erase_buffer *MUST* be
803 * called by the handling function (such as load_page_from_str).
804 */
805 static int
806 do_load_url(struct tab *tab, const char *url, const char *base)
808 struct phos_uri uri;
809 struct proto *p;
810 struct proxy *proxy;
811 char *t;
813 tab->proxy = NULL;
815 if (tab->fd != -1) {
816 close(tab->fd);
817 tab->fd = -1;
818 free(tab->path);
819 tab->path = NULL;
822 tab->trust = TS_UNKNOWN;
824 if (base == NULL)
825 memcpy(&uri, &tab->uri, sizeof(tab->uri));
826 else
827 phos_parse_absolute_uri(base, &uri);
829 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
830 if (asprintf(&t, "#error loading %s\n>%s\n",
831 url, "Can't parse the URI") == -1)
832 die();
833 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
834 load_page_from_str(tab, t);
835 free(t);
836 return 0;
839 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
840 sizeof(tab->hist_cur->h));
842 for (p = protos; p->schema != NULL; ++p) {
843 if (!strcmp(tab->uri.scheme, p->schema)) {
844 /* patch the port */
845 if (*tab->uri.port == '\0' && p->port != NULL)
846 strlcpy(tab->uri.port, p->port,
847 sizeof(tab->uri.port));
849 return p->loadfn(tab, url);
853 TAILQ_FOREACH(proxy, &proxies, proxies) {
854 if (!strcmp(tab->uri.scheme, proxy->match_proto))
855 return load_via_proxy(tab, url, proxy);
858 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
861 /*
862 * Load url in tab. If tab is marked as lazy, only prepare the url
863 * but don't load it. If tab is lazy and a url was already prepared,
864 * do load it!
865 */
866 void
867 load_url(struct tab *tab, const char *url, const char *base, int nohist)
869 int lazy;
871 lazy = tab->flags & TAB_LAZY;
873 if (lazy && tab->hist_cur != NULL) {
874 lazy = 0;
875 tab->flags &= ~TAB_LAZY;
878 /* can't have both nohist and lazy at the same time. */
879 if (nohist && lazy)
880 nohist = 0;
882 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
883 if (tab->hist_cur != NULL)
884 hist_clear_forward(&tab->hist,
885 TAILQ_NEXT(tab->hist_cur, entries));
887 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
888 event_loopbreak();
889 return;
892 strlcpy(tab->buffer.page.title, url,
893 sizeof(tab->buffer.page.title));
894 hist_push(&tab->hist, tab->hist_cur);
896 if (lazy)
897 strlcpy(tab->hist_cur->h, url,
898 sizeof(tab->hist_cur->h));
901 if (!lazy && do_load_url(tab, url, base))
902 erase_buffer(&tab->buffer);
905 void
906 load_url_in_tab(struct tab *tab, const char *url, const char *base, int nohist)
908 if (!operating) {
909 load_url(tab, url, base, nohist);
910 return;
913 autosave_hook();
915 message("Loading %s...", url);
916 start_loading_anim(tab);
917 load_url(tab, url, base, nohist);
920 int
921 load_previous_page(struct tab *tab)
923 struct hist *h;
925 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
926 return 0;
927 tab->hist_cur = h;
928 do_load_url(tab, h->h, NULL);
929 return 1;
932 int
933 load_next_page(struct tab *tab)
935 struct hist *h;
937 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
938 return 0;
939 tab->hist_cur = h;
940 do_load_url(tab, h->h, NULL);
941 return 1;
944 void
945 switch_to_tab(struct tab *tab)
947 current_tab = tab;
948 tab->flags &= ~TAB_URGENT;
950 if (operating && tab->flags & TAB_LAZY)
951 load_url_in_tab(tab, tab->hist_cur->h, NULL, 0);
954 unsigned int
955 tab_new_id(void)
957 static uint32_t tab_counter;
959 return tab_counter++;
962 struct tab *
963 new_tab(const char *url, const char *base, struct tab *after)
965 struct tab *tab;
967 autosave_hook();
969 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
970 event_loopbreak();
971 return NULL;
973 tab->fd = -1;
975 TAILQ_INIT(&tab->hist.head);
977 TAILQ_INIT(&tab->buffer.head);
978 TAILQ_INIT(&tab->buffer.page.head);
980 tab->id = tab_new_id();
981 if (!operating)
982 tab->flags |= TAB_LAZY;
983 switch_to_tab(tab);
985 if (after != NULL)
986 TAILQ_INSERT_AFTER(&tabshead, after, tab, tabs);
987 else
988 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
990 load_url_in_tab(tab, url, base, 0);
991 return tab;
994 /*
995 * Free every resource linked to the tab, including the tab itself.
996 * Removes the tab from the tablist, but doesn't update the
997 * current_tab though.
998 */
999 void
1000 free_tab(struct tab *tab)
1002 stop_tab(tab);
1004 autosave_hook();
1006 if (evtimer_pending(&tab->loadingev, NULL))
1007 evtimer_del(&tab->loadingev);
1009 TAILQ_REMOVE(&tabshead, tab, tabs);
1010 free(tab);
1013 void
1014 stop_tab(struct tab *tab)
1016 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
1018 if (tab->fd != -1) {
1019 close(tab->fd);
1020 tab->fd = -1;
1021 free(tab->path);
1022 tab->path = NULL;
1023 load_page_from_str(tab, "Stopped.\n");
1027 void
1028 add_to_bookmarks(const char *str)
1030 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
1031 str, strlen(str)+1);
1034 void
1035 save_session(void)
1037 struct tab *tab;
1038 char *t;
1039 int flags;
1041 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
1043 TAILQ_FOREACH(tab, &tabshead, tabs) {
1044 flags = tab->flags;
1045 if (tab == current_tab)
1046 flags |= TAB_CURRENT;
1048 t = tab->hist_cur->h;
1049 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
1051 t = tab->buffer.page.title;
1052 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
1055 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
1058 static void
1059 autosave_timer(int fd, short event, void *data)
1061 save_session();
1065 * Function to be called in "interesting" places where we may want to
1066 * schedule an autosave (like on new tab or before loading an url.)
1068 void
1069 autosave_hook(void)
1071 struct timeval tv;
1073 if (autosave <= 0)
1074 return;
1076 if (!evtimer_pending(&autosaveev, NULL)) {
1077 tv.tv_sec = autosave;
1078 tv.tv_usec = 0;
1080 evtimer_add(&autosaveev, &tv);
1085 * Parse a line of the session file. The format is:
1087 * URL [flags,...] [title]\n
1089 static void
1090 parse_session_line(char *line, const char **title, uint32_t *flags)
1092 char *s, *t, *ap;
1094 *title = "";
1095 *flags = 0;
1096 if ((s = strchr(line, ' ')) == NULL)
1097 return;
1099 *s++ = '\0';
1101 if ((t = strchr(s, ' ')) != NULL) {
1102 *t++ = '\0';
1103 *title = t;
1106 while ((ap = strsep(&s, ",")) != NULL) {
1107 if (*ap == '\0')
1109 else if (!strcmp(ap, "current"))
1110 *flags |= TAB_CURRENT;
1111 else
1112 message("unknown tab flag: %s", ap);
1116 static void
1117 load_last_session(void)
1119 const char *title;
1120 char *nl, *line = NULL;
1121 uint32_t flags;
1122 size_t linesize = 0;
1123 ssize_t linelen;
1124 FILE *session;
1125 struct tab *tab, *curr = NULL;
1127 if ((session = fopen(session_file, "r")) == NULL) {
1128 /* first time? */
1129 new_tab("about:new", NULL, NULL);
1130 switch_to_tab(new_tab("about:help", NULL, NULL));
1131 return;
1134 while ((linelen = getline(&line, &linesize, session)) != -1) {
1135 if ((nl = strchr(line, '\n')) != NULL)
1136 *nl = '\0';
1137 parse_session_line(line, &title, &flags);
1138 if ((tab = new_tab(line, NULL, NULL)) == NULL)
1139 err(1, "new_tab");
1140 strlcpy(tab->buffer.page.title, title,
1141 sizeof(tab->buffer.page.title));
1142 if (flags & TAB_CURRENT)
1143 curr = tab;
1146 if (ferror(session))
1147 message("error reading %s: %s",
1148 session_file, strerror(errno));
1149 fclose(session);
1150 free(line);
1152 if (curr != NULL)
1153 switch_to_tab(curr);
1155 if (last_time_crashed())
1156 switch_to_tab(new_tab("about:crash", NULL, NULL));
1158 return;
1161 static pid_t
1162 start_child(enum telescope_process p, const char *argv0, int fd)
1164 const char *argv[4];
1165 int argc = 0;
1166 pid_t pid;
1168 switch (pid = fork()) {
1169 case -1:
1170 die();
1171 case 0:
1172 break;
1173 default:
1174 close(fd);
1175 return pid;
1178 if (dup2(fd, 3) == -1)
1179 err(1, "cannot setup imsg fd");
1181 argv[argc++] = argv0;
1182 switch (p) {
1183 case PROC_UI:
1184 errx(1, "Can't start ui process");
1185 case PROC_FS:
1186 argv[argc++] = "-Tf";
1187 break;
1188 case PROC_NET:
1189 argv[argc++] = "-Tn";
1190 break;
1193 argv[argc++] = NULL;
1194 execvp(argv0, (char *const *)argv);
1195 err(1, "execvp(%s)", argv0);
1198 static int
1199 ui_send_net(int type, uint32_t peerid, const void *data,
1200 uint16_t datalen)
1202 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1203 datalen);
1206 static int
1207 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1209 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1210 datalen);
1213 static void __attribute__((noreturn))
1214 usage(int r)
1216 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
1217 getprogname());
1218 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1219 exit(r);
1222 int
1223 main(int argc, char * const *argv)
1225 struct imsgev net_ibuf, fs_ibuf;
1226 int pipe2net[2], pipe2fs[2];
1227 int ch, configtest = 0, fail = 0;
1228 int has_url = 0;
1229 int proc = -1;
1230 int sessionfd;
1231 char path[PATH_MAX];
1232 const char *url = NEW_TAB_URL;
1233 const char *argv0;
1235 argv0 = argv[0];
1237 signal(SIGCHLD, SIG_IGN);
1238 signal(SIGPIPE, SIG_IGN);
1240 if (getenv("NO_COLOR") != NULL)
1241 enable_colors = 0;
1243 strlcpy(path, getenv("HOME"), sizeof(path));
1244 strlcat(path, "/.telescope/config", sizeof(path));
1246 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1247 switch (ch) {
1248 case 'C':
1249 exit(ui_print_colors());
1250 case 'c':
1251 fail = 1;
1252 strlcpy(path, optarg, sizeof(path));
1253 break;
1254 case 'n':
1255 configtest = 1;
1256 break;
1257 case 'h':
1258 usage(0);
1259 case 'T':
1260 switch (*optarg) {
1261 case 'f':
1262 proc = PROC_FS;
1263 break;
1264 case 'n':
1265 proc = PROC_NET;
1266 break;
1267 default:
1268 errx(1, "invalid process spec %c",
1269 *optarg);
1271 break;
1272 case 'v':
1273 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1274 exit(0);
1275 break;
1276 default:
1277 usage(1);
1281 argc -= optind;
1282 argv += optind;
1284 if (proc != -1) {
1285 if (argc > 0)
1286 usage(1);
1287 else if (proc == PROC_FS)
1288 return fs_main();
1289 else if (proc == PROC_NET)
1290 return net_main();
1291 else
1292 usage(1);
1295 if (argc != 0) {
1296 has_url = 1;
1297 url = argv[0];
1300 /* setup keys before reading the config */
1301 TAILQ_INIT(&global_map.m);
1302 global_map.unhandled_input = global_key_unbound;
1303 TAILQ_INIT(&minibuffer_map.m);
1305 config_init();
1306 parseconfig(path, fail);
1307 if (configtest){
1308 puts("config OK");
1309 exit(0);
1312 fs_init();
1313 if ((sessionfd = lock_session()) == -1)
1314 errx(1, "can't lock session, is another instance of "
1315 "telescope already running?");
1317 /* Start children. */
1318 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1319 err(1, "socketpair");
1320 start_child(PROC_FS, argv0, pipe2fs[1]);
1321 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1322 iev_fs = &fs_ibuf;
1323 iev_fs->handler = handle_dispatch_imsg;
1325 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1326 err(1, "socketpair");
1327 start_child(PROC_NET, argv0, pipe2net[1]);
1328 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1329 iev_net = &net_ibuf;
1330 iev_net->handler = handle_dispatch_imsg;
1332 setproctitle("ui");
1334 /* initialize tofu & load certificates */
1335 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1336 load_certs(&certs);
1338 event_init();
1340 /* Setup event handler for the autosave */
1341 evtimer_set(&autosaveev, autosave_timer, NULL);
1343 /* Setup event handlers for pipes to fs/net */
1344 iev_fs->events = EV_READ;
1345 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1346 iev_fs->handler, iev_fs);
1347 event_add(&iev_fs->ev, NULL);
1349 iev_net->events = EV_READ;
1350 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1351 iev_net->handler, iev_net);
1352 event_add(&iev_net->ev, NULL);
1354 if (ui_init()) {
1355 load_last_session();
1356 if (has_url || TAILQ_EMPTY(&tabshead))
1357 new_tab(url, NULL, NULL);
1359 sandbox_ui_process();
1360 operating = 1;
1361 ui_main_loop();
1362 ui_end();
1365 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1366 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1367 imsg_flush(&iev_fs->ibuf);
1368 imsg_flush(&iev_net->ibuf);
1370 close(sessionfd);
1372 return 0;