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 void
743 stop_tab(struct tab *tab)
745 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
747 if (tab->fd != -1) {
748 close(tab->fd);
749 tab->fd = -1;
750 free(tab->path);
751 tab->path = NULL;
752 load_page_from_str(tab, "Stopped.\n");
756 void
757 add_to_bookmarks(const char *str)
759 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
760 str, strlen(str)+1);
763 void
764 save_session(void)
766 struct tab *tab;
767 char *t;
768 int flags;
770 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
772 TAILQ_FOREACH(tab, &tabshead, tabs) {
773 flags = tab->flags;
774 if (tab == current_tab)
775 flags |= TAB_CURRENT;
777 t = tab->hist_cur->h;
778 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
780 t = tab->buffer.page.title;
781 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
784 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
787 /*
788 * Parse a line of the session file. The format is:
790 * URL [flags,...] [title]\n
791 */
792 static void
793 parse_session_line(char *line, const char **title, uint32_t *flags)
795 char *s, *t, *ap;
797 *title = "";
798 *flags = 0;
799 if ((s = strchr(line, ' ')) == NULL)
800 return;
802 *s++ = '\0';
804 if ((t = strchr(s, ' ')) != NULL) {
805 *t++ = '\0';
806 *title = t;
809 while ((ap = strsep(&s, ",")) != NULL) {
810 if (*ap == '\0')
812 else if (!strcmp(ap, "current"))
813 *flags |= TAB_CURRENT;
814 else
815 message("unknown tab flag: %s", ap);
819 static void
820 load_last_session(void)
822 const char *title;
823 char *nl, *line = NULL;
824 uint32_t flags;
825 size_t linesize = 0;
826 ssize_t linelen;
827 FILE *session;
828 struct tab *tab, *curr = NULL;
830 if ((session = fopen(session_file, "r")) == NULL) {
831 /* first time? */
832 new_tab("about:new", NULL);
833 switch_to_tab(new_tab("about:help", NULL));
834 return;
837 while ((linelen = getline(&line, &linesize, session)) != -1) {
838 if ((nl = strchr(line, '\n')) != NULL)
839 *nl = '\0';
840 parse_session_line(line, &title, &flags);
841 if ((tab = new_tab(line, NULL)) == NULL)
842 err(1, "new_tab");
843 strlcpy(tab->buffer.page.title, title,
844 sizeof(tab->buffer.page.title));
845 if (flags & TAB_CURRENT)
846 curr = tab;
849 if (ferror(session))
850 message("error reading %s: %s",
851 session_file, strerror(errno));
852 fclose(session);
853 free(line);
855 if (curr != NULL)
856 switch_to_tab(curr);
858 if (last_time_crashed())
859 switch_to_tab(new_tab("about:crash", NULL));
861 return;
864 static pid_t
865 start_child(enum telescope_process p, const char *argv0, int fd)
867 const char *argv[4];
868 int argc = 0;
869 pid_t pid;
871 switch (pid = fork()) {
872 case -1:
873 die();
874 case 0:
875 break;
876 default:
877 close(fd);
878 return pid;
881 if (dup2(fd, 3) == -1)
882 err(1, "cannot setup imsg fd");
884 argv[argc++] = argv0;
885 switch (p) {
886 case PROC_UI:
887 errx(1, "Can't start ui process");
888 case PROC_FS:
889 argv[argc++] = "-Tf";
890 break;
891 case PROC_NET:
892 argv[argc++] = "-Tn";
893 break;
896 argv[argc++] = NULL;
897 execvp(argv0, (char *const *)argv);
898 err(1, "execvp(%s)", argv0);
901 static int
902 ui_send_net(int type, uint32_t peerid, const void *data,
903 uint16_t datalen)
905 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
906 datalen);
909 static int
910 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
912 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
913 datalen);
916 static void __attribute__((noreturn))
917 usage(int r)
919 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
920 getprogname());
921 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
922 exit(r);
925 int
926 main(int argc, char * const *argv)
928 struct imsgev net_ibuf, fs_ibuf;
929 int pipe2net[2], pipe2fs[2];
930 int ch, configtest = 0, fail = 0;
931 int has_url = 0;
932 int proc = -1;
933 int sessionfd;
934 char path[PATH_MAX];
935 const char *url = NEW_TAB_URL;
936 const char *argv0;
938 argv0 = argv[0];
940 signal(SIGCHLD, SIG_IGN);
941 signal(SIGPIPE, SIG_IGN);
943 if (getenv("NO_COLOR") != NULL)
944 enable_colors = 0;
946 strlcpy(path, getenv("HOME"), sizeof(path));
947 strlcat(path, "/.telescope/config", sizeof(path));
949 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
950 switch (ch) {
951 case 'C':
952 exit(ui_print_colors());
953 case 'c':
954 fail = 1;
955 strlcpy(path, optarg, sizeof(path));
956 break;
957 case 'n':
958 configtest = 1;
959 break;
960 case 'h':
961 usage(0);
962 case 'T':
963 switch (*optarg) {
964 case 'f':
965 proc = PROC_FS;
966 break;
967 case 'n':
968 proc = PROC_NET;
969 break;
970 default:
971 errx(1, "invalid process spec %c",
972 *optarg);
974 break;
975 case 'v':
976 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
977 exit(0);
978 break;
979 default:
980 usage(1);
984 argc -= optind;
985 argv += optind;
987 if (proc != -1) {
988 if (argc > 0)
989 usage(1);
990 else if (proc == PROC_FS)
991 return fs_main();
992 else if (proc == PROC_NET)
993 return client_main();
994 else
995 usage(1);
998 if (argc != 0) {
999 has_url = 1;
1000 url = argv[0];
1003 /* setup keys before reading the config */
1004 TAILQ_INIT(&global_map.m);
1005 global_map.unhandled_input = global_key_unbound;
1006 TAILQ_INIT(&minibuffer_map.m);
1008 config_init();
1009 parseconfig(path, fail);
1010 if (configtest){
1011 puts("config OK");
1012 exit(0);
1015 fs_init();
1016 if ((sessionfd = lock_session()) == -1)
1017 errx(1, "can't lock session, is another instance of "
1018 "telescope already running?");
1020 /* Start children. */
1021 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1022 err(1, "socketpair");
1023 start_child(PROC_FS, argv0, pipe2fs[1]);
1024 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1025 iev_fs = &fs_ibuf;
1026 iev_fs->handler = handle_dispatch_imsg;
1028 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1029 err(1, "socketpair");
1030 start_child(PROC_NET, argv0, pipe2net[1]);
1031 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1032 iev_net = &net_ibuf;
1033 iev_net->handler = handle_dispatch_imsg;
1035 setproctitle("ui");
1037 /* initialize tofu & load certificates */
1038 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1039 load_certs(&certs);
1041 event_init();
1043 /* Setup event handlers for pipes to fs/net */
1044 iev_fs->events = EV_READ;
1045 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1046 iev_fs->handler, iev_fs);
1047 event_add(&iev_fs->ev, NULL);
1049 iev_net->events = EV_READ;
1050 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1051 iev_net->handler, iev_net);
1052 event_add(&iev_net->ev, NULL);
1054 if (ui_init()) {
1055 load_last_session();
1056 if (has_url || TAILQ_EMPTY(&tabshead))
1057 new_tab(url, NULL);
1059 sandbox_ui_process();
1060 ui_main_loop();
1061 ui_end();
1064 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1065 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1066 imsg_flush(&iev_fs->ibuf);
1067 imsg_flush(&iev_net->ibuf);
1069 close(sessionfd);
1071 return 0;