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 <sys/socket.h>
19 #include <errno.h>
20 #include <getopt.h>
21 #include <limits.h>
22 #include <signal.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
28 #include "defaults.h"
29 #include "parser.h"
30 #include "telescope.h"
31 #include "ui.h"
33 static struct option longopts[] = {
34 {"colors", no_argument, NULL, 'c'},
35 {"help", no_argument, NULL, 'h'},
36 {"version", no_argument, NULL, 'v'},
37 {NULL, 0, NULL, 0},
38 };
40 static const char *opts = "Cc:hnT:v";
42 static struct imsgev *iev_fs, *iev_net;
44 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
45 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
47 enum telescope_process {
48 PROC_UI,
49 PROC_FS,
50 PROC_NET,
51 };
53 /* the first is also the fallback one */
54 static struct proto protos[] = {
55 { "gemini", load_gemini_url },
56 { "about", load_about_url },
57 { NULL, NULL },
58 };
61 #define CANNOT_FETCH 0
62 #define TOO_MUCH_REDIRECTS 1
63 #define MALFORMED_RESPONSE 2
64 #define UNKNOWN_TYPE_OR_CSET 3
65 #define UNKNOWN_PROTOCOL 4
67 /* XXX: keep in sync with telescope.c:/^normalize_code/ */
68 const char *err_pages[70] = {
69 [CANNOT_FETCH] = "# Couldn't load the page\n",
70 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
71 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
72 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
73 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
75 [10] = "# Input required\n",
76 [11] = "# Input required\n",
77 [40] = "# Temporary failure\n",
78 [41] = "# Server unavailable\n",
79 [42] = "# CGI error\n",
80 [43] = "# Proxy error\n",
81 [44] = "# Slow down\n",
82 [50] = "# Permanent failure\n",
83 [51] = "# Not found\n",
84 [52] = "# Gone\n",
85 [53] = "# Proxy request refused\n",
86 [59] = "# Bad request\n",
87 [60] = "# Client certificate required\n",
88 [61] = "# Certificate not authorised\n",
89 [62] = "# Certificate not valid\n"
90 };
92 static void die(void) __attribute__((__noreturn__));
93 static struct tab *tab_by_id(uint32_t);
94 static void handle_imsg_err(struct imsg*, size_t);
95 static void handle_imsg_check_cert(struct imsg*, size_t);
96 static void handle_check_cert_user_choice(int, struct tab *);
97 static void handle_maybe_save_new_cert(int, struct tab *);
98 static void handle_imsg_got_code(struct imsg*, size_t);
99 static void handle_imsg_got_meta(struct imsg*, size_t);
100 static void handle_maybe_save_page(int, struct tab *);
101 static void handle_save_page_path(const char *, struct tab *);
102 static void handle_imsg_file_opened(struct imsg*, size_t);
103 static void handle_imsg_buf(struct imsg*, size_t);
104 static void handle_imsg_eof(struct imsg*, size_t);
105 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
106 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
107 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
108 static void handle_dispatch_imsg(int, short, void*);
109 static void load_page_from_str(struct tab*, const char*);
110 static int do_load_url(struct tab*, const char *, const char *);
111 static void parse_session_line(char *, const char **, uint32_t *);
112 static void load_last_session(void);
113 static pid_t start_child(enum telescope_process, const char *, int);
114 static int ui_send_net(int, uint32_t, const void *, uint16_t);
115 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
117 static imsg_handlerfn *handlers[] = {
118 [IMSG_ERR] = handle_imsg_err,
119 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
120 [IMSG_GOT_CODE] = handle_imsg_got_code,
121 [IMSG_GOT_META] = handle_imsg_got_meta,
122 [IMSG_BUF] = handle_imsg_buf,
123 [IMSG_EOF] = handle_imsg_eof,
124 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
125 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
126 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
127 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
128 };
130 static struct ohash certs;
132 static void __attribute__((__noreturn__))
133 die(void)
135 abort(); /* TODO */
138 static struct tab *
139 tab_by_id(uint32_t id)
141 struct tab *t;
143 TAILQ_FOREACH(t, &tabshead, tabs) {
144 if (t->id == id)
145 return t;
148 return NULL;
151 static void
152 handle_imsg_err(struct imsg *imsg, size_t datalen)
154 struct tab *tab;
155 char *page;
157 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
158 return;
160 page = imsg->data;
161 page[datalen-1] = '\0';
163 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
164 tab->hist_cur->h, page) == -1)
165 die();
166 load_page_from_str(tab, page);
167 free(page);
170 static void
171 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
173 const char *hash, *host, *port;
174 int tofu_res;
175 struct tofu_entry *e;
176 struct tab *tab;
178 hash = imsg->data;
179 if (hash[datalen-1] != '\0')
180 abort();
182 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
183 return;
185 if (tab->proxy != NULL) {
186 host = tab->proxy->host;
187 port = tab->proxy->port;
188 } else {
189 host = tab->uri.host;
190 port = tab->uri.port;
193 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
194 /* TODO: an update in libressl/libretls changed
195 * significantly. Find a better approach at storing
196 * the certs! */
197 if (datalen > sizeof(e->hash))
198 abort();
200 tofu_res = 1; /* trust on first use */
201 if ((e = calloc(1, sizeof(*e))) == NULL)
202 abort();
203 strlcpy(e->domain, host, sizeof(e->domain));
204 if (*port != '\0' && strcmp(port, "1965")) {
205 strlcat(e->domain, ":", sizeof(e->domain));
206 strlcat(e->domain, port, sizeof(e->domain));
208 strlcpy(e->hash, hash, sizeof(e->hash));
209 tofu_add(&certs, e);
210 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
211 } else
212 tofu_res = !strcmp(hash, e->hash);
214 if (tofu_res) {
215 if (e->verified == -1)
216 tab->trust = TS_TEMP_TRUSTED;
217 else if (e->verified == 1)
218 tab->trust = TS_VERIFIED;
219 else
220 tab->trust = TS_TRUSTED;
222 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
223 &tofu_res, sizeof(tofu_res));
224 } else {
225 tab->trust = TS_UNTRUSTED;
226 load_page_from_str(tab, "# Certificate mismatch\n");
227 if ((tab->cert = strdup(hash)) == NULL)
228 die();
229 ui_yornp("Certificate mismatch. Proceed?",
230 handle_check_cert_user_choice, tab);
234 static void
235 handle_check_cert_user_choice(int accept, struct tab *tab)
237 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
238 sizeof(accept));
240 if (accept) {
241 /*
242 * trust the certificate for this session only. If
243 * the page results in a redirect while we're asking
244 * the user to save, we'll end up with an invalid
245 * tabid (one request == one tab id) and crash. It
246 * also makes sense to save it for the current session
247 * if the user accepted it.
248 */
249 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
251 ui_yornp("Save the new certificate?",
252 handle_maybe_save_new_cert, tab);
253 } else {
254 free(tab->cert);
255 tab->cert = NULL;
259 static void
260 handle_maybe_save_new_cert(int accept, struct tab *tab)
262 struct tofu_entry *e;
263 const char *host, *port;
265 if (tab->proxy != NULL) {
266 host = tab->proxy->host;
267 port = tab->proxy->port;
268 } else {
269 host = tab->uri.host;
270 port = tab->uri.port;
273 if (!accept)
274 goto end;
276 if ((e = calloc(1, sizeof(*e))) == NULL)
277 die();
279 strlcpy(e->domain, host, sizeof(e->domain));
280 if (*port != '\0' && strcmp(port, "1965")) {
281 strlcat(e->domain, ":", sizeof(e->domain));
282 strlcat(e->domain, port, sizeof(e->domain));
284 strlcpy(e->hash, tab->cert, sizeof(e->hash));
285 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
287 tofu_update(&certs, e);
289 tab->trust = TS_TRUSTED;
291 end:
292 free(tab->cert);
293 tab->cert = NULL;
296 static inline int
297 normalize_code(int n)
299 if (n < 20) {
300 if (n == 10 || n == 11)
301 return n;
302 return 10;
303 } else if (n < 30) {
304 return 20;
305 } else if (n < 40) {
306 if (n == 30 || n == 31)
307 return n;
308 return 30;
309 } else if (n < 50) {
310 if (n <= 44)
311 return n;
312 return 40;
313 } else if (n < 60) {
314 if (n <= 53 || n == 59)
315 return n;
316 return 50;
317 } else if (n < 70) {
318 if (n <= 62)
319 return n;
320 return 60;
321 } else
322 return MALFORMED_RESPONSE;
325 static void
326 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
328 struct tab *tab;
330 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
331 return;
333 if (sizeof(tab->code) != datalen)
334 die();
336 memcpy(&tab->code, imsg->data, sizeof(tab->code));
337 tab->code = normalize_code(tab->code);
338 if (tab->code != 30 && tab->code != 31)
339 tab->redirect_count = 0;
342 static void
343 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
345 struct tab *tab;
347 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
348 return;
350 if (sizeof(tab->meta) <= datalen)
351 die();
353 memcpy(tab->meta, imsg->data, datalen);
355 if (tab->code < 10) { /* internal errors */
356 load_page_from_str(tab, err_pages[tab->code]);
357 } else if (tab->code < 20) { /* 1x */
358 load_page_from_str(tab, err_pages[tab->code]);
359 ui_require_input(tab, tab->code == 11);
360 } else if (tab->code == 20) {
361 if (setup_parser_for(tab)) {
362 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
363 } else {
364 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
365 ui_yornp("Can't display page, wanna save?",
366 handle_maybe_save_page, tab);
368 } else if (tab->code < 40) { /* 3x */
369 tab->redirect_count++;
371 /* TODO: make customizable? */
372 if (tab->redirect_count > 5) {
373 load_page_from_str(tab,
374 err_pages[TOO_MUCH_REDIRECTS]);
375 } else
376 do_load_url(tab, tab->meta, NULL);
377 } else { /* 4x, 5x & 6x */
378 load_page_from_str(tab, err_pages[tab->code]);
382 static void
383 handle_maybe_save_page(int dosave, struct tab *tab)
385 if (dosave)
386 ui_read("Save to path", handle_save_page_path, tab);
387 else
388 stop_tab(tab);
391 static void
392 handle_save_page_path(const char *path, struct tab *tab)
394 if (path == NULL) {
395 stop_tab(tab);
396 return;
399 tab->path = strdup(path);
401 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
404 static void
405 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
407 struct tab *tab;
408 char *page;
409 const char *e;
410 int l;
412 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
413 if (imsg->fd != -1)
414 close(imsg->fd);
415 return;
418 if (imsg->fd == -1) {
419 stop_tab(tab);
421 e = imsg->data;
422 if (e[datalen-1] != '\0')
423 die();
424 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
425 tab->path, e);
426 if (l == -1)
427 die();
428 load_page_from_str(tab, page);
429 free(page);
430 } else {
431 tab->fd = imsg->fd;
432 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
436 static void
437 handle_imsg_buf(struct imsg *imsg, size_t datalen)
439 struct tab *tab;
440 int l;
441 char *page, buf[FMT_SCALED_STRSIZE] = {0};
443 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
444 return;
446 tab->bytes += datalen;
447 if (tab->fd == -1) {
448 if (!tab->buffer.page.parse(&tab->buffer.page,
449 imsg->data, datalen))
450 die();
451 } else {
452 write(tab->fd, imsg->data, datalen);
453 fmt_scaled(tab->bytes, buf);
454 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
455 tab->path,
456 buf);
457 if (l == -1)
458 die();
459 load_page_from_str(tab, page);
460 free(page);
463 ui_on_tab_refresh(tab);
466 static void
467 handle_imsg_eof(struct imsg *imsg, size_t datalen)
469 struct tab *tab;
470 int l;
471 char *page, buf[FMT_SCALED_STRSIZE] = {0};
473 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
474 return;
476 if (tab->fd == -1) {
477 if (!tab->buffer.page.free(&tab->buffer.page))
478 die();
479 } else {
480 fmt_scaled(tab->bytes, buf);
481 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
482 tab->path,
483 buf);
484 if (l == -1)
485 die();
486 load_page_from_str(tab, page);
487 free(page);
489 close(tab->fd);
490 tab->fd = -1;
491 free(tab->path);
492 tab->path = NULL;
495 ui_on_tab_refresh(tab);
496 ui_on_tab_loaded(tab);
499 static void
500 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
502 int res;
504 if (datalen != sizeof(res))
505 die();
507 memcpy(&res, imsg->data, sizeof(res));
508 if (res == 0)
509 message("Added to bookmarks!");
510 else
511 message("Failed to add to bookmarks: %s",
512 strerror(res));
515 static void
516 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
518 int res;
520 if (datalen != sizeof(res))
521 die();
522 memcpy(&res, imsg->data, datalen);
523 if (res != 0)
524 message("Failed to save the cert for: %s",
525 strerror(res));
528 static void
529 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
531 int res;
533 if (datalen != sizeof(res))
534 die();
535 memcpy(&res, imsg->data, datalen);
536 if (!res)
537 message("Failed to update the certificate");
540 static void
541 handle_dispatch_imsg(int fd, short ev, void *d)
543 struct imsgev *iev = d;
545 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
546 err(1, "connection closed");
549 static void
550 load_page_from_str(struct tab *tab, const char *page)
552 erase_buffer(&tab->buffer);
553 gemtext_initparser(&tab->buffer.page);
554 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
555 die();
556 if (!tab->buffer.page.free(&tab->buffer.page))
557 die();
558 ui_on_tab_refresh(tab);
559 ui_on_tab_loaded(tab);
562 void
563 load_about_url(struct tab *tab, const char *url)
565 tab->trust = TS_VERIFIED;
567 gemtext_initparser(&tab->buffer.page);
569 ui_send_fs(IMSG_GET, tab->id,
570 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
573 void
574 load_gemini_url(struct tab *tab, const char *url)
576 struct get_req req;
578 stop_tab(tab);
579 tab->id = tab_new_id();
581 memset(&req, 0, sizeof(req));
582 strlcpy(req.host, tab->uri.host, sizeof(req.host));
583 strlcpy(req.port, tab->uri.port, sizeof(req.host));
585 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
586 strlcat(req.req, "\r\n", sizeof(req.req));
588 req.proto = PROTO_GEMINI;
590 ui_send_net(IMSG_GET_RAW, tab->id,
591 &req, sizeof(req));
594 void
595 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
597 struct get_req req;
599 stop_tab(tab);
600 tab->id = tab_new_id();
601 tab->proxy = p;
603 memset(&req, 0, sizeof(req));
604 strlcpy(req.host, p->host, sizeof(req.host));
605 strlcpy(req.port, p->port, sizeof(req.host));
607 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
608 strlcat(req.req, "\r\n", sizeof(req.req));
610 req.proto = p->proto;
612 ui_send_net(IMSG_GET_RAW, tab->id,
613 &req, sizeof(req));
616 /*
617 * Effectively load the given url in the given tab. Return 1 when
618 * loading the page asynchronously, and thus when an erase_buffer can
619 * be done right after this function return, or 0 when loading the
620 * page synchronously. In this last case, erase_buffer *MUST* be
621 * called by the handling function (such as load_page_from_str).
622 */
623 static int
624 do_load_url(struct tab *tab, const char *url, const char *base)
626 struct phos_uri uri;
627 struct proto *p;
628 struct proxy *proxy;
629 char *t;
631 tab->proxy = NULL;
633 if (tab->fd != -1) {
634 close(tab->fd);
635 tab->fd = -1;
636 free(tab->path);
637 tab->path = NULL;
640 tab->trust = TS_UNKNOWN;
642 if (base == NULL)
643 memcpy(&uri, &tab->uri, sizeof(tab->uri));
644 else
645 phos_parse_absolute_uri(base, &uri);
647 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
648 if (asprintf(&t, "#error loading %s\n>%s\n",
649 url, "Can't parse the URI") == -1)
650 die();
651 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
652 load_page_from_str(tab, t);
653 free(t);
654 return 0;
657 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
658 sizeof(tab->hist_cur->h));
660 for (p = protos; p->schema != NULL; ++p) {
661 if (!strcmp(tab->uri.scheme, p->schema)) {
662 p->loadfn(tab, url);
663 return 1;
667 TAILQ_FOREACH(proxy, &proxies, proxies) {
668 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
669 load_via_proxy(tab, url, proxy);
670 return 1;
674 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
675 return 0;
678 /*
679 * Load url in tab. If tab is marked as lazy, only prepare the url
680 * but don't load it. If tab is lazy and a url was already prepared,
681 * do load it!
682 */
683 void
684 load_url(struct tab *tab, const char *url, const char *base)
686 int lazy;
688 lazy = tab->flags & TAB_LAZY;
690 if (lazy && tab->hist_cur != NULL) {
691 lazy = 0;
692 tab->flags &= ~TAB_LAZY;
695 if (!lazy || tab->hist_cur == NULL) {
696 if (tab->hist_cur != NULL)
697 hist_clear_forward(&tab->hist,
698 TAILQ_NEXT(tab->hist_cur, entries));
700 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
701 event_loopbreak();
702 return;
705 strlcpy(tab->buffer.page.title, url,
706 sizeof(tab->buffer.page.title));
707 hist_push(&tab->hist, tab->hist_cur);
709 if (lazy)
710 strlcpy(tab->hist_cur->h, url,
711 sizeof(tab->hist_cur->h));
714 if (!lazy && do_load_url(tab, url, base))
715 erase_buffer(&tab->buffer);
718 int
719 load_previous_page(struct tab *tab)
721 struct hist *h;
723 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
724 return 0;
725 tab->hist_cur = h;
726 do_load_url(tab, h->h, NULL);
727 return 1;
730 int
731 load_next_page(struct tab *tab)
733 struct hist *h;
735 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
736 return 0;
737 tab->hist_cur = h;
738 do_load_url(tab, h->h, NULL);
739 return 1;
742 /*
743 * Free every resource linked to the tab, including the tab itself.
744 * Removes the tab from the tablist, but doesn't update the
745 * current_tab though.
746 */
747 void
748 free_tab(struct tab *tab)
750 stop_tab(tab);
752 if (evtimer_pending(&tab->loadingev, NULL))
753 evtimer_del(&tab->loadingev);
755 TAILQ_REMOVE(&tabshead, tab, tabs);
756 free(tab);
759 void
760 stop_tab(struct tab *tab)
762 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
764 if (tab->fd != -1) {
765 close(tab->fd);
766 tab->fd = -1;
767 free(tab->path);
768 tab->path = NULL;
769 load_page_from_str(tab, "Stopped.\n");
773 void
774 add_to_bookmarks(const char *str)
776 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
777 str, strlen(str)+1);
780 void
781 save_session(void)
783 struct tab *tab;
784 char *t;
785 int flags;
787 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
789 TAILQ_FOREACH(tab, &tabshead, tabs) {
790 flags = tab->flags;
791 if (tab == current_tab)
792 flags |= TAB_CURRENT;
794 t = tab->hist_cur->h;
795 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
797 t = tab->buffer.page.title;
798 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
801 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
804 /*
805 * Parse a line of the session file. The format is:
807 * URL [flags,...] [title]\n
808 */
809 static void
810 parse_session_line(char *line, const char **title, uint32_t *flags)
812 char *s, *t, *ap;
814 *title = "";
815 *flags = 0;
816 if ((s = strchr(line, ' ')) == NULL)
817 return;
819 *s++ = '\0';
821 if ((t = strchr(s, ' ')) != NULL) {
822 *t++ = '\0';
823 *title = t;
826 while ((ap = strsep(&s, ",")) != NULL) {
827 if (*ap == '\0')
829 else if (!strcmp(ap, "current"))
830 *flags |= TAB_CURRENT;
831 else
832 message("unknown tab flag: %s", ap);
836 static void
837 load_last_session(void)
839 const char *title;
840 char *nl, *line = NULL;
841 uint32_t flags;
842 size_t linesize = 0;
843 ssize_t linelen;
844 FILE *session;
845 struct tab *tab, *curr = NULL;
847 if ((session = fopen(session_file, "r")) == NULL) {
848 /* first time? */
849 new_tab("about:new", NULL);
850 switch_to_tab(new_tab("about:help", NULL));
851 return;
854 while ((linelen = getline(&line, &linesize, session)) != -1) {
855 if ((nl = strchr(line, '\n')) != NULL)
856 *nl = '\0';
857 parse_session_line(line, &title, &flags);
858 if ((tab = new_tab(line, NULL)) == NULL)
859 err(1, "new_tab");
860 strlcpy(tab->buffer.page.title, title,
861 sizeof(tab->buffer.page.title));
862 if (flags & TAB_CURRENT)
863 curr = tab;
866 if (ferror(session))
867 message("error reading %s: %s",
868 session_file, strerror(errno));
869 fclose(session);
870 free(line);
872 if (curr != NULL)
873 switch_to_tab(curr);
875 if (last_time_crashed())
876 switch_to_tab(new_tab("about:crash", NULL));
878 return;
881 static pid_t
882 start_child(enum telescope_process p, const char *argv0, int fd)
884 const char *argv[4];
885 int argc = 0;
886 pid_t pid;
888 switch (pid = fork()) {
889 case -1:
890 die();
891 case 0:
892 break;
893 default:
894 close(fd);
895 return pid;
898 if (dup2(fd, 3) == -1)
899 err(1, "cannot setup imsg fd");
901 argv[argc++] = argv0;
902 switch (p) {
903 case PROC_UI:
904 errx(1, "Can't start ui process");
905 case PROC_FS:
906 argv[argc++] = "-Tf";
907 break;
908 case PROC_NET:
909 argv[argc++] = "-Tn";
910 break;
913 argv[argc++] = NULL;
914 execvp(argv0, (char *const *)argv);
915 err(1, "execvp(%s)", argv0);
918 static int
919 ui_send_net(int type, uint32_t peerid, const void *data,
920 uint16_t datalen)
922 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
923 datalen);
926 static int
927 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
929 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
930 datalen);
933 static void __attribute__((noreturn))
934 usage(int r)
936 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
937 getprogname());
938 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
939 exit(r);
942 int
943 main(int argc, char * const *argv)
945 struct imsgev net_ibuf, fs_ibuf;
946 int pipe2net[2], pipe2fs[2];
947 int ch, configtest = 0, fail = 0;
948 int has_url = 0;
949 int proc = -1;
950 int sessionfd;
951 char path[PATH_MAX];
952 const char *url = NEW_TAB_URL;
953 const char *argv0;
955 argv0 = argv[0];
957 signal(SIGCHLD, SIG_IGN);
958 signal(SIGPIPE, SIG_IGN);
960 if (getenv("NO_COLOR") != NULL)
961 enable_colors = 0;
963 strlcpy(path, getenv("HOME"), sizeof(path));
964 strlcat(path, "/.telescope/config", sizeof(path));
966 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
967 switch (ch) {
968 case 'C':
969 exit(ui_print_colors());
970 case 'c':
971 fail = 1;
972 strlcpy(path, optarg, sizeof(path));
973 break;
974 case 'n':
975 configtest = 1;
976 break;
977 case 'h':
978 usage(0);
979 case 'T':
980 switch (*optarg) {
981 case 'f':
982 proc = PROC_FS;
983 break;
984 case 'n':
985 proc = PROC_NET;
986 break;
987 default:
988 errx(1, "invalid process spec %c",
989 *optarg);
991 break;
992 case 'v':
993 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
994 exit(0);
995 break;
996 default:
997 usage(1);
1001 argc -= optind;
1002 argv += optind;
1004 if (proc != -1) {
1005 if (argc > 0)
1006 usage(1);
1007 else if (proc == PROC_FS)
1008 return fs_main();
1009 else if (proc == PROC_NET)
1010 return client_main();
1011 else
1012 usage(1);
1015 if (argc != 0) {
1016 has_url = 1;
1017 url = argv[0];
1020 /* setup keys before reading the config */
1021 TAILQ_INIT(&global_map.m);
1022 global_map.unhandled_input = global_key_unbound;
1023 TAILQ_INIT(&minibuffer_map.m);
1025 config_init();
1026 parseconfig(path, fail);
1027 if (configtest){
1028 puts("config OK");
1029 exit(0);
1032 fs_init();
1033 if ((sessionfd = lock_session()) == -1)
1034 errx(1, "can't lock session, is another instance of "
1035 "telescope already running?");
1037 /* Start children. */
1038 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1039 err(1, "socketpair");
1040 start_child(PROC_FS, argv0, pipe2fs[1]);
1041 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1042 iev_fs = &fs_ibuf;
1043 iev_fs->handler = handle_dispatch_imsg;
1045 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1046 err(1, "socketpair");
1047 start_child(PROC_NET, argv0, pipe2net[1]);
1048 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1049 iev_net = &net_ibuf;
1050 iev_net->handler = handle_dispatch_imsg;
1052 setproctitle("ui");
1054 /* initialize tofu & load certificates */
1055 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1056 load_certs(&certs);
1058 event_init();
1060 /* Setup event handlers for pipes to fs/net */
1061 iev_fs->events = EV_READ;
1062 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1063 iev_fs->handler, iev_fs);
1064 event_add(&iev_fs->ev, NULL);
1066 iev_net->events = EV_READ;
1067 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1068 iev_net->handler, iev_net);
1069 event_add(&iev_net->ev, NULL);
1071 if (ui_init()) {
1072 load_last_session();
1073 if (has_url || TAILQ_EMPTY(&tabshead))
1074 new_tab(url, NULL);
1076 sandbox_ui_process();
1077 ui_main_loop();
1078 ui_end();
1081 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1082 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1083 imsg_flush(&iev_fs->ibuf);
1084 imsg_flush(&iev_net->ibuf);
1086 close(sessionfd);
1088 return 0;