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_try(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 struct tab *
152 tab_by_id(uint32_t id)
154 struct tab *t;
156 if ((t = tab_by_id_try(id)) == NULL)
157 die();
158 return t;
161 static void
162 handle_imsg_err(struct imsg *imsg, size_t datalen)
164 struct tab *tab;
165 char *page;
167 tab = tab_by_id(imsg->hdr.peerid);
169 page = imsg->data;
170 page[datalen-1] = '\0';
172 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
173 tab->hist_cur->h, page) == -1)
174 die();
175 load_page_from_str(tab, page);
176 free(page);
179 static void
180 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
182 const char *hash, *host, *port;
183 int tofu_res;
184 struct tofu_entry *e;
185 struct tab *tab;
187 hash = imsg->data;
188 if (hash[datalen-1] != '\0')
189 abort();
191 tab = tab_by_id(imsg->hdr.peerid);
193 if (tab->proxy != NULL) {
194 host = tab->proxy->host;
195 port = tab->proxy->port;
196 } else {
197 host = tab->uri.host;
198 port = tab->uri.port;
201 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
202 /* TODO: an update in libressl/libretls changed
203 * significantly. Find a better approach at storing
204 * the certs! */
205 if (datalen > sizeof(e->hash))
206 abort();
208 tofu_res = 1; /* trust on first use */
209 if ((e = calloc(1, sizeof(*e))) == NULL)
210 abort();
211 strlcpy(e->domain, host, sizeof(e->domain));
212 if (*port != '\0' && strcmp(port, "1965")) {
213 strlcat(e->domain, ":", sizeof(e->domain));
214 strlcat(e->domain, port, sizeof(e->domain));
216 strlcpy(e->hash, hash, sizeof(e->hash));
217 tofu_add(&certs, e);
218 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
219 } else
220 tofu_res = !strcmp(hash, e->hash);
222 if (tofu_res) {
223 if (e->verified == -1)
224 tab->trust = TS_TEMP_TRUSTED;
225 else if (e->verified == 1)
226 tab->trust = TS_VERIFIED;
227 else
228 tab->trust = TS_TRUSTED;
230 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
231 &tofu_res, sizeof(tofu_res));
232 } else {
233 tab->trust = TS_UNTRUSTED;
234 load_page_from_str(tab, "# Certificate mismatch\n");
235 if ((tab->cert = strdup(hash)) == NULL)
236 die();
237 ui_yornp("Certificate mismatch. Proceed?",
238 handle_check_cert_user_choice, tab);
242 static void
243 handle_check_cert_user_choice(int accept, struct tab *tab)
245 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
246 sizeof(accept));
248 if (accept) {
249 /*
250 * trust the certificate for this session only. If
251 * the page results in a redirect while we're asking
252 * the user to save, we'll end up with an invalid
253 * tabid (one request == one tab id) and crash. It
254 * also makes sense to save it for the current session
255 * if the user accepted it.
256 */
257 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
259 ui_yornp("Save the new certificate?",
260 handle_maybe_save_new_cert, tab);
261 } else {
262 free(tab->cert);
263 tab->cert = NULL;
267 static void
268 handle_maybe_save_new_cert(int accept, struct tab *tab)
270 struct tofu_entry *e;
271 const char *host, *port;
273 if (tab->proxy != NULL) {
274 host = tab->proxy->host;
275 port = tab->proxy->port;
276 } else {
277 host = tab->uri.host;
278 port = tab->uri.port;
281 if (!accept)
282 goto end;
284 if ((e = calloc(1, sizeof(*e))) == NULL)
285 die();
287 strlcpy(e->domain, host, sizeof(e->domain));
288 if (*port != '\0' && strcmp(port, "1965")) {
289 strlcat(e->domain, ":", sizeof(e->domain));
290 strlcat(e->domain, port, sizeof(e->domain));
292 strlcpy(e->hash, tab->cert, sizeof(e->hash));
293 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
295 tofu_update(&certs, e);
297 tab->trust = TS_TRUSTED;
299 end:
300 free(tab->cert);
301 tab->cert = NULL;
304 static inline int
305 normalize_code(int n)
307 if (n < 20) {
308 if (n == 10 || n == 11)
309 return n;
310 return 10;
311 } else if (n < 30) {
312 return 20;
313 } else if (n < 40) {
314 if (n == 30 || n == 31)
315 return n;
316 return 30;
317 } else if (n < 50) {
318 if (n <= 44)
319 return n;
320 return 40;
321 } else if (n < 60) {
322 if (n <= 53 || n == 59)
323 return n;
324 return 50;
325 } else if (n < 70) {
326 if (n <= 62)
327 return n;
328 return 60;
329 } else
330 return MALFORMED_RESPONSE;
333 static void
334 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
336 struct tab *tab;
338 tab = tab_by_id(imsg->hdr.peerid);
340 if (sizeof(tab->code) != datalen)
341 die();
343 memcpy(&tab->code, imsg->data, sizeof(tab->code));
344 tab->code = normalize_code(tab->code);
345 if (tab->code != 30 && tab->code != 31)
346 tab->redirect_count = 0;
349 static void
350 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
352 struct tab *tab;
354 tab = tab_by_id(imsg->hdr.peerid);
356 if (sizeof(tab->meta) <= datalen)
357 die();
359 memcpy(tab->meta, imsg->data, datalen);
361 if (tab->code < 10) { /* internal errors */
362 load_page_from_str(tab, err_pages[tab->code]);
363 } else if (tab->code < 20) { /* 1x */
364 load_page_from_str(tab, err_pages[tab->code]);
365 ui_require_input(tab, tab->code == 11);
366 } else if (tab->code == 20) {
367 if (setup_parser_for(tab)) {
368 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
369 } else {
370 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
371 ui_yornp("Can't display page, wanna save?",
372 handle_maybe_save_page, tab);
374 } else if (tab->code < 40) { /* 3x */
375 tab->redirect_count++;
377 /* TODO: make customizable? */
378 if (tab->redirect_count > 5) {
379 load_page_from_str(tab,
380 err_pages[TOO_MUCH_REDIRECTS]);
381 } else
382 do_load_url(tab, tab->meta);
383 } else { /* 4x, 5x & 6x */
384 load_page_from_str(tab, err_pages[tab->code]);
388 static void
389 handle_maybe_save_page(int dosave, struct tab *tab)
391 if (dosave)
392 ui_read("Save to path", handle_save_page_path, tab);
393 else
394 stop_tab(tab);
397 static void
398 handle_save_page_path(const char *path, struct tab *tab)
400 if (path == NULL) {
401 stop_tab(tab);
402 return;
405 tab->path = strdup(path);
407 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
410 static void
411 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
413 struct tab *tab;
414 char *page;
415 const char *e;
416 int l;
418 tab = tab_by_id(imsg->hdr.peerid);
420 if (imsg->fd == -1) {
421 stop_tab(tab);
423 e = imsg->data;
424 if (e[datalen-1] != '\0')
425 die();
426 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
427 tab->path, e);
428 if (l == -1)
429 die();
430 load_page_from_str(tab, page);
431 free(page);
432 } else {
433 tab->fd = imsg->fd;
434 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
438 static void
439 handle_imsg_buf(struct imsg *imsg, size_t datalen)
441 struct tab *tab;
442 int l;
443 char *page, buf[FMT_SCALED_STRSIZE] = {0};
445 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
446 /*
447 * Since messages between ui and net are asynchronous,
448 * we could be in a case where we sent a tab_stop
449 * command, but still receive data for the old id. My
450 * initial idea of crashing on invalid tab ids just
451 * doesn't scale well in an asynchronous world.
452 */
453 return;
456 tab->bytes += datalen;
457 if (tab->fd == -1) {
458 if (!tab->buffer.page.parse(&tab->buffer.page,
459 imsg->data, datalen))
460 die();
461 } else {
462 write(tab->fd, imsg->data, datalen);
463 fmt_scaled(tab->bytes, buf);
464 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
465 tab->path,
466 buf);
467 if (l == -1)
468 die();
469 load_page_from_str(tab, page);
470 free(page);
473 ui_on_tab_refresh(tab);
476 static void
477 handle_imsg_eof(struct imsg *imsg, size_t datalen)
479 struct tab *tab;
480 int l;
481 char *page, buf[FMT_SCALED_STRSIZE] = {0};
483 tab = tab_by_id(imsg->hdr.peerid);
485 if (tab->fd == -1) {
486 if (!tab->buffer.page.free(&tab->buffer.page))
487 die();
488 } else {
489 fmt_scaled(tab->bytes, buf);
490 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
491 tab->path,
492 buf);
493 if (l == -1)
494 die();
495 load_page_from_str(tab, page);
496 free(page);
498 close(tab->fd);
499 tab->fd = -1;
500 free(tab->path);
501 tab->path = NULL;
504 ui_on_tab_refresh(tab);
505 ui_on_tab_loaded(tab);
508 static void
509 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
511 int res;
513 if (datalen != sizeof(res))
514 die();
516 memcpy(&res, imsg->data, sizeof(res));
517 if (res == 0)
518 message("Added to bookmarks!");
519 else
520 message("Failed to add to bookmarks: %s",
521 strerror(res));
524 static void
525 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
527 int res;
529 if (datalen != sizeof(res))
530 die();
531 memcpy(&res, imsg->data, datalen);
532 if (res != 0)
533 message("Failed to save the cert for: %s",
534 strerror(res));
537 static void
538 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
540 int res;
542 if (datalen != sizeof(res))
543 die();
544 memcpy(&res, imsg->data, datalen);
545 if (!res)
546 message("Failed to update the certificate");
549 static void
550 handle_dispatch_imsg(int fd, short ev, void *d)
552 struct imsgev *iev = d;
553 dispatch_imsg(iev, ev, handlers, sizeof(handlers));
556 static void
557 load_page_from_str(struct tab *tab, const char *page)
559 erase_buffer(&tab->buffer);
560 gemtext_initparser(&tab->buffer.page);
561 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
562 die();
563 if (!tab->buffer.page.free(&tab->buffer.page))
564 die();
565 ui_on_tab_refresh(tab);
566 ui_on_tab_loaded(tab);
569 void
570 load_about_url(struct tab *tab, const char *url)
572 tab->trust = TS_VERIFIED;
574 gemtext_initparser(&tab->buffer.page);
576 ui_send_fs(IMSG_GET, tab->id,
577 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
580 void
581 load_gemini_url(struct tab *tab, const char *url)
583 struct get_req req;
585 stop_tab(tab);
586 tab->id = tab_new_id();
588 memset(&req, 0, sizeof(req));
589 strlcpy(req.host, tab->uri.host, sizeof(req.host));
590 strlcpy(req.port, tab->uri.port, sizeof(req.host));
592 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
593 strlcat(req.req, "\r\n", sizeof(req.req));
595 req.proto = PROTO_GEMINI;
597 ui_send_net(IMSG_GET_RAW, tab->id,
598 &req, sizeof(req));
601 void
602 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
604 struct get_req req;
606 stop_tab(tab);
607 tab->id = tab_new_id();
608 tab->proxy = p;
610 memset(&req, 0, sizeof(req));
611 strlcpy(req.host, p->host, sizeof(req.host));
612 strlcpy(req.port, p->port, sizeof(req.host));
614 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
615 strlcat(req.req, "\r\n", sizeof(req.req));
617 req.proto = p->proto;
619 ui_send_net(IMSG_GET_RAW, tab->id,
620 &req, sizeof(req));
623 /*
624 * Effectively load the given url in the given tab. Return 1 when
625 * loading the page asynchronously, and thus when an erase_buffer can
626 * be done right after this function return, or 0 when loading the
627 * page synchronously. In this last case, erase_buffer *MUST* be
628 * called by the handling function (such as load_page_from_str).
629 */
630 static int
631 do_load_url(struct tab *tab, const char *url)
633 struct phos_uri uri;
634 struct proto *p;
635 struct proxy *proxy;
636 char *t;
638 tab->proxy = NULL;
640 if (tab->fd != -1) {
641 close(tab->fd);
642 tab->fd = -1;
643 free(tab->path);
644 tab->path = NULL;
647 tab->trust = TS_UNKNOWN;
649 memcpy(&uri, &tab->uri, sizeof(tab->uri));
650 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
651 if (asprintf(&t, "#error loading %s\n>%s\n",
652 url, "Can't parse the URI") == -1)
653 die();
654 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
655 load_page_from_str(tab, t);
656 free(t);
657 return 0;
660 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
661 sizeof(tab->hist_cur->h));
663 for (p = protos; p->schema != NULL; ++p) {
664 if (!strcmp(tab->uri.scheme, p->schema)) {
665 p->loadfn(tab, url);
666 return 1;
670 TAILQ_FOREACH(proxy, &proxies, proxies) {
671 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
672 load_via_proxy(tab, url, proxy);
673 return 1;
677 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
678 return 0;
681 /*
682 * Load url in tab. If tab is marked as lazy, only prepare the url
683 * but don't load it. If tab is lazy and a url was already prepared,
684 * do load it!
685 */
686 void
687 load_url(struct tab *tab, const char *url)
689 int lazy;
691 lazy = tab->flags & TAB_LAZY;
693 if (lazy && tab->hist_cur != NULL) {
694 lazy = 0;
695 tab->flags &= ~TAB_LAZY;
698 if (!lazy || tab->hist_cur == NULL) {
699 if (tab->hist_cur != NULL)
700 hist_clear_forward(&tab->hist,
701 TAILQ_NEXT(tab->hist_cur, entries));
703 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
704 event_loopbreak();
705 return;
708 strlcpy(tab->buffer.page.title, url,
709 sizeof(tab->buffer.page.title));
710 hist_push(&tab->hist, tab->hist_cur);
712 if (lazy)
713 strlcpy(tab->hist_cur->h, url,
714 sizeof(tab->hist_cur->h));
717 if (!lazy && do_load_url(tab, url))
718 erase_buffer(&tab->buffer);
721 int
722 load_previous_page(struct tab *tab)
724 struct hist *h;
726 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
727 return 0;
728 tab->hist_cur = h;
729 do_load_url(tab, h->h);
730 return 1;
733 int
734 load_next_page(struct tab *tab)
736 struct hist *h;
738 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
739 return 0;
740 tab->hist_cur = h;
741 do_load_url(tab, h->h);
742 return 1;
745 void
746 stop_tab(struct tab *tab)
748 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
750 if (tab->fd != -1) {
751 close(tab->fd);
752 tab->fd = -1;
753 free(tab->path);
754 tab->path = NULL;
755 load_page_from_str(tab, "Stopped.\n");
759 void
760 add_to_bookmarks(const char *str)
762 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
763 str, strlen(str)+1);
766 void
767 save_session(void)
769 struct tab *tab;
770 char *t;
771 int flags;
773 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
775 TAILQ_FOREACH(tab, &tabshead, tabs) {
776 flags = tab->flags;
777 if (tab == current_tab)
778 flags |= TAB_CURRENT;
780 t = tab->hist_cur->h;
781 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
783 t = tab->buffer.page.title;
784 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
787 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
790 /*
791 * Parse a line of the session file. The format is:
793 * URL [flags,...] [title]\n
794 */
795 static void
796 parse_session_line(char *line, const char **title, uint32_t *flags)
798 char *s, *t, *ap;
800 *title = "";
801 *flags = 0;
802 if ((s = strchr(line, ' ')) == NULL)
803 return;
805 *s++ = '\0';
807 if ((t = strchr(s, ' ')) != NULL) {
808 *t++ = '\0';
809 *title = t;
812 while ((ap = strsep(&s, ",")) != NULL) {
813 if (*ap == '\0')
815 else if (!strcmp(ap, "current"))
816 *flags |= TAB_CURRENT;
817 else
818 message("unknown tab flag: %s", ap);
822 static void
823 load_last_session(void)
825 const char *title;
826 char *nl, *line = NULL;
827 uint32_t flags;
828 size_t linesize = 0;
829 ssize_t linelen;
830 FILE *session;
831 struct tab *tab, *curr = NULL;
833 if ((session = fopen(session_file, "r")) == NULL) {
834 /* first time? */
835 new_tab("about:new");
836 switch_to_tab(new_tab("about:help"));
837 return;
840 while ((linelen = getline(&line, &linesize, session)) != -1) {
841 if ((nl = strchr(line, '\n')) != NULL)
842 *nl = '\0';
843 parse_session_line(line, &title, &flags);
844 if ((tab = new_tab(line)) == NULL)
845 err(1, "new_tab");
846 strlcpy(tab->buffer.page.title, title,
847 sizeof(tab->buffer.page.title));
848 if (flags & TAB_CURRENT)
849 curr = tab;
852 if (ferror(session))
853 message("error reading %s: %s",
854 session_file, strerror(errno));
855 fclose(session);
856 free(line);
858 if (curr != NULL)
859 switch_to_tab(curr);
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);
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;