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 static struct proto protos[] = {
57 { "about", load_about_url },
58 { "finger", load_finger_url },
59 { "gemini", load_gemini_url },
60 { NULL, NULL },
61 };
64 #define CANNOT_FETCH 0
65 #define TOO_MUCH_REDIRECTS 1
66 #define MALFORMED_RESPONSE 2
67 #define UNKNOWN_TYPE_OR_CSET 3
68 #define UNKNOWN_PROTOCOL 4
70 /* XXX: keep in sync with telescope.c:/^normalize_code/ */
71 const char *err_pages[70] = {
72 [CANNOT_FETCH] = "# Couldn't load the page\n",
73 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
74 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
75 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
76 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
78 [10] = "# Input required\n",
79 [11] = "# Input required\n",
80 [40] = "# Temporary failure\n",
81 [41] = "# Server unavailable\n",
82 [42] = "# CGI error\n",
83 [43] = "# Proxy error\n",
84 [44] = "# Slow down\n",
85 [50] = "# Permanent failure\n",
86 [51] = "# Not found\n",
87 [52] = "# Gone\n",
88 [53] = "# Proxy request refused\n",
89 [59] = "# Bad request\n",
90 [60] = "# Client certificate required\n",
91 [61] = "# Certificate not authorised\n",
92 [62] = "# Certificate not valid\n"
93 };
95 static void die(void) __attribute__((__noreturn__));
96 static struct tab *tab_by_id(uint32_t);
97 static void handle_imsg_err(struct imsg*, size_t);
98 static void handle_imsg_check_cert(struct imsg*, size_t);
99 static void handle_check_cert_user_choice(int, struct tab *);
100 static void handle_maybe_save_new_cert(int, struct tab *);
101 static void handle_imsg_got_code(struct imsg*, size_t);
102 static void handle_imsg_got_meta(struct imsg*, size_t);
103 static void handle_maybe_save_page(int, struct tab *);
104 static void handle_save_page_path(const char *, struct tab *);
105 static void handle_imsg_file_opened(struct imsg*, size_t);
106 static void handle_imsg_buf(struct imsg*, size_t);
107 static void handle_imsg_eof(struct imsg*, size_t);
108 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
109 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
110 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
111 static void handle_dispatch_imsg(int, short, void*);
112 static void load_page_from_str(struct tab*, const char*);
113 static int do_load_url(struct tab*, const char *, const char *);
114 static void parse_session_line(char *, const char **, uint32_t *);
115 static void load_last_session(void);
116 static pid_t start_child(enum telescope_process, const char *, int);
117 static int ui_send_net(int, uint32_t, const void *, uint16_t);
118 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
120 static imsg_handlerfn *handlers[] = {
121 [IMSG_ERR] = handle_imsg_err,
122 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
123 [IMSG_GOT_CODE] = handle_imsg_got_code,
124 [IMSG_GOT_META] = handle_imsg_got_meta,
125 [IMSG_BUF] = handle_imsg_buf,
126 [IMSG_EOF] = handle_imsg_eof,
127 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
128 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
129 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
130 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
131 };
133 static struct ohash certs;
135 static void __attribute__((__noreturn__))
136 die(void)
138 abort(); /* TODO */
141 static struct tab *
142 tab_by_id(uint32_t id)
144 struct tab *t;
146 TAILQ_FOREACH(t, &tabshead, tabs) {
147 if (t->id == id)
148 return t;
151 return NULL;
154 static void
155 handle_imsg_err(struct imsg *imsg, size_t datalen)
157 struct tab *tab;
158 char *page;
160 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
161 return;
163 page = imsg->data;
164 page[datalen-1] = '\0';
166 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
167 tab->hist_cur->h, page) == -1)
168 die();
169 load_page_from_str(tab, page);
170 free(page);
173 static void
174 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
176 const char *hash, *host, *port;
177 int tofu_res;
178 struct tofu_entry *e;
179 struct tab *tab;
181 hash = imsg->data;
182 if (hash[datalen-1] != '\0')
183 abort();
185 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
186 return;
188 if (tab->proxy != NULL) {
189 host = tab->proxy->host;
190 port = tab->proxy->port;
191 } else {
192 host = tab->uri.host;
193 port = tab->uri.port;
196 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
197 /* TODO: an update in libressl/libretls changed
198 * significantly. Find a better approach at storing
199 * the certs! */
200 if (datalen > sizeof(e->hash))
201 abort();
203 tofu_res = 1; /* trust on first use */
204 if ((e = calloc(1, sizeof(*e))) == NULL)
205 abort();
206 strlcpy(e->domain, host, sizeof(e->domain));
207 if (*port != '\0' && strcmp(port, "1965")) {
208 strlcat(e->domain, ":", sizeof(e->domain));
209 strlcat(e->domain, port, sizeof(e->domain));
211 strlcpy(e->hash, hash, sizeof(e->hash));
212 tofu_add(&certs, e);
213 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
214 } else
215 tofu_res = !strcmp(hash, e->hash);
217 if (tofu_res) {
218 if (e->verified == -1)
219 tab->trust = TS_TEMP_TRUSTED;
220 else if (e->verified == 1)
221 tab->trust = TS_VERIFIED;
222 else
223 tab->trust = TS_TRUSTED;
225 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
226 &tofu_res, sizeof(tofu_res));
227 } else {
228 tab->trust = TS_UNTRUSTED;
229 load_page_from_str(tab, "# Certificate mismatch\n");
230 if ((tab->cert = strdup(hash)) == NULL)
231 die();
232 ui_yornp("Certificate mismatch. Proceed?",
233 handle_check_cert_user_choice, tab);
237 static void
238 handle_check_cert_user_choice(int accept, struct tab *tab)
240 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
241 sizeof(accept));
243 if (accept) {
244 /*
245 * trust the certificate for this session only. If
246 * the page results in a redirect while we're asking
247 * the user to save, we'll end up with an invalid
248 * tabid (one request == one tab id) and crash. It
249 * also makes sense to save it for the current session
250 * if the user accepted it.
251 */
252 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
254 ui_yornp("Save the new certificate?",
255 handle_maybe_save_new_cert, tab);
256 } else {
257 free(tab->cert);
258 tab->cert = NULL;
262 static void
263 handle_maybe_save_new_cert(int accept, struct tab *tab)
265 struct tofu_entry *e;
266 const char *host, *port;
268 if (tab->proxy != NULL) {
269 host = tab->proxy->host;
270 port = tab->proxy->port;
271 } else {
272 host = tab->uri.host;
273 port = tab->uri.port;
276 if (!accept)
277 goto end;
279 if ((e = calloc(1, sizeof(*e))) == NULL)
280 die();
282 strlcpy(e->domain, host, sizeof(e->domain));
283 if (*port != '\0' && strcmp(port, "1965")) {
284 strlcat(e->domain, ":", sizeof(e->domain));
285 strlcat(e->domain, port, sizeof(e->domain));
287 strlcpy(e->hash, tab->cert, sizeof(e->hash));
288 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
290 tofu_update(&certs, e);
292 tab->trust = TS_TRUSTED;
294 end:
295 free(tab->cert);
296 tab->cert = NULL;
299 static inline int
300 normalize_code(int n)
302 if (n < 20) {
303 if (n == 10 || n == 11)
304 return n;
305 return 10;
306 } else if (n < 30) {
307 return 20;
308 } else if (n < 40) {
309 if (n == 30 || n == 31)
310 return n;
311 return 30;
312 } else if (n < 50) {
313 if (n <= 44)
314 return n;
315 return 40;
316 } else if (n < 60) {
317 if (n <= 53 || n == 59)
318 return n;
319 return 50;
320 } else if (n < 70) {
321 if (n <= 62)
322 return n;
323 return 60;
324 } else
325 return MALFORMED_RESPONSE;
328 static void
329 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
331 struct tab *tab;
333 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
334 return;
336 if (sizeof(tab->code) != datalen)
337 die();
339 memcpy(&tab->code, imsg->data, sizeof(tab->code));
340 tab->code = normalize_code(tab->code);
341 if (tab->code != 30 && tab->code != 31)
342 tab->redirect_count = 0;
345 static void
346 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
348 struct tab *tab;
350 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
351 return;
353 if (sizeof(tab->meta) <= datalen)
354 die();
356 memcpy(tab->meta, imsg->data, datalen);
358 if (tab->code < 10) { /* internal errors */
359 load_page_from_str(tab, err_pages[tab->code]);
360 } else if (tab->code < 20) { /* 1x */
361 load_page_from_str(tab, err_pages[tab->code]);
362 ui_require_input(tab, tab->code == 11);
363 } else if (tab->code == 20) {
364 if (setup_parser_for(tab)) {
365 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
366 } else {
367 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
368 ui_yornp("Can't display page, wanna save?",
369 handle_maybe_save_page, tab);
371 } else if (tab->code < 40) { /* 3x */
372 tab->redirect_count++;
374 /* TODO: make customizable? */
375 if (tab->redirect_count > 5) {
376 load_page_from_str(tab,
377 err_pages[TOO_MUCH_REDIRECTS]);
378 } else
379 do_load_url(tab, tab->meta, NULL);
380 } else { /* 4x, 5x & 6x */
381 load_page_from_str(tab, err_pages[tab->code]);
385 static void
386 handle_maybe_save_page(int dosave, struct tab *tab)
388 if (dosave)
389 ui_read("Save to path", handle_save_page_path, tab);
390 else
391 stop_tab(tab);
394 static void
395 handle_save_page_path(const char *path, struct tab *tab)
397 if (path == NULL) {
398 stop_tab(tab);
399 return;
402 tab->path = strdup(path);
404 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
407 static void
408 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
410 struct tab *tab;
411 char *page;
412 const char *e;
413 int l;
415 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
416 if (imsg->fd != -1)
417 close(imsg->fd);
418 return;
421 if (imsg->fd == -1) {
422 stop_tab(tab);
424 e = imsg->data;
425 if (e[datalen-1] != '\0')
426 die();
427 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
428 tab->path, e);
429 if (l == -1)
430 die();
431 load_page_from_str(tab, page);
432 free(page);
433 } else {
434 tab->fd = imsg->fd;
435 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
439 static void
440 handle_imsg_buf(struct imsg *imsg, size_t datalen)
442 struct tab *tab;
443 int l;
444 char *page, buf[FMT_SCALED_STRSIZE] = {0};
446 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
447 return;
449 tab->bytes += datalen;
450 if (tab->fd == -1) {
451 if (!tab->buffer.page.parse(&tab->buffer.page,
452 imsg->data, datalen))
453 die();
454 } else {
455 write(tab->fd, imsg->data, datalen);
456 fmt_scaled(tab->bytes, buf);
457 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
458 tab->path,
459 buf);
460 if (l == -1)
461 die();
462 load_page_from_str(tab, page);
463 free(page);
466 ui_on_tab_refresh(tab);
469 static void
470 handle_imsg_eof(struct imsg *imsg, size_t datalen)
472 struct tab *tab;
473 int l;
474 char *page, buf[FMT_SCALED_STRSIZE] = {0};
476 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
477 return;
479 if (tab->fd == -1) {
480 if (!tab->buffer.page.free(&tab->buffer.page))
481 die();
482 } else {
483 fmt_scaled(tab->bytes, buf);
484 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
485 tab->path,
486 buf);
487 if (l == -1)
488 die();
489 load_page_from_str(tab, page);
490 free(page);
492 close(tab->fd);
493 tab->fd = -1;
494 free(tab->path);
495 tab->path = NULL;
498 ui_on_tab_refresh(tab);
499 ui_on_tab_loaded(tab);
502 static void
503 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
505 int res;
507 if (datalen != sizeof(res))
508 die();
510 memcpy(&res, imsg->data, sizeof(res));
511 if (res == 0)
512 message("Added to bookmarks!");
513 else
514 message("Failed to add to bookmarks: %s",
515 strerror(res));
518 static void
519 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
521 int res;
523 if (datalen != sizeof(res))
524 die();
525 memcpy(&res, imsg->data, datalen);
526 if (res != 0)
527 message("Failed to save the cert for: %s",
528 strerror(res));
531 static void
532 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
534 int res;
536 if (datalen != sizeof(res))
537 die();
538 memcpy(&res, imsg->data, datalen);
539 if (!res)
540 message("Failed to update the certificate");
543 static void
544 handle_dispatch_imsg(int fd, short ev, void *d)
546 struct imsgev *iev = d;
548 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
549 err(1, "connection closed");
552 static void
553 load_page_from_str(struct tab *tab, const char *page)
555 erase_buffer(&tab->buffer);
556 gemtext_initparser(&tab->buffer.page);
557 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
558 die();
559 if (!tab->buffer.page.free(&tab->buffer.page))
560 die();
561 ui_on_tab_refresh(tab);
562 ui_on_tab_loaded(tab);
565 void
566 load_about_url(struct tab *tab, const char *url)
568 tab->trust = TS_VERIFIED;
570 gemtext_initparser(&tab->buffer.page);
572 ui_send_fs(IMSG_GET, tab->id,
573 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
576 void
577 load_finger_url(struct tab *tab, const char *url)
579 struct get_req req;
580 size_t len;
581 char *at;
583 stop_tab(tab);
584 tab->id = tab_new_id();
586 memset(&req, 0, sizeof(req));
587 if (*tab->uri.port != '\0')
588 strlcpy(req.port, tab->uri.port, sizeof(req.port));
589 else
590 strlcpy(req.port, "79", sizeof(req.port));
592 /*
593 * Sometimes the finger url have the user as path component
594 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
595 * userinfo (e.g. finger://cobradile@finger.farm).
596 */
597 if ((at = strchr(tab->uri.host, '@')) != NULL) {
598 len = at - tab->uri.host;
599 memcpy(req.req, tab->uri.host, len);
601 if (len >= sizeof(req.req))
602 die();
603 req.req[len] = '\0';
605 strlcpy(req.host, at+1, sizeof(req.host));
606 } else {
607 strlcpy(req.host, tab->uri.host, sizeof(req.host));
609 /* +1 to skip the initial `/' */
610 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
613 strlcat(req.req, "\r\n", sizeof(req.req));
615 req.proto = PROTO_FINGER;
617 ui_send_net(IMSG_GET_RAW, tab->id, &req, sizeof(req));
619 textplain_initparser(&tab->buffer.page);
622 void
623 load_gemini_url(struct tab *tab, const char *url)
625 struct get_req req;
627 stop_tab(tab);
628 tab->id = tab_new_id();
630 memset(&req, 0, sizeof(req));
631 strlcpy(req.host, tab->uri.host, sizeof(req.host));
632 strlcpy(req.port, tab->uri.port, sizeof(req.host));
634 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
635 strlcat(req.req, "\r\n", sizeof(req.req));
637 req.proto = PROTO_GEMINI;
639 ui_send_net(IMSG_GET_RAW, tab->id,
640 &req, sizeof(req));
643 void
644 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
646 struct get_req req;
648 stop_tab(tab);
649 tab->id = tab_new_id();
650 tab->proxy = p;
652 memset(&req, 0, sizeof(req));
653 strlcpy(req.host, p->host, sizeof(req.host));
654 strlcpy(req.port, p->port, sizeof(req.host));
656 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
657 strlcat(req.req, "\r\n", sizeof(req.req));
659 req.proto = p->proto;
661 ui_send_net(IMSG_GET_RAW, tab->id,
662 &req, sizeof(req));
665 /*
666 * Effectively load the given url in the given tab. Return 1 when
667 * loading the page asynchronously, and thus when an erase_buffer can
668 * be done right after this function return, or 0 when loading the
669 * page synchronously. In this last case, erase_buffer *MUST* be
670 * called by the handling function (such as load_page_from_str).
671 */
672 static int
673 do_load_url(struct tab *tab, const char *url, const char *base)
675 struct phos_uri uri;
676 struct proto *p;
677 struct proxy *proxy;
678 char *t;
680 tab->proxy = NULL;
682 if (tab->fd != -1) {
683 close(tab->fd);
684 tab->fd = -1;
685 free(tab->path);
686 tab->path = NULL;
689 tab->trust = TS_UNKNOWN;
691 if (base == NULL)
692 memcpy(&uri, &tab->uri, sizeof(tab->uri));
693 else
694 phos_parse_absolute_uri(base, &uri);
696 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
697 if (asprintf(&t, "#error loading %s\n>%s\n",
698 url, "Can't parse the URI") == -1)
699 die();
700 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
701 load_page_from_str(tab, t);
702 free(t);
703 return 0;
706 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
707 sizeof(tab->hist_cur->h));
709 for (p = protos; p->schema != NULL; ++p) {
710 if (!strcmp(tab->uri.scheme, p->schema)) {
711 p->loadfn(tab, url);
712 return 1;
716 TAILQ_FOREACH(proxy, &proxies, proxies) {
717 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
718 load_via_proxy(tab, url, proxy);
719 return 1;
723 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
724 return 0;
727 /*
728 * Load url in tab. If tab is marked as lazy, only prepare the url
729 * but don't load it. If tab is lazy and a url was already prepared,
730 * do load it!
731 */
732 void
733 load_url(struct tab *tab, const char *url, const char *base)
735 int lazy;
737 lazy = tab->flags & TAB_LAZY;
739 if (lazy && tab->hist_cur != NULL) {
740 lazy = 0;
741 tab->flags &= ~TAB_LAZY;
744 if (!lazy || tab->hist_cur == NULL) {
745 if (tab->hist_cur != NULL)
746 hist_clear_forward(&tab->hist,
747 TAILQ_NEXT(tab->hist_cur, entries));
749 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
750 event_loopbreak();
751 return;
754 strlcpy(tab->buffer.page.title, url,
755 sizeof(tab->buffer.page.title));
756 hist_push(&tab->hist, tab->hist_cur);
758 if (lazy)
759 strlcpy(tab->hist_cur->h, url,
760 sizeof(tab->hist_cur->h));
763 if (!lazy && do_load_url(tab, url, base))
764 erase_buffer(&tab->buffer);
767 int
768 load_previous_page(struct tab *tab)
770 struct hist *h;
772 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
773 return 0;
774 tab->hist_cur = h;
775 do_load_url(tab, h->h, NULL);
776 return 1;
779 int
780 load_next_page(struct tab *tab)
782 struct hist *h;
784 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
785 return 0;
786 tab->hist_cur = h;
787 do_load_url(tab, h->h, NULL);
788 return 1;
791 /*
792 * Free every resource linked to the tab, including the tab itself.
793 * Removes the tab from the tablist, but doesn't update the
794 * current_tab though.
795 */
796 void
797 free_tab(struct tab *tab)
799 stop_tab(tab);
801 if (evtimer_pending(&tab->loadingev, NULL))
802 evtimer_del(&tab->loadingev);
804 TAILQ_REMOVE(&tabshead, tab, tabs);
805 free(tab);
808 void
809 stop_tab(struct tab *tab)
811 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
813 if (tab->fd != -1) {
814 close(tab->fd);
815 tab->fd = -1;
816 free(tab->path);
817 tab->path = NULL;
818 load_page_from_str(tab, "Stopped.\n");
822 void
823 add_to_bookmarks(const char *str)
825 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
826 str, strlen(str)+1);
829 void
830 save_session(void)
832 struct tab *tab;
833 char *t;
834 int flags;
836 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
838 TAILQ_FOREACH(tab, &tabshead, tabs) {
839 flags = tab->flags;
840 if (tab == current_tab)
841 flags |= TAB_CURRENT;
843 t = tab->hist_cur->h;
844 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
846 t = tab->buffer.page.title;
847 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
850 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
853 /*
854 * Parse a line of the session file. The format is:
856 * URL [flags,...] [title]\n
857 */
858 static void
859 parse_session_line(char *line, const char **title, uint32_t *flags)
861 char *s, *t, *ap;
863 *title = "";
864 *flags = 0;
865 if ((s = strchr(line, ' ')) == NULL)
866 return;
868 *s++ = '\0';
870 if ((t = strchr(s, ' ')) != NULL) {
871 *t++ = '\0';
872 *title = t;
875 while ((ap = strsep(&s, ",")) != NULL) {
876 if (*ap == '\0')
878 else if (!strcmp(ap, "current"))
879 *flags |= TAB_CURRENT;
880 else
881 message("unknown tab flag: %s", ap);
885 static void
886 load_last_session(void)
888 const char *title;
889 char *nl, *line = NULL;
890 uint32_t flags;
891 size_t linesize = 0;
892 ssize_t linelen;
893 FILE *session;
894 struct tab *tab, *curr = NULL;
896 if ((session = fopen(session_file, "r")) == NULL) {
897 /* first time? */
898 new_tab("about:new", NULL);
899 switch_to_tab(new_tab("about:help", NULL));
900 return;
903 while ((linelen = getline(&line, &linesize, session)) != -1) {
904 if ((nl = strchr(line, '\n')) != NULL)
905 *nl = '\0';
906 parse_session_line(line, &title, &flags);
907 if ((tab = new_tab(line, NULL)) == NULL)
908 err(1, "new_tab");
909 strlcpy(tab->buffer.page.title, title,
910 sizeof(tab->buffer.page.title));
911 if (flags & TAB_CURRENT)
912 curr = tab;
915 if (ferror(session))
916 message("error reading %s: %s",
917 session_file, strerror(errno));
918 fclose(session);
919 free(line);
921 if (curr != NULL)
922 switch_to_tab(curr);
924 if (last_time_crashed())
925 switch_to_tab(new_tab("about:crash", NULL));
927 return;
930 static pid_t
931 start_child(enum telescope_process p, const char *argv0, int fd)
933 const char *argv[4];
934 int argc = 0;
935 pid_t pid;
937 switch (pid = fork()) {
938 case -1:
939 die();
940 case 0:
941 break;
942 default:
943 close(fd);
944 return pid;
947 if (dup2(fd, 3) == -1)
948 err(1, "cannot setup imsg fd");
950 argv[argc++] = argv0;
951 switch (p) {
952 case PROC_UI:
953 errx(1, "Can't start ui process");
954 case PROC_FS:
955 argv[argc++] = "-Tf";
956 break;
957 case PROC_NET:
958 argv[argc++] = "-Tn";
959 break;
962 argv[argc++] = NULL;
963 execvp(argv0, (char *const *)argv);
964 err(1, "execvp(%s)", argv0);
967 static int
968 ui_send_net(int type, uint32_t peerid, const void *data,
969 uint16_t datalen)
971 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
972 datalen);
975 static int
976 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
978 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
979 datalen);
982 static void __attribute__((noreturn))
983 usage(int r)
985 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
986 getprogname());
987 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
988 exit(r);
991 int
992 main(int argc, char * const *argv)
994 struct imsgev net_ibuf, fs_ibuf;
995 int pipe2net[2], pipe2fs[2];
996 int ch, configtest = 0, fail = 0;
997 int has_url = 0;
998 int proc = -1;
999 int sessionfd;
1000 char path[PATH_MAX];
1001 const char *url = NEW_TAB_URL;
1002 const char *argv0;
1004 argv0 = argv[0];
1006 signal(SIGCHLD, SIG_IGN);
1007 signal(SIGPIPE, SIG_IGN);
1009 if (getenv("NO_COLOR") != NULL)
1010 enable_colors = 0;
1012 strlcpy(path, getenv("HOME"), sizeof(path));
1013 strlcat(path, "/.telescope/config", sizeof(path));
1015 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1016 switch (ch) {
1017 case 'C':
1018 exit(ui_print_colors());
1019 case 'c':
1020 fail = 1;
1021 strlcpy(path, optarg, sizeof(path));
1022 break;
1023 case 'n':
1024 configtest = 1;
1025 break;
1026 case 'h':
1027 usage(0);
1028 case 'T':
1029 switch (*optarg) {
1030 case 'f':
1031 proc = PROC_FS;
1032 break;
1033 case 'n':
1034 proc = PROC_NET;
1035 break;
1036 default:
1037 errx(1, "invalid process spec %c",
1038 *optarg);
1040 break;
1041 case 'v':
1042 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1043 exit(0);
1044 break;
1045 default:
1046 usage(1);
1050 argc -= optind;
1051 argv += optind;
1053 if (proc != -1) {
1054 if (argc > 0)
1055 usage(1);
1056 else if (proc == PROC_FS)
1057 return fs_main();
1058 else if (proc == PROC_NET)
1059 return net_main();
1060 else
1061 usage(1);
1064 if (argc != 0) {
1065 has_url = 1;
1066 url = argv[0];
1069 /* setup keys before reading the config */
1070 TAILQ_INIT(&global_map.m);
1071 global_map.unhandled_input = global_key_unbound;
1072 TAILQ_INIT(&minibuffer_map.m);
1074 config_init();
1075 parseconfig(path, fail);
1076 if (configtest){
1077 puts("config OK");
1078 exit(0);
1081 fs_init();
1082 if ((sessionfd = lock_session()) == -1)
1083 errx(1, "can't lock session, is another instance of "
1084 "telescope already running?");
1086 /* Start children. */
1087 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1088 err(1, "socketpair");
1089 start_child(PROC_FS, argv0, pipe2fs[1]);
1090 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1091 iev_fs = &fs_ibuf;
1092 iev_fs->handler = handle_dispatch_imsg;
1094 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1095 err(1, "socketpair");
1096 start_child(PROC_NET, argv0, pipe2net[1]);
1097 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1098 iev_net = &net_ibuf;
1099 iev_net->handler = handle_dispatch_imsg;
1101 setproctitle("ui");
1103 /* initialize tofu & load certificates */
1104 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1105 load_certs(&certs);
1107 event_init();
1109 /* Setup event handlers for pipes to fs/net */
1110 iev_fs->events = EV_READ;
1111 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1112 iev_fs->handler, iev_fs);
1113 event_add(&iev_fs->ev, NULL);
1115 iev_net->events = EV_READ;
1116 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1117 iev_net->handler, iev_net);
1118 event_add(&iev_net->ev, NULL);
1120 if (ui_init()) {
1121 load_last_session();
1122 if (has_url || TAILQ_EMPTY(&tabshead))
1123 new_tab(url, NULL);
1125 sandbox_ui_process();
1126 ui_main_loop();
1127 ui_end();
1130 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1131 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1132 imsg_flush(&iev_fs->ibuf);
1133 imsg_flush(&iev_net->ibuf);
1135 close(sessionfd);
1137 return 0;