Blob


1 #include <sys/socket.h>
3 #include <errno.h>
4 #include <getopt.h>
5 #include <limits.h>
6 #include <signal.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <unistd.h>
12 #include "defaults.h"
13 #include "parser.h"
14 #include "telescope.h"
15 #include "ui.h"
17 static struct option longopts[] = {
18 {"colors", no_argument, NULL, 'c'},
19 {"help", no_argument, NULL, 'h'},
20 {"version", no_argument, NULL, 'v'},
21 {NULL, 0, NULL, 0},
22 };
24 static const char *opts = "Cc:hnT:v";
26 static struct imsgev *iev_fs, *iev_net;
28 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
29 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
31 enum telescope_process {
32 PROC_UI,
33 PROC_FS,
34 PROC_NET,
35 };
37 /* the first is also the fallback one */
38 static struct proto protos[] = {
39 { "gemini", load_gemini_url },
40 { "about", load_about_url },
41 { NULL, NULL },
42 };
45 #define CANNOT_FETCH 0
46 #define TOO_MUCH_REDIRECTS 1
47 #define MALFORMED_RESPONSE 2
48 #define UNKNOWN_TYPE_OR_CSET 3
49 #define UNKNOWN_PROTOCOL 4
51 /* XXX: keep in sync with telescope.c:/^normalize_code/ */
52 const char *err_pages[70] = {
53 [CANNOT_FETCH] = "# Couldn't load the page\n",
54 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
55 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
56 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
57 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
59 [10] = "# Input required\n",
60 [11] = "# Input required\n",
61 [40] = "# Temporary failure\n",
62 [41] = "# Server unavailable\n",
63 [42] = "# CGI error\n",
64 [43] = "# Proxy error\n",
65 [44] = "# Slow down\n",
66 [50] = "# Permanent failure\n",
67 [51] = "# Not found\n",
68 [52] = "# Gone\n",
69 [53] = "# Proxy request refused\n",
70 [59] = "# Bad request\n",
71 [60] = "# Client certificate required\n",
72 [61] = "# Certificate not authorised\n",
73 [62] = "# Certificate not valid\n"
74 };
76 static void die(void) __attribute__((__noreturn__));
77 static struct tab *tab_by_id(uint32_t);
78 static void handle_imsg_err(struct imsg*, size_t);
79 static void handle_imsg_check_cert(struct imsg*, size_t);
80 static void handle_check_cert_user_choice(int, struct tab *);
81 static void handle_maybe_save_new_cert(int, struct tab *);
82 static void handle_imsg_got_code(struct imsg*, size_t);
83 static void handle_imsg_got_meta(struct imsg*, size_t);
84 static void handle_maybe_save_page(int, struct tab *);
85 static void handle_save_page_path(const char *, struct tab *);
86 static void handle_imsg_file_opened(struct imsg*, size_t);
87 static void handle_imsg_buf(struct imsg*, size_t);
88 static void handle_imsg_eof(struct imsg*, size_t);
89 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
90 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
91 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
92 static void handle_dispatch_imsg(int, short, void*);
93 static void load_page_from_str(struct tab*, const char*);
94 static int do_load_url(struct tab*, const char*);
95 static void parse_session_line(char *, const char **, uint32_t *);
96 static void load_last_session(void);
97 static pid_t start_child(enum telescope_process, const char *, int);
98 static int ui_send_net(int, uint32_t, const void *, uint16_t);
99 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
101 static imsg_handlerfn *handlers[] = {
102 [IMSG_ERR] = handle_imsg_err,
103 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
104 [IMSG_GOT_CODE] = handle_imsg_got_code,
105 [IMSG_GOT_META] = handle_imsg_got_meta,
106 [IMSG_BUF] = handle_imsg_buf,
107 [IMSG_EOF] = handle_imsg_eof,
108 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
109 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
110 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
111 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
112 };
114 static struct ohash certs;
116 static void __attribute__((__noreturn__))
117 die(void)
119 abort(); /* TODO */
122 static struct tab *
123 tab_by_id(uint32_t id)
125 struct tab *t;
127 TAILQ_FOREACH(t, &tabshead, tabs) {
128 if (t->id == id)
129 return t;
132 die();
135 static void
136 handle_imsg_err(struct imsg *imsg, size_t datalen)
138 struct tab *tab;
139 char *page;
141 tab = tab_by_id(imsg->hdr.peerid);
143 page = imsg->data;
144 page[datalen-1] = '\0';
146 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
147 tab->hist_cur->h, page) == -1)
148 die();
149 load_page_from_str(tab, page);
150 free(page);
153 static void
154 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
156 const char *hash, *host, *port;
157 int tofu_res;
158 struct tofu_entry *e;
159 struct tab *tab;
161 hash = imsg->data;
162 if (hash[datalen-1] != '\0')
163 abort();
165 tab = tab_by_id(imsg->hdr.peerid);
167 if (tab->proxy != NULL) {
168 host = tab->proxy->host;
169 port = tab->proxy->port;
170 } else {
171 host = tab->uri.host;
172 port = tab->uri.port;
175 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
176 /* TODO: an update in libressl/libretls changed
177 * significantly. Find a better approach at storing
178 * the certs! */
179 if (datalen > sizeof(e->hash))
180 abort();
182 tofu_res = 1; /* trust on first use */
183 if ((e = calloc(1, sizeof(*e))) == NULL)
184 abort();
185 strlcpy(e->domain, host, sizeof(e->domain));
186 if (*port != '\0' && strcmp(port, "1965")) {
187 strlcat(e->domain, ":", sizeof(e->domain));
188 strlcat(e->domain, port, sizeof(e->domain));
190 strlcpy(e->hash, hash, sizeof(e->hash));
191 tofu_add(&certs, e);
192 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
193 } else
194 tofu_res = !strcmp(hash, e->hash);
196 if (tofu_res) {
197 if (e->verified == -1)
198 tab->trust = TS_TEMP_TRUSTED;
199 else if (e->verified == 1)
200 tab->trust = TS_VERIFIED;
201 else
202 tab->trust = TS_TRUSTED;
204 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
205 &tofu_res, sizeof(tofu_res));
206 } else {
207 tab->trust = TS_UNTRUSTED;
208 load_page_from_str(tab, "# Certificate mismatch\n");
209 if ((tab->cert = strdup(hash)) == NULL)
210 die();
211 ui_yornp("Certificate mismatch. Proceed?",
212 handle_check_cert_user_choice, tab);
216 static void
217 handle_check_cert_user_choice(int accept, struct tab *tab)
219 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
220 sizeof(accept));
222 if (accept) {
223 /*
224 * trust the certificate for this session only. If
225 * the page results in a redirect while we're asking
226 * the user to save, we'll end up with an invalid
227 * tabid (one request == one tab id) and crash. It
228 * also makes sense to save it for the current session
229 * if the user accepted it.
230 */
231 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
233 ui_yornp("Save the new certificate?",
234 handle_maybe_save_new_cert, tab);
235 } else {
236 free(tab->cert);
237 tab->cert = NULL;
241 static void
242 handle_maybe_save_new_cert(int accept, struct tab *tab)
244 struct tofu_entry *e;
245 const char *host, *port;
247 if (tab->proxy != NULL) {
248 host = tab->proxy->host;
249 port = tab->proxy->port;
250 } else {
251 host = tab->uri.host;
252 port = tab->uri.port;
255 if (!accept)
256 goto end;
258 if ((e = calloc(1, sizeof(*e))) == NULL)
259 die();
261 strlcpy(e->domain, host, sizeof(e->domain));
262 if (*port != '\0' && strcmp(port, "1965")) {
263 strlcat(e->domain, ":", sizeof(e->domain));
264 strlcat(e->domain, port, sizeof(e->domain));
266 strlcpy(e->hash, tab->cert, sizeof(e->hash));
267 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
269 tofu_update(&certs, e);
271 tab->trust = TS_TRUSTED;
273 end:
274 free(tab->cert);
275 tab->cert = NULL;
278 static inline int
279 normalize_code(int n)
281 if (n < 20) {
282 if (n == 10 || n == 11)
283 return n;
284 return 10;
285 } else if (n < 30) {
286 return 20;
287 } else if (n < 40) {
288 if (n == 30 || n == 31)
289 return n;
290 return 30;
291 } else if (n < 50) {
292 if (n <= 44)
293 return n;
294 return 40;
295 } else if (n < 60) {
296 if (n <= 53 || n == 59)
297 return n;
298 return 50;
299 } else if (n < 70) {
300 if (n <= 62)
301 return n;
302 return 60;
303 } else
304 return MALFORMED_RESPONSE;
307 static void
308 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
310 struct tab *tab;
312 tab = tab_by_id(imsg->hdr.peerid);
314 if (sizeof(tab->code) != datalen)
315 die();
317 memcpy(&tab->code, imsg->data, sizeof(tab->code));
318 tab->code = normalize_code(tab->code);
319 if (tab->code != 30 && tab->code != 31)
320 tab->redirect_count = 0;
323 static void
324 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
326 struct tab *tab;
328 tab = tab_by_id(imsg->hdr.peerid);
330 if (sizeof(tab->meta) <= datalen)
331 die();
333 memcpy(tab->meta, imsg->data, datalen);
335 if (tab->code < 10) { /* internal errors */
336 load_page_from_str(tab, err_pages[tab->code]);
337 } else if (tab->code < 20) { /* 1x */
338 load_page_from_str(tab, err_pages[tab->code]);
339 ui_require_input(tab, tab->code == 11);
340 } else if (tab->code == 20) {
341 if (setup_parser_for(tab)) {
342 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
343 } else {
344 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
345 ui_yornp("Can't display page, wanna save?",
346 handle_maybe_save_page, tab);
348 } else if (tab->code < 40) { /* 3x */
349 tab->redirect_count++;
351 /* TODO: make customizable? */
352 if (tab->redirect_count > 5) {
353 load_page_from_str(tab,
354 err_pages[TOO_MUCH_REDIRECTS]);
355 } else
356 do_load_url(tab, tab->meta);
357 } else { /* 4x, 5x & 6x */
358 load_page_from_str(tab, err_pages[tab->code]);
362 static void
363 handle_maybe_save_page(int dosave, struct tab *tab)
365 if (dosave)
366 ui_read("Save to path", handle_save_page_path, tab);
367 else
368 stop_tab(tab);
371 static void
372 handle_save_page_path(const char *path, struct tab *tab)
374 if (path == NULL) {
375 stop_tab(tab);
376 return;
379 tab->path = strdup(path);
381 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
384 static void
385 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
387 struct tab *tab;
388 char *page;
389 const char *e;
390 int l;
392 tab = tab_by_id(imsg->hdr.peerid);
394 if (imsg->fd == -1) {
395 stop_tab(tab);
397 e = imsg->data;
398 if (e[datalen-1] != '\0')
399 die();
400 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
401 tab->path, e);
402 if (l == -1)
403 die();
404 load_page_from_str(tab, page);
405 free(page);
406 } else {
407 tab->fd = imsg->fd;
408 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
412 static void
413 handle_imsg_buf(struct imsg *imsg, size_t datalen)
415 struct tab *tab;
416 int l;
417 char *page, buf[FMT_SCALED_STRSIZE] = {0};
419 tab = tab_by_id(imsg->hdr.peerid);
421 tab->bytes += datalen;
422 if (tab->fd == -1) {
423 if (!tab->buffer.page.parse(&tab->buffer.page,
424 imsg->data, datalen))
425 die();
426 } else {
427 write(tab->fd, imsg->data, datalen);
428 fmt_scaled(tab->bytes, buf);
429 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
430 tab->path,
431 buf);
432 if (l == -1)
433 die();
434 load_page_from_str(tab, page);
435 free(page);
438 ui_on_tab_refresh(tab);
441 static void
442 handle_imsg_eof(struct imsg *imsg, size_t datalen)
444 struct tab *tab;
445 int l;
446 char *page, buf[FMT_SCALED_STRSIZE] = {0};
448 tab = tab_by_id(imsg->hdr.peerid);
450 if (tab->fd == -1) {
451 if (!tab->buffer.page.free(&tab->buffer.page))
452 die();
453 } else {
454 fmt_scaled(tab->bytes, buf);
455 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
456 tab->path,
457 buf);
458 if (l == -1)
459 die();
460 load_page_from_str(tab, page);
461 free(page);
463 close(tab->fd);
464 tab->fd = -1;
465 free(tab->path);
466 tab->path = NULL;
469 ui_on_tab_refresh(tab);
470 ui_on_tab_loaded(tab);
473 static void
474 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
476 int res;
478 if (datalen != sizeof(res))
479 die();
481 memcpy(&res, imsg->data, sizeof(res));
482 if (res == 0)
483 message("Added to bookmarks!");
484 else
485 message("Failed to add to bookmarks: %s",
486 strerror(res));
489 static void
490 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
492 int res;
494 if (datalen != sizeof(res))
495 die();
496 memcpy(&res, imsg->data, datalen);
497 if (res != 0)
498 message("Failed to save the cert for: %s",
499 strerror(res));
502 static void
503 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
505 int res;
507 if (datalen != sizeof(res))
508 die();
509 memcpy(&res, imsg->data, datalen);
510 if (!res)
511 message("Failed to update the certificate");
514 static void
515 handle_dispatch_imsg(int fd, short ev, void *d)
517 struct imsgev *iev = d;
518 dispatch_imsg(iev, ev, handlers, sizeof(handlers));
521 static void
522 load_page_from_str(struct tab *tab, const char *page)
524 erase_buffer(&tab->buffer);
525 gemtext_initparser(&tab->buffer.page);
526 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
527 die();
528 if (!tab->buffer.page.free(&tab->buffer.page))
529 die();
530 ui_on_tab_refresh(tab);
531 ui_on_tab_loaded(tab);
534 void
535 load_about_url(struct tab *tab, const char *url)
537 tab->trust = TS_VERIFIED;
539 gemtext_initparser(&tab->buffer.page);
541 ui_send_fs(IMSG_GET, tab->id,
542 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
545 void
546 load_gemini_url(struct tab *tab, const char *url)
548 struct get_req req;
550 stop_tab(tab);
551 tab->id = tab_new_id();
553 memset(&req, 0, sizeof(req));
554 strlcpy(req.host, tab->uri.host, sizeof(req.host));
555 strlcpy(req.port, tab->uri.port, sizeof(req.host));
557 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
558 strlcat(req.req, "\r\n", sizeof(req.req));
560 req.proto = PROTO_GEMINI;
562 ui_send_net(IMSG_GET_RAW, tab->id,
563 &req, sizeof(req));
566 void
567 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
569 struct get_req req;
571 stop_tab(tab);
572 tab->id = tab_new_id();
573 tab->proxy = p;
575 memset(&req, 0, sizeof(req));
576 strlcpy(req.host, p->host, sizeof(req.host));
577 strlcpy(req.port, p->port, sizeof(req.host));
579 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
580 strlcat(req.req, "\r\n", sizeof(req.req));
582 req.proto = p->proto;
584 ui_send_net(IMSG_GET_RAW, tab->id,
585 &req, sizeof(req));
588 /*
589 * Effectively load the given url in the given tab. Return 1 when
590 * loading the page asynchronously, and thus when an erase_buffer can
591 * be done right after this function return, or 0 when loading the
592 * page synchronously. In this last case, erase_buffer *MUST* be
593 * called by the handling function (such as load_page_from_str).
594 */
595 static int
596 do_load_url(struct tab *tab, const char *url)
598 struct phos_uri uri;
599 struct proto *p;
600 struct proxy *proxy;
601 char *t;
603 tab->proxy = NULL;
605 if (tab->fd != -1) {
606 close(tab->fd);
607 tab->fd = -1;
608 free(tab->path);
609 tab->path = NULL;
612 tab->trust = TS_UNKNOWN;
614 memcpy(&uri, &tab->uri, sizeof(tab->uri));
615 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
616 if (asprintf(&t, "#error loading %s\n>%s\n",
617 url, "Can't parse the URI") == -1)
618 die();
619 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
620 load_page_from_str(tab, t);
621 free(t);
622 return 0;
625 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
626 sizeof(tab->hist_cur->h));
628 for (p = protos; p->schema != NULL; ++p) {
629 if (!strcmp(tab->uri.scheme, p->schema)) {
630 p->loadfn(tab, url);
631 return 1;
635 TAILQ_FOREACH(proxy, &proxies, proxies) {
636 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
637 load_via_proxy(tab, url, proxy);
638 return 1;
642 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
643 return 0;
646 /*
647 * Load url in tab. If tab is marked as lazy, only prepare the url
648 * but don't load it. If tab is lazy and a url was already prepared,
649 * do load it!
650 */
651 void
652 load_url(struct tab *tab, const char *url)
654 int lazy;
656 lazy = tab->flags & TAB_LAZY;
658 if (lazy && tab->hist_cur != NULL) {
659 lazy = 0;
660 tab->flags &= ~TAB_LAZY;
663 if (!lazy || tab->hist_cur == NULL) {
664 if (tab->hist_cur != NULL)
665 hist_clear_forward(&tab->hist,
666 TAILQ_NEXT(tab->hist_cur, entries));
668 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
669 event_loopbreak();
670 return;
673 strlcpy(tab->buffer.page.title, url,
674 sizeof(tab->buffer.page.title));
675 hist_push(&tab->hist, tab->hist_cur);
677 if (lazy)
678 strlcpy(tab->hist_cur->h, url,
679 sizeof(tab->hist_cur->h));
682 if (!lazy && do_load_url(tab, url))
683 erase_buffer(&tab->buffer);
686 int
687 load_previous_page(struct tab *tab)
689 struct hist *h;
691 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
692 return 0;
693 tab->hist_cur = h;
694 do_load_url(tab, h->h);
695 return 1;
698 int
699 load_next_page(struct tab *tab)
701 struct hist *h;
703 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
704 return 0;
705 tab->hist_cur = h;
706 do_load_url(tab, h->h);
707 return 1;
710 void
711 stop_tab(struct tab *tab)
713 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
715 if (tab->fd != -1) {
716 close(tab->fd);
717 tab->fd = -1;
718 free(tab->path);
719 tab->path = NULL;
720 load_page_from_str(tab, "Stopped.\n");
724 void
725 add_to_bookmarks(const char *str)
727 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
728 str, strlen(str)+1);
731 void
732 save_session(void)
734 struct tab *tab;
735 char *t;
736 int flags;
738 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
740 TAILQ_FOREACH(tab, &tabshead, tabs) {
741 flags = tab->flags;
742 if (tab == current_tab)
743 flags |= TAB_CURRENT;
745 t = tab->hist_cur->h;
746 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
748 t = tab->buffer.page.title;
749 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
752 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
755 /*
756 * Parse a line of the session file. The format is:
758 * URL [flags,...] [title]\n
759 */
760 static void
761 parse_session_line(char *line, const char **title, uint32_t *flags)
763 char *s, *t, *ap;
765 *title = "";
766 *flags = 0;
767 if ((s = strchr(line, ' ')) == NULL)
768 return;
770 *s++ = '\0';
772 if ((t = strchr(s, ' ')) != NULL) {
773 *t++ = '\0';
774 *title = t;
777 while ((ap = strsep(&s, ",")) != NULL) {
778 if (*ap == '\0')
780 else if (!strcmp(ap, "current"))
781 *flags |= TAB_CURRENT;
782 else
783 message("unknown tab flag: %s", ap);
787 static void
788 load_last_session(void)
790 const char *title;
791 char *nl, *line = NULL;
792 uint32_t flags;
793 size_t linesize = 0;
794 ssize_t linelen;
795 FILE *session;
796 struct tab *tab, *curr = NULL;
798 if ((session = fopen(session_file, "r")) == NULL) {
799 /* first time? */
800 new_tab("about:new");
801 switch_to_tab(new_tab("about:help"));
802 return;
805 while ((linelen = getline(&line, &linesize, session)) != -1) {
806 if ((nl = strchr(line, '\n')) != NULL)
807 *nl = '\0';
808 parse_session_line(line, &title, &flags);
809 if ((tab = new_tab(line)) == NULL)
810 err(1, "new_tab");
811 strlcpy(tab->buffer.page.title, title,
812 sizeof(tab->buffer.page.title));
813 if (flags & TAB_CURRENT)
814 curr = tab;
817 if (ferror(session))
818 message("error reading %s: %s",
819 session_file, strerror(errno));
820 fclose(session);
821 free(line);
823 if (curr != NULL)
824 switch_to_tab(curr);
826 return;
829 static pid_t
830 start_child(enum telescope_process p, const char *argv0, int fd)
832 const char *argv[4];
833 int argc = 0;
834 pid_t pid;
836 switch (pid = fork()) {
837 case -1:
838 die();
839 case 0:
840 break;
841 default:
842 close(fd);
843 return pid;
846 if (dup2(fd, 3) == -1)
847 err(1, "cannot setup imsg fd");
849 argv[argc++] = argv0;
850 switch (p) {
851 case PROC_UI:
852 errx(1, "Can't start ui process");
853 case PROC_FS:
854 argv[argc++] = "-Tf";
855 break;
856 case PROC_NET:
857 argv[argc++] = "-Tn";
858 break;
861 argv[argc++] = NULL;
862 execvp(argv0, (char *const *)argv);
863 err(1, "execvp(%s)", argv0);
866 static int
867 ui_send_net(int type, uint32_t peerid, const void *data,
868 uint16_t datalen)
870 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
871 datalen);
874 static int
875 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
877 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
878 datalen);
881 static void __attribute__((noreturn))
882 usage(int r)
884 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
885 getprogname());
886 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
887 exit(r);
890 int
891 main(int argc, char * const *argv)
893 struct imsgev net_ibuf, fs_ibuf;
894 int pipe2net[2], pipe2fs[2];
895 int ch, configtest = 0, fail = 0;
896 int has_url = 0;
897 int proc = -1;
898 int sessionfd;
899 char path[PATH_MAX];
900 const char *url = NEW_TAB_URL;
901 const char *argv0;
903 argv0 = argv[0];
905 signal(SIGCHLD, SIG_IGN);
906 signal(SIGPIPE, SIG_IGN);
908 if (getenv("NO_COLOR") != NULL)
909 enable_colors = 0;
911 strlcpy(path, getenv("HOME"), sizeof(path));
912 strlcat(path, "/.telescope/config", sizeof(path));
914 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
915 switch (ch) {
916 case 'C':
917 exit(ui_print_colors());
918 case 'c':
919 fail = 1;
920 strlcpy(path, optarg, sizeof(path));
921 break;
922 case 'n':
923 configtest = 1;
924 break;
925 case 'h':
926 usage(0);
927 case 'T':
928 switch (*optarg) {
929 case 'f':
930 proc = PROC_FS;
931 break;
932 case 'n':
933 proc = PROC_NET;
934 break;
935 default:
936 errx(1, "invalid process spec %c",
937 *optarg);
939 break;
940 case 'v':
941 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
942 exit(0);
943 break;
944 default:
945 usage(1);
949 argc -= optind;
950 argv += optind;
952 if (proc != -1) {
953 if (argc > 0)
954 usage(1);
955 else if (proc == PROC_FS)
956 return fs_main();
957 else if (proc == PROC_NET)
958 return client_main();
959 else
960 usage(1);
963 if (argc != 0) {
964 has_url = 1;
965 url = argv[0];
968 /* setup keys before reading the config */
969 TAILQ_INIT(&global_map.m);
970 global_map.unhandled_input = global_key_unbound;
971 TAILQ_INIT(&minibuffer_map.m);
973 config_init();
974 parseconfig(path, fail);
975 if (configtest){
976 puts("config OK");
977 exit(0);
980 fs_init();
981 if ((sessionfd = lock_session()) == -1)
982 errx(1, "can't lock session, is another instance of "
983 "telescope already running?");
985 /* Start children. */
986 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
987 err(1, "socketpair");
988 start_child(PROC_FS, argv0, pipe2fs[1]);
989 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
990 iev_fs = &fs_ibuf;
991 iev_fs->handler = handle_dispatch_imsg;
993 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
994 err(1, "socketpair");
995 start_child(PROC_NET, argv0, pipe2net[1]);
996 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
997 iev_net = &net_ibuf;
998 iev_net->handler = handle_dispatch_imsg;
1000 setproctitle("ui");
1002 /* initialize tofu & load certificates */
1003 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1004 load_certs(&certs);
1006 event_init();
1008 /* Setup event handlers for pipes to fs/net */
1009 iev_fs->events = EV_READ;
1010 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1011 iev_fs->handler, iev_fs);
1012 event_add(&iev_fs->ev, NULL);
1014 iev_net->events = EV_READ;
1015 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1016 iev_net->handler, iev_net);
1017 event_add(&iev_net->ev, NULL);
1019 if (ui_init()) {
1020 load_last_session();
1021 if (has_url || TAILQ_EMPTY(&tabshead))
1022 new_tab(url);
1024 sandbox_ui_process();
1025 ui_main_loop();
1026 ui_end();
1029 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1030 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1031 imsg_flush(&iev_fs->ibuf);
1032 imsg_flush(&iev_net->ibuf);
1034 close(sessionfd);
1036 return 0;