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*);
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 die();
151 static void
152 handle_imsg_err(struct imsg *imsg, size_t datalen)
154 struct tab *tab;
155 char *page;
157 tab = tab_by_id(imsg->hdr.peerid);
159 page = imsg->data;
160 page[datalen-1] = '\0';
162 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
163 tab->hist_cur->h, page) == -1)
164 die();
165 load_page_from_str(tab, page);
166 free(page);
169 static void
170 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
172 const char *hash, *host, *port;
173 int tofu_res;
174 struct tofu_entry *e;
175 struct tab *tab;
177 hash = imsg->data;
178 if (hash[datalen-1] != '\0')
179 abort();
181 tab = tab_by_id(imsg->hdr.peerid);
183 if (tab->proxy != NULL) {
184 host = tab->proxy->host;
185 port = tab->proxy->port;
186 } else {
187 host = tab->uri.host;
188 port = tab->uri.port;
191 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
192 /* TODO: an update in libressl/libretls changed
193 * significantly. Find a better approach at storing
194 * the certs! */
195 if (datalen > sizeof(e->hash))
196 abort();
198 tofu_res = 1; /* trust on first use */
199 if ((e = calloc(1, sizeof(*e))) == NULL)
200 abort();
201 strlcpy(e->domain, host, sizeof(e->domain));
202 if (*port != '\0' && strcmp(port, "1965")) {
203 strlcat(e->domain, ":", sizeof(e->domain));
204 strlcat(e->domain, port, sizeof(e->domain));
206 strlcpy(e->hash, hash, sizeof(e->hash));
207 tofu_add(&certs, e);
208 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
209 } else
210 tofu_res = !strcmp(hash, e->hash);
212 if (tofu_res) {
213 if (e->verified == -1)
214 tab->trust = TS_TEMP_TRUSTED;
215 else if (e->verified == 1)
216 tab->trust = TS_VERIFIED;
217 else
218 tab->trust = TS_TRUSTED;
220 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
221 &tofu_res, sizeof(tofu_res));
222 } else {
223 tab->trust = TS_UNTRUSTED;
224 load_page_from_str(tab, "# Certificate mismatch\n");
225 if ((tab->cert = strdup(hash)) == NULL)
226 die();
227 ui_yornp("Certificate mismatch. Proceed?",
228 handle_check_cert_user_choice, tab);
232 static void
233 handle_check_cert_user_choice(int accept, struct tab *tab)
235 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
236 sizeof(accept));
238 if (accept) {
239 /*
240 * trust the certificate for this session only. If
241 * the page results in a redirect while we're asking
242 * the user to save, we'll end up with an invalid
243 * tabid (one request == one tab id) and crash. It
244 * also makes sense to save it for the current session
245 * if the user accepted it.
246 */
247 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
249 ui_yornp("Save the new certificate?",
250 handle_maybe_save_new_cert, tab);
251 } else {
252 free(tab->cert);
253 tab->cert = NULL;
257 static void
258 handle_maybe_save_new_cert(int accept, struct tab *tab)
260 struct tofu_entry *e;
261 const char *host, *port;
263 if (tab->proxy != NULL) {
264 host = tab->proxy->host;
265 port = tab->proxy->port;
266 } else {
267 host = tab->uri.host;
268 port = tab->uri.port;
271 if (!accept)
272 goto end;
274 if ((e = calloc(1, sizeof(*e))) == NULL)
275 die();
277 strlcpy(e->domain, host, sizeof(e->domain));
278 if (*port != '\0' && strcmp(port, "1965")) {
279 strlcat(e->domain, ":", sizeof(e->domain));
280 strlcat(e->domain, port, sizeof(e->domain));
282 strlcpy(e->hash, tab->cert, sizeof(e->hash));
283 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
285 tofu_update(&certs, e);
287 tab->trust = TS_TRUSTED;
289 end:
290 free(tab->cert);
291 tab->cert = NULL;
294 static inline int
295 normalize_code(int n)
297 if (n < 20) {
298 if (n == 10 || n == 11)
299 return n;
300 return 10;
301 } else if (n < 30) {
302 return 20;
303 } else if (n < 40) {
304 if (n == 30 || n == 31)
305 return n;
306 return 30;
307 } else if (n < 50) {
308 if (n <= 44)
309 return n;
310 return 40;
311 } else if (n < 60) {
312 if (n <= 53 || n == 59)
313 return n;
314 return 50;
315 } else if (n < 70) {
316 if (n <= 62)
317 return n;
318 return 60;
319 } else
320 return MALFORMED_RESPONSE;
323 static void
324 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
326 struct tab *tab;
328 tab = tab_by_id(imsg->hdr.peerid);
330 if (sizeof(tab->code) != datalen)
331 die();
333 memcpy(&tab->code, imsg->data, sizeof(tab->code));
334 tab->code = normalize_code(tab->code);
335 if (tab->code != 30 && tab->code != 31)
336 tab->redirect_count = 0;
339 static void
340 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
342 struct tab *tab;
344 tab = tab_by_id(imsg->hdr.peerid);
346 if (sizeof(tab->meta) <= datalen)
347 die();
349 memcpy(tab->meta, imsg->data, datalen);
351 if (tab->code < 10) { /* internal errors */
352 load_page_from_str(tab, err_pages[tab->code]);
353 } else if (tab->code < 20) { /* 1x */
354 load_page_from_str(tab, err_pages[tab->code]);
355 ui_require_input(tab, tab->code == 11);
356 } else if (tab->code == 20) {
357 if (setup_parser_for(tab)) {
358 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
359 } else {
360 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
361 ui_yornp("Can't display page, wanna save?",
362 handle_maybe_save_page, tab);
364 } else if (tab->code < 40) { /* 3x */
365 tab->redirect_count++;
367 /* TODO: make customizable? */
368 if (tab->redirect_count > 5) {
369 load_page_from_str(tab,
370 err_pages[TOO_MUCH_REDIRECTS]);
371 } else
372 do_load_url(tab, tab->meta);
373 } else { /* 4x, 5x & 6x */
374 load_page_from_str(tab, err_pages[tab->code]);
378 static void
379 handle_maybe_save_page(int dosave, struct tab *tab)
381 if (dosave)
382 ui_read("Save to path", handle_save_page_path, tab);
383 else
384 stop_tab(tab);
387 static void
388 handle_save_page_path(const char *path, struct tab *tab)
390 if (path == NULL) {
391 stop_tab(tab);
392 return;
395 tab->path = strdup(path);
397 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
400 static void
401 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
403 struct tab *tab;
404 char *page;
405 const char *e;
406 int l;
408 tab = tab_by_id(imsg->hdr.peerid);
410 if (imsg->fd == -1) {
411 stop_tab(tab);
413 e = imsg->data;
414 if (e[datalen-1] != '\0')
415 die();
416 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
417 tab->path, e);
418 if (l == -1)
419 die();
420 load_page_from_str(tab, page);
421 free(page);
422 } else {
423 tab->fd = imsg->fd;
424 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
428 static void
429 handle_imsg_buf(struct imsg *imsg, size_t datalen)
431 struct tab *tab;
432 int l;
433 char *page, buf[FMT_SCALED_STRSIZE] = {0};
435 tab = tab_by_id(imsg->hdr.peerid);
437 tab->bytes += datalen;
438 if (tab->fd == -1) {
439 if (!tab->buffer.page.parse(&tab->buffer.page,
440 imsg->data, datalen))
441 die();
442 } else {
443 write(tab->fd, imsg->data, datalen);
444 fmt_scaled(tab->bytes, buf);
445 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
446 tab->path,
447 buf);
448 if (l == -1)
449 die();
450 load_page_from_str(tab, page);
451 free(page);
454 ui_on_tab_refresh(tab);
457 static void
458 handle_imsg_eof(struct imsg *imsg, size_t datalen)
460 struct tab *tab;
461 int l;
462 char *page, buf[FMT_SCALED_STRSIZE] = {0};
464 tab = tab_by_id(imsg->hdr.peerid);
466 if (tab->fd == -1) {
467 if (!tab->buffer.page.free(&tab->buffer.page))
468 die();
469 } else {
470 fmt_scaled(tab->bytes, buf);
471 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
472 tab->path,
473 buf);
474 if (l == -1)
475 die();
476 load_page_from_str(tab, page);
477 free(page);
479 close(tab->fd);
480 tab->fd = -1;
481 free(tab->path);
482 tab->path = NULL;
485 ui_on_tab_refresh(tab);
486 ui_on_tab_loaded(tab);
489 static void
490 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
492 int res;
494 if (datalen != sizeof(res))
495 die();
497 memcpy(&res, imsg->data, sizeof(res));
498 if (res == 0)
499 message("Added to bookmarks!");
500 else
501 message("Failed to add to bookmarks: %s",
502 strerror(res));
505 static void
506 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
508 int res;
510 if (datalen != sizeof(res))
511 die();
512 memcpy(&res, imsg->data, datalen);
513 if (res != 0)
514 message("Failed to save the cert for: %s",
515 strerror(res));
518 static void
519 handle_imsg_update_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)
527 message("Failed to update the certificate");
530 static void
531 handle_dispatch_imsg(int fd, short ev, void *d)
533 struct imsgev *iev = d;
534 dispatch_imsg(iev, ev, handlers, sizeof(handlers));
537 static void
538 load_page_from_str(struct tab *tab, const char *page)
540 erase_buffer(&tab->buffer);
541 gemtext_initparser(&tab->buffer.page);
542 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
543 die();
544 if (!tab->buffer.page.free(&tab->buffer.page))
545 die();
546 ui_on_tab_refresh(tab);
547 ui_on_tab_loaded(tab);
550 void
551 load_about_url(struct tab *tab, const char *url)
553 tab->trust = TS_VERIFIED;
555 gemtext_initparser(&tab->buffer.page);
557 ui_send_fs(IMSG_GET, tab->id,
558 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
561 void
562 load_gemini_url(struct tab *tab, const char *url)
564 struct get_req req;
566 stop_tab(tab);
567 tab->id = tab_new_id();
569 memset(&req, 0, sizeof(req));
570 strlcpy(req.host, tab->uri.host, sizeof(req.host));
571 strlcpy(req.port, tab->uri.port, sizeof(req.host));
573 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
574 strlcat(req.req, "\r\n", sizeof(req.req));
576 req.proto = PROTO_GEMINI;
578 ui_send_net(IMSG_GET_RAW, tab->id,
579 &req, sizeof(req));
582 void
583 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
585 struct get_req req;
587 stop_tab(tab);
588 tab->id = tab_new_id();
589 tab->proxy = p;
591 memset(&req, 0, sizeof(req));
592 strlcpy(req.host, p->host, sizeof(req.host));
593 strlcpy(req.port, p->port, sizeof(req.host));
595 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
596 strlcat(req.req, "\r\n", sizeof(req.req));
598 req.proto = p->proto;
600 ui_send_net(IMSG_GET_RAW, tab->id,
601 &req, sizeof(req));
604 /*
605 * Effectively load the given url in the given tab. Return 1 when
606 * loading the page asynchronously, and thus when an erase_buffer can
607 * be done right after this function return, or 0 when loading the
608 * page synchronously. In this last case, erase_buffer *MUST* be
609 * called by the handling function (such as load_page_from_str).
610 */
611 static int
612 do_load_url(struct tab *tab, const char *url)
614 struct phos_uri uri;
615 struct proto *p;
616 struct proxy *proxy;
617 char *t;
619 tab->proxy = NULL;
621 if (tab->fd != -1) {
622 close(tab->fd);
623 tab->fd = -1;
624 free(tab->path);
625 tab->path = NULL;
628 tab->trust = TS_UNKNOWN;
630 memcpy(&uri, &tab->uri, sizeof(tab->uri));
631 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
632 if (asprintf(&t, "#error loading %s\n>%s\n",
633 url, "Can't parse the URI") == -1)
634 die();
635 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
636 load_page_from_str(tab, t);
637 free(t);
638 return 0;
641 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
642 sizeof(tab->hist_cur->h));
644 for (p = protos; p->schema != NULL; ++p) {
645 if (!strcmp(tab->uri.scheme, p->schema)) {
646 p->loadfn(tab, url);
647 return 1;
651 TAILQ_FOREACH(proxy, &proxies, proxies) {
652 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
653 load_via_proxy(tab, url, proxy);
654 return 1;
658 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
659 return 0;
662 /*
663 * Load url in tab. If tab is marked as lazy, only prepare the url
664 * but don't load it. If tab is lazy and a url was already prepared,
665 * do load it!
666 */
667 void
668 load_url(struct tab *tab, const char *url)
670 int lazy;
672 lazy = tab->flags & TAB_LAZY;
674 if (lazy && tab->hist_cur != NULL) {
675 lazy = 0;
676 tab->flags &= ~TAB_LAZY;
679 if (!lazy || tab->hist_cur == NULL) {
680 if (tab->hist_cur != NULL)
681 hist_clear_forward(&tab->hist,
682 TAILQ_NEXT(tab->hist_cur, entries));
684 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
685 event_loopbreak();
686 return;
689 strlcpy(tab->buffer.page.title, url,
690 sizeof(tab->buffer.page.title));
691 hist_push(&tab->hist, tab->hist_cur);
693 if (lazy)
694 strlcpy(tab->hist_cur->h, url,
695 sizeof(tab->hist_cur->h));
698 if (!lazy && do_load_url(tab, url))
699 erase_buffer(&tab->buffer);
702 int
703 load_previous_page(struct tab *tab)
705 struct hist *h;
707 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
708 return 0;
709 tab->hist_cur = h;
710 do_load_url(tab, h->h);
711 return 1;
714 int
715 load_next_page(struct tab *tab)
717 struct hist *h;
719 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
720 return 0;
721 tab->hist_cur = h;
722 do_load_url(tab, h->h);
723 return 1;
726 void
727 stop_tab(struct tab *tab)
729 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
731 if (tab->fd != -1) {
732 close(tab->fd);
733 tab->fd = -1;
734 free(tab->path);
735 tab->path = NULL;
736 load_page_from_str(tab, "Stopped.\n");
740 void
741 add_to_bookmarks(const char *str)
743 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
744 str, strlen(str)+1);
747 void
748 save_session(void)
750 struct tab *tab;
751 char *t;
752 int flags;
754 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
756 TAILQ_FOREACH(tab, &tabshead, tabs) {
757 flags = tab->flags;
758 if (tab == current_tab)
759 flags |= TAB_CURRENT;
761 t = tab->hist_cur->h;
762 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
764 t = tab->buffer.page.title;
765 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
768 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
771 /*
772 * Parse a line of the session file. The format is:
774 * URL [flags,...] [title]\n
775 */
776 static void
777 parse_session_line(char *line, const char **title, uint32_t *flags)
779 char *s, *t, *ap;
781 *title = "";
782 *flags = 0;
783 if ((s = strchr(line, ' ')) == NULL)
784 return;
786 *s++ = '\0';
788 if ((t = strchr(s, ' ')) != NULL) {
789 *t++ = '\0';
790 *title = t;
793 while ((ap = strsep(&s, ",")) != NULL) {
794 if (*ap == '\0')
796 else if (!strcmp(ap, "current"))
797 *flags |= TAB_CURRENT;
798 else
799 message("unknown tab flag: %s", ap);
803 static void
804 load_last_session(void)
806 const char *title;
807 char *nl, *line = NULL;
808 uint32_t flags;
809 size_t linesize = 0;
810 ssize_t linelen;
811 FILE *session;
812 struct tab *tab, *curr = NULL;
814 if ((session = fopen(session_file, "r")) == NULL) {
815 /* first time? */
816 new_tab("about:new");
817 switch_to_tab(new_tab("about:help"));
818 return;
821 while ((linelen = getline(&line, &linesize, session)) != -1) {
822 if ((nl = strchr(line, '\n')) != NULL)
823 *nl = '\0';
824 parse_session_line(line, &title, &flags);
825 if ((tab = new_tab(line)) == NULL)
826 err(1, "new_tab");
827 strlcpy(tab->buffer.page.title, title,
828 sizeof(tab->buffer.page.title));
829 if (flags & TAB_CURRENT)
830 curr = tab;
833 if (ferror(session))
834 message("error reading %s: %s",
835 session_file, strerror(errno));
836 fclose(session);
837 free(line);
839 if (curr != NULL)
840 switch_to_tab(curr);
842 return;
845 static pid_t
846 start_child(enum telescope_process p, const char *argv0, int fd)
848 const char *argv[4];
849 int argc = 0;
850 pid_t pid;
852 switch (pid = fork()) {
853 case -1:
854 die();
855 case 0:
856 break;
857 default:
858 close(fd);
859 return pid;
862 if (dup2(fd, 3) == -1)
863 err(1, "cannot setup imsg fd");
865 argv[argc++] = argv0;
866 switch (p) {
867 case PROC_UI:
868 errx(1, "Can't start ui process");
869 case PROC_FS:
870 argv[argc++] = "-Tf";
871 break;
872 case PROC_NET:
873 argv[argc++] = "-Tn";
874 break;
877 argv[argc++] = NULL;
878 execvp(argv0, (char *const *)argv);
879 err(1, "execvp(%s)", argv0);
882 static int
883 ui_send_net(int type, uint32_t peerid, const void *data,
884 uint16_t datalen)
886 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
887 datalen);
890 static int
891 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
893 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
894 datalen);
897 static void __attribute__((noreturn))
898 usage(int r)
900 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
901 getprogname());
902 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
903 exit(r);
906 int
907 main(int argc, char * const *argv)
909 struct imsgev net_ibuf, fs_ibuf;
910 int pipe2net[2], pipe2fs[2];
911 int ch, configtest = 0, fail = 0;
912 int has_url = 0;
913 int proc = -1;
914 int sessionfd;
915 char path[PATH_MAX];
916 const char *url = NEW_TAB_URL;
917 const char *argv0;
919 argv0 = argv[0];
921 signal(SIGCHLD, SIG_IGN);
922 signal(SIGPIPE, SIG_IGN);
924 if (getenv("NO_COLOR") != NULL)
925 enable_colors = 0;
927 strlcpy(path, getenv("HOME"), sizeof(path));
928 strlcat(path, "/.telescope/config", sizeof(path));
930 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
931 switch (ch) {
932 case 'C':
933 exit(ui_print_colors());
934 case 'c':
935 fail = 1;
936 strlcpy(path, optarg, sizeof(path));
937 break;
938 case 'n':
939 configtest = 1;
940 break;
941 case 'h':
942 usage(0);
943 case 'T':
944 switch (*optarg) {
945 case 'f':
946 proc = PROC_FS;
947 break;
948 case 'n':
949 proc = PROC_NET;
950 break;
951 default:
952 errx(1, "invalid process spec %c",
953 *optarg);
955 break;
956 case 'v':
957 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
958 exit(0);
959 break;
960 default:
961 usage(1);
965 argc -= optind;
966 argv += optind;
968 if (proc != -1) {
969 if (argc > 0)
970 usage(1);
971 else if (proc == PROC_FS)
972 return fs_main();
973 else if (proc == PROC_NET)
974 return client_main();
975 else
976 usage(1);
979 if (argc != 0) {
980 has_url = 1;
981 url = argv[0];
984 /* setup keys before reading the config */
985 TAILQ_INIT(&global_map.m);
986 global_map.unhandled_input = global_key_unbound;
987 TAILQ_INIT(&minibuffer_map.m);
989 config_init();
990 parseconfig(path, fail);
991 if (configtest){
992 puts("config OK");
993 exit(0);
996 fs_init();
997 if ((sessionfd = lock_session()) == -1)
998 errx(1, "can't lock session, is another instance of "
999 "telescope already running?");
1001 /* Start children. */
1002 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1003 err(1, "socketpair");
1004 start_child(PROC_FS, argv0, pipe2fs[1]);
1005 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1006 iev_fs = &fs_ibuf;
1007 iev_fs->handler = handle_dispatch_imsg;
1009 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1010 err(1, "socketpair");
1011 start_child(PROC_NET, argv0, pipe2net[1]);
1012 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1013 iev_net = &net_ibuf;
1014 iev_net->handler = handle_dispatch_imsg;
1016 setproctitle("ui");
1018 /* initialize tofu & load certificates */
1019 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1020 load_certs(&certs);
1022 event_init();
1024 /* Setup event handlers for pipes to fs/net */
1025 iev_fs->events = EV_READ;
1026 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1027 iev_fs->handler, iev_fs);
1028 event_add(&iev_fs->ev, NULL);
1030 iev_net->events = EV_READ;
1031 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1032 iev_net->handler, iev_net);
1033 event_add(&iev_net->ev, NULL);
1035 if (ui_init()) {
1036 load_last_session();
1037 if (has_url || TAILQ_EMPTY(&tabshead))
1038 new_tab(url);
1040 sandbox_ui_process();
1041 ui_main_loop();
1042 ui_end();
1045 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1046 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1047 imsg_flush(&iev_fs->ibuf);
1048 imsg_flush(&iev_net->ibuf);
1050 close(sessionfd);
1052 return 0;