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 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);
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;
544 dispatch_imsg(iev, ev, handlers, sizeof(handlers));
547 static void
548 load_page_from_str(struct tab *tab, const char *page)
550 erase_buffer(&tab->buffer);
551 gemtext_initparser(&tab->buffer.page);
552 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
553 die();
554 if (!tab->buffer.page.free(&tab->buffer.page))
555 die();
556 ui_on_tab_refresh(tab);
557 ui_on_tab_loaded(tab);
560 void
561 load_about_url(struct tab *tab, const char *url)
563 tab->trust = TS_VERIFIED;
565 gemtext_initparser(&tab->buffer.page);
567 ui_send_fs(IMSG_GET, tab->id,
568 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
571 void
572 load_gemini_url(struct tab *tab, const char *url)
574 struct get_req req;
576 stop_tab(tab);
577 tab->id = tab_new_id();
579 memset(&req, 0, sizeof(req));
580 strlcpy(req.host, tab->uri.host, sizeof(req.host));
581 strlcpy(req.port, tab->uri.port, sizeof(req.host));
583 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
584 strlcat(req.req, "\r\n", sizeof(req.req));
586 req.proto = PROTO_GEMINI;
588 ui_send_net(IMSG_GET_RAW, tab->id,
589 &req, sizeof(req));
592 void
593 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
595 struct get_req req;
597 stop_tab(tab);
598 tab->id = tab_new_id();
599 tab->proxy = p;
601 memset(&req, 0, sizeof(req));
602 strlcpy(req.host, p->host, sizeof(req.host));
603 strlcpy(req.port, p->port, sizeof(req.host));
605 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
606 strlcat(req.req, "\r\n", sizeof(req.req));
608 req.proto = p->proto;
610 ui_send_net(IMSG_GET_RAW, tab->id,
611 &req, sizeof(req));
614 /*
615 * Effectively load the given url in the given tab. Return 1 when
616 * loading the page asynchronously, and thus when an erase_buffer can
617 * be done right after this function return, or 0 when loading the
618 * page synchronously. In this last case, erase_buffer *MUST* be
619 * called by the handling function (such as load_page_from_str).
620 */
621 static int
622 do_load_url(struct tab *tab, const char *url)
624 struct phos_uri uri;
625 struct proto *p;
626 struct proxy *proxy;
627 char *t;
629 tab->proxy = NULL;
631 if (tab->fd != -1) {
632 close(tab->fd);
633 tab->fd = -1;
634 free(tab->path);
635 tab->path = NULL;
638 tab->trust = TS_UNKNOWN;
640 memcpy(&uri, &tab->uri, sizeof(tab->uri));
641 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
642 if (asprintf(&t, "#error loading %s\n>%s\n",
643 url, "Can't parse the URI") == -1)
644 die();
645 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
646 load_page_from_str(tab, t);
647 free(t);
648 return 0;
651 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
652 sizeof(tab->hist_cur->h));
654 for (p = protos; p->schema != NULL; ++p) {
655 if (!strcmp(tab->uri.scheme, p->schema)) {
656 p->loadfn(tab, url);
657 return 1;
661 TAILQ_FOREACH(proxy, &proxies, proxies) {
662 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
663 load_via_proxy(tab, url, proxy);
664 return 1;
668 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
669 return 0;
672 /*
673 * Load url in tab. If tab is marked as lazy, only prepare the url
674 * but don't load it. If tab is lazy and a url was already prepared,
675 * do load it!
676 */
677 void
678 load_url(struct tab *tab, const char *url)
680 int lazy;
682 lazy = tab->flags & TAB_LAZY;
684 if (lazy && tab->hist_cur != NULL) {
685 lazy = 0;
686 tab->flags &= ~TAB_LAZY;
689 if (!lazy || tab->hist_cur == NULL) {
690 if (tab->hist_cur != NULL)
691 hist_clear_forward(&tab->hist,
692 TAILQ_NEXT(tab->hist_cur, entries));
694 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
695 event_loopbreak();
696 return;
699 strlcpy(tab->buffer.page.title, url,
700 sizeof(tab->buffer.page.title));
701 hist_push(&tab->hist, tab->hist_cur);
703 if (lazy)
704 strlcpy(tab->hist_cur->h, url,
705 sizeof(tab->hist_cur->h));
708 if (!lazy && do_load_url(tab, url))
709 erase_buffer(&tab->buffer);
712 int
713 load_previous_page(struct tab *tab)
715 struct hist *h;
717 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
718 return 0;
719 tab->hist_cur = h;
720 do_load_url(tab, h->h);
721 return 1;
724 int
725 load_next_page(struct tab *tab)
727 struct hist *h;
729 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
730 return 0;
731 tab->hist_cur = h;
732 do_load_url(tab, h->h);
733 return 1;
736 void
737 stop_tab(struct tab *tab)
739 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
741 if (tab->fd != -1) {
742 close(tab->fd);
743 tab->fd = -1;
744 free(tab->path);
745 tab->path = NULL;
746 load_page_from_str(tab, "Stopped.\n");
750 void
751 add_to_bookmarks(const char *str)
753 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
754 str, strlen(str)+1);
757 void
758 save_session(void)
760 struct tab *tab;
761 char *t;
762 int flags;
764 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
766 TAILQ_FOREACH(tab, &tabshead, tabs) {
767 flags = tab->flags;
768 if (tab == current_tab)
769 flags |= TAB_CURRENT;
771 t = tab->hist_cur->h;
772 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
774 t = tab->buffer.page.title;
775 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
778 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
781 /*
782 * Parse a line of the session file. The format is:
784 * URL [flags,...] [title]\n
785 */
786 static void
787 parse_session_line(char *line, const char **title, uint32_t *flags)
789 char *s, *t, *ap;
791 *title = "";
792 *flags = 0;
793 if ((s = strchr(line, ' ')) == NULL)
794 return;
796 *s++ = '\0';
798 if ((t = strchr(s, ' ')) != NULL) {
799 *t++ = '\0';
800 *title = t;
803 while ((ap = strsep(&s, ",")) != NULL) {
804 if (*ap == '\0')
806 else if (!strcmp(ap, "current"))
807 *flags |= TAB_CURRENT;
808 else
809 message("unknown tab flag: %s", ap);
813 static void
814 load_last_session(void)
816 const char *title;
817 char *nl, *line = NULL;
818 uint32_t flags;
819 size_t linesize = 0;
820 ssize_t linelen;
821 FILE *session;
822 struct tab *tab, *curr = NULL;
824 if ((session = fopen(session_file, "r")) == NULL) {
825 /* first time? */
826 new_tab("about:new");
827 switch_to_tab(new_tab("about:help"));
828 return;
831 while ((linelen = getline(&line, &linesize, session)) != -1) {
832 if ((nl = strchr(line, '\n')) != NULL)
833 *nl = '\0';
834 parse_session_line(line, &title, &flags);
835 if ((tab = new_tab(line)) == NULL)
836 err(1, "new_tab");
837 strlcpy(tab->buffer.page.title, title,
838 sizeof(tab->buffer.page.title));
839 if (flags & TAB_CURRENT)
840 curr = tab;
843 if (ferror(session))
844 message("error reading %s: %s",
845 session_file, strerror(errno));
846 fclose(session);
847 free(line);
849 if (curr != NULL)
850 switch_to_tab(curr);
852 return;
855 static pid_t
856 start_child(enum telescope_process p, const char *argv0, int fd)
858 const char *argv[4];
859 int argc = 0;
860 pid_t pid;
862 switch (pid = fork()) {
863 case -1:
864 die();
865 case 0:
866 break;
867 default:
868 close(fd);
869 return pid;
872 if (dup2(fd, 3) == -1)
873 err(1, "cannot setup imsg fd");
875 argv[argc++] = argv0;
876 switch (p) {
877 case PROC_UI:
878 errx(1, "Can't start ui process");
879 case PROC_FS:
880 argv[argc++] = "-Tf";
881 break;
882 case PROC_NET:
883 argv[argc++] = "-Tn";
884 break;
887 argv[argc++] = NULL;
888 execvp(argv0, (char *const *)argv);
889 err(1, "execvp(%s)", argv0);
892 static int
893 ui_send_net(int type, uint32_t peerid, const void *data,
894 uint16_t datalen)
896 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
897 datalen);
900 static int
901 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
903 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
904 datalen);
907 static void __attribute__((noreturn))
908 usage(int r)
910 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
911 getprogname());
912 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
913 exit(r);
916 int
917 main(int argc, char * const *argv)
919 struct imsgev net_ibuf, fs_ibuf;
920 int pipe2net[2], pipe2fs[2];
921 int ch, configtest = 0, fail = 0;
922 int has_url = 0;
923 int proc = -1;
924 int sessionfd;
925 char path[PATH_MAX];
926 const char *url = NEW_TAB_URL;
927 const char *argv0;
929 argv0 = argv[0];
931 signal(SIGCHLD, SIG_IGN);
932 signal(SIGPIPE, SIG_IGN);
934 if (getenv("NO_COLOR") != NULL)
935 enable_colors = 0;
937 strlcpy(path, getenv("HOME"), sizeof(path));
938 strlcat(path, "/.telescope/config", sizeof(path));
940 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
941 switch (ch) {
942 case 'C':
943 exit(ui_print_colors());
944 case 'c':
945 fail = 1;
946 strlcpy(path, optarg, sizeof(path));
947 break;
948 case 'n':
949 configtest = 1;
950 break;
951 case 'h':
952 usage(0);
953 case 'T':
954 switch (*optarg) {
955 case 'f':
956 proc = PROC_FS;
957 break;
958 case 'n':
959 proc = PROC_NET;
960 break;
961 default:
962 errx(1, "invalid process spec %c",
963 *optarg);
965 break;
966 case 'v':
967 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
968 exit(0);
969 break;
970 default:
971 usage(1);
975 argc -= optind;
976 argv += optind;
978 if (proc != -1) {
979 if (argc > 0)
980 usage(1);
981 else if (proc == PROC_FS)
982 return fs_main();
983 else if (proc == PROC_NET)
984 return client_main();
985 else
986 usage(1);
989 if (argc != 0) {
990 has_url = 1;
991 url = argv[0];
994 /* setup keys before reading the config */
995 TAILQ_INIT(&global_map.m);
996 global_map.unhandled_input = global_key_unbound;
997 TAILQ_INIT(&minibuffer_map.m);
999 config_init();
1000 parseconfig(path, fail);
1001 if (configtest){
1002 puts("config OK");
1003 exit(0);
1006 fs_init();
1007 if ((sessionfd = lock_session()) == -1)
1008 errx(1, "can't lock session, is another instance of "
1009 "telescope already running?");
1011 /* Start children. */
1012 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1013 err(1, "socketpair");
1014 start_child(PROC_FS, argv0, pipe2fs[1]);
1015 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1016 iev_fs = &fs_ibuf;
1017 iev_fs->handler = handle_dispatch_imsg;
1019 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1020 err(1, "socketpair");
1021 start_child(PROC_NET, argv0, pipe2net[1]);
1022 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1023 iev_net = &net_ibuf;
1024 iev_net->handler = handle_dispatch_imsg;
1026 setproctitle("ui");
1028 /* initialize tofu & load certificates */
1029 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1030 load_certs(&certs);
1032 event_init();
1034 /* Setup event handlers for pipes to fs/net */
1035 iev_fs->events = EV_READ;
1036 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1037 iev_fs->handler, iev_fs);
1038 event_add(&iev_fs->ev, NULL);
1040 iev_net->events = EV_READ;
1041 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1042 iev_net->handler, iev_net);
1043 event_add(&iev_net->ev, NULL);
1045 if (ui_init()) {
1046 load_last_session();
1047 if (has_url || TAILQ_EMPTY(&tabshead))
1048 new_tab(url);
1050 sandbox_ui_process();
1051 ui_main_loop();
1052 ui_end();
1055 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1056 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1057 imsg_flush(&iev_fs->ibuf);
1058 imsg_flush(&iev_net->ibuf);
1060 close(sessionfd);
1062 return 0;