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 "pages.h"
14 #include "parser.h"
15 #include "telescope.h"
16 #include "ui.h"
18 static struct option longopts[] = {
19 {"colors", no_argument, NULL, 'c'},
20 {"help", no_argument, NULL, 'h'},
21 {"version", no_argument, NULL, 'v'},
22 {NULL, 0, NULL, 0},
23 };
25 static const char *opts = "Cc:hnT:v";
27 static struct imsgev *iev_fs, *iev_net;
29 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
30 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
32 enum telescope_process {
33 PROC_UI,
34 PROC_FS,
35 PROC_NET,
36 };
38 /* the first is also the fallback one */
39 static struct proto protos[] = {
40 { "gemini", load_gemini_url },
41 { "about", load_about_url },
42 { NULL, NULL },
43 };
46 #define CANNOT_FETCH 0
47 #define TOO_MUCH_REDIRECTS 1
48 #define MALFORMED_RESPONSE 2
49 #define UNKNOWN_TYPE_OR_CSET 3
50 #define UNKNOWN_PROTOCOL 4
52 /* XXX: keep in sync with telescope.c:/^normalize_code/ */
53 const char *err_pages[70] = {
54 [CANNOT_FETCH] = "# Couldn't load the page\n",
55 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
56 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
57 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
58 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
60 [10] = "# Input required\n",
61 [11] = "# Input required\n",
62 [40] = "# Temporary failure\n",
63 [41] = "# Server unavailable\n",
64 [42] = "# CGI error\n",
65 [43] = "# Proxy error\n",
66 [44] = "# Slow down\n",
67 [50] = "# Permanent failure\n",
68 [51] = "# Not found\n",
69 [52] = "# Gone\n",
70 [53] = "# Proxy request refused\n",
71 [59] = "# Bad request\n",
72 [60] = "# Client certificate required\n",
73 [61] = "# Certificate not authorised\n",
74 [62] = "# Certificate not valid\n"
75 };
77 static void die(void) __attribute__((__noreturn__));
78 static struct tab *tab_by_id(uint32_t);
79 static void handle_imsg_err(struct imsg*, size_t);
80 static void handle_imsg_check_cert(struct imsg*, size_t);
81 static void handle_check_cert_user_choice(int, struct tab *);
82 static void handle_maybe_save_new_cert(int, struct tab *);
83 static void handle_imsg_got_code(struct imsg*, size_t);
84 static void handle_imsg_got_meta(struct imsg*, size_t);
85 static void handle_maybe_save_page(int, struct tab *);
86 static void handle_save_page_path(const char *, struct tab *);
87 static void handle_imsg_file_opened(struct imsg*, size_t);
88 static void handle_imsg_buf(struct imsg*, size_t);
89 static void handle_imsg_eof(struct imsg*, size_t);
90 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
91 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
92 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
93 static void handle_dispatch_imsg(int, short, void*);
94 static void load_page_from_str(struct tab*, const char*);
95 static int do_load_url(struct tab*, const char*);
96 static void parse_session_line(char *, const char **, uint32_t *);
97 static void load_last_session(void);
98 static pid_t start_child(enum telescope_process, const char *, int);
99 static int ui_send_net(int, uint32_t, const void *, uint16_t);
100 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
102 static imsg_handlerfn *handlers[] = {
103 [IMSG_ERR] = handle_imsg_err,
104 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
105 [IMSG_GOT_CODE] = handle_imsg_got_code,
106 [IMSG_GOT_META] = handle_imsg_got_meta,
107 [IMSG_BUF] = handle_imsg_buf,
108 [IMSG_EOF] = handle_imsg_eof,
109 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
110 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
111 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
112 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
113 };
115 static struct ohash certs;
117 static void __attribute__((__noreturn__))
118 die(void)
120 abort(); /* TODO */
123 static struct tab *
124 tab_by_id(uint32_t id)
126 struct tab *t;
128 TAILQ_FOREACH(t, &tabshead, tabs) {
129 if (t->id == id)
130 return t;
133 die();
136 static void
137 handle_imsg_err(struct imsg *imsg, size_t datalen)
139 struct tab *tab;
140 char *page;
142 tab = tab_by_id(imsg->hdr.peerid);
144 page = imsg->data;
145 page[datalen-1] = '\0';
147 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
148 tab->hist_cur->h, page) == -1)
149 die();
150 load_page_from_str(tab, page);
151 free(page);
154 static void
155 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
157 const char *hash, *host, *port;
158 int tofu_res;
159 struct tofu_entry *e;
160 struct tab *tab;
162 hash = imsg->data;
163 if (hash[datalen-1] != '\0')
164 abort();
166 tab = tab_by_id(imsg->hdr.peerid);
168 if (tab->proxy != NULL) {
169 host = tab->proxy->host;
170 port = tab->proxy->port;
171 } else {
172 host = tab->uri.host;
173 port = tab->uri.port;
176 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
177 /* TODO: an update in libressl/libretls changed
178 * significantly. Find a better approach at storing
179 * the certs! */
180 if (datalen > sizeof(e->hash))
181 abort();
183 tofu_res = 1; /* trust on first use */
184 if ((e = calloc(1, sizeof(*e))) == NULL)
185 abort();
186 strlcpy(e->domain, host, sizeof(e->domain));
187 if (*port != '\0' && strcmp(port, "1965")) {
188 strlcat(e->domain, ":", sizeof(e->domain));
189 strlcat(e->domain, port, sizeof(e->domain));
191 strlcpy(e->hash, hash, sizeof(e->hash));
192 tofu_add(&certs, e);
193 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
194 } else
195 tofu_res = !strcmp(hash, e->hash);
197 if (tofu_res) {
198 if (e->verified == -1)
199 tab->trust = TS_TEMP_TRUSTED;
200 else if (e->verified == 1)
201 tab->trust = TS_VERIFIED;
202 else
203 tab->trust = TS_TRUSTED;
205 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
206 &tofu_res, sizeof(tofu_res));
207 } else {
208 tab->trust = TS_UNTRUSTED;
209 load_page_from_str(tab, "# Certificate mismatch\n");
210 if ((tab->cert = strdup(hash)) == NULL)
211 die();
212 ui_yornp("Certificate mismatch. Proceed?",
213 handle_check_cert_user_choice, tab);
217 static void
218 handle_check_cert_user_choice(int accept, struct tab *tab)
220 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
221 sizeof(accept));
223 if (accept) {
224 /*
225 * trust the certificate for this session only. If
226 * the page results in a redirect while we're asking
227 * the user to save, we'll end up with an invalid
228 * tabid (one request == one tab id) and crash. It
229 * also makes sense to save it for the current session
230 * if the user accepted it.
231 */
232 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
234 ui_yornp("Save the new certificate?",
235 handle_maybe_save_new_cert, tab);
236 } else {
237 free(tab->cert);
238 tab->cert = NULL;
242 static void
243 handle_maybe_save_new_cert(int accept, struct tab *tab)
245 struct tofu_entry *e;
246 const char *host, *port;
248 if (tab->proxy != NULL) {
249 host = tab->proxy->host;
250 port = tab->proxy->port;
251 } else {
252 host = tab->uri.host;
253 port = tab->uri.port;
256 if (!accept)
257 goto end;
259 if ((e = calloc(1, sizeof(*e))) == NULL)
260 die();
262 strlcpy(e->domain, host, sizeof(e->domain));
263 if (*port != '\0' && strcmp(port, "1965")) {
264 strlcat(e->domain, ":", sizeof(e->domain));
265 strlcat(e->domain, port, sizeof(e->domain));
267 strlcpy(e->hash, tab->cert, sizeof(e->hash));
268 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
270 tofu_update(&certs, e);
272 tab->trust = TS_TRUSTED;
274 end:
275 free(tab->cert);
276 tab->cert = NULL;
279 static inline int
280 normalize_code(int n)
282 if (n < 20) {
283 if (n == 10 || n == 11)
284 return n;
285 return 10;
286 } else if (n < 30) {
287 return 20;
288 } else if (n < 40) {
289 if (n == 30 || n == 31)
290 return n;
291 return 30;
292 } else if (n < 50) {
293 if (n <= 44)
294 return n;
295 return 40;
296 } else if (n < 60) {
297 if (n <= 53 || n == 59)
298 return n;
299 return 50;
300 } else if (n < 70) {
301 if (n <= 62)
302 return n;
303 return 60;
304 } else
305 return MALFORMED_RESPONSE;
308 static void
309 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
311 struct tab *tab;
313 tab = tab_by_id(imsg->hdr.peerid);
315 if (sizeof(tab->code) != datalen)
316 die();
318 memcpy(&tab->code, imsg->data, sizeof(tab->code));
319 tab->code = normalize_code(tab->code);
320 if (tab->code != 30 && tab->code != 31)
321 tab->redirect_count = 0;
324 static void
325 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
327 struct tab *tab;
329 tab = tab_by_id(imsg->hdr.peerid);
331 if (sizeof(tab->meta) <= datalen)
332 die();
334 memcpy(tab->meta, imsg->data, datalen);
336 if (tab->code < 10) { /* internal errors */
337 load_page_from_str(tab, err_pages[tab->code]);
338 } else if (tab->code < 20) { /* 1x */
339 load_page_from_str(tab, err_pages[tab->code]);
340 ui_require_input(tab, tab->code == 11);
341 } else if (tab->code == 20) {
342 if (setup_parser_for(tab)) {
343 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
344 } else {
345 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
346 ui_yornp("Can't display page, wanna save?",
347 handle_maybe_save_page, tab);
349 } else if (tab->code < 40) { /* 3x */
350 tab->redirect_count++;
352 /* TODO: make customizable? */
353 if (tab->redirect_count > 5) {
354 load_page_from_str(tab,
355 err_pages[TOO_MUCH_REDIRECTS]);
356 } else
357 do_load_url(tab, tab->meta);
358 } else { /* 4x, 5x & 6x */
359 load_page_from_str(tab, err_pages[tab->code]);
363 static void
364 handle_maybe_save_page(int dosave, struct tab *tab)
366 if (dosave)
367 ui_read("Save to path", handle_save_page_path, tab);
368 else
369 stop_tab(tab);
372 static void
373 handle_save_page_path(const char *path, struct tab *tab)
375 if (path == NULL) {
376 stop_tab(tab);
377 return;
380 tab->path = strdup(path);
382 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
385 static void
386 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
388 struct tab *tab;
389 char *page;
390 const char *e;
391 int l;
393 tab = tab_by_id(imsg->hdr.peerid);
395 if (imsg->fd == -1) {
396 stop_tab(tab);
398 e = imsg->data;
399 if (e[datalen-1] != '\0')
400 die();
401 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
402 tab->path, e);
403 if (l == -1)
404 die();
405 load_page_from_str(tab, page);
406 free(page);
407 } else {
408 tab->fd = imsg->fd;
409 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
413 static void
414 handle_imsg_buf(struct imsg *imsg, size_t datalen)
416 struct tab *tab;
417 int l;
418 char *page, buf[FMT_SCALED_STRSIZE] = {0};
420 tab = tab_by_id(imsg->hdr.peerid);
422 tab->bytes += datalen;
423 if (tab->fd == -1) {
424 if (!tab->buffer.page.parse(&tab->buffer.page,
425 imsg->data, datalen))
426 die();
427 } else {
428 write(tab->fd, imsg->data, datalen);
429 fmt_scaled(tab->bytes, buf);
430 l = asprintf(&page, "Saving to \"%s\"... (%s)\n",
431 tab->path,
432 buf);
433 if (l == -1)
434 die();
435 load_page_from_str(tab, page);
436 free(page);
439 ui_on_tab_refresh(tab);
442 static void
443 handle_imsg_eof(struct imsg *imsg, size_t datalen)
445 struct tab *tab;
446 int l;
447 char *page, buf[FMT_SCALED_STRSIZE] = {0};
449 tab = tab_by_id(imsg->hdr.peerid);
451 if (tab->fd == -1) {
452 if (!tab->buffer.page.free(&tab->buffer.page))
453 die();
454 } else {
455 fmt_scaled(tab->bytes, buf);
456 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
457 tab->path,
458 buf);
459 if (l == -1)
460 die();
461 load_page_from_str(tab, page);
462 free(page);
464 close(tab->fd);
465 tab->fd = -1;
466 free(tab->path);
467 tab->path = NULL;
470 ui_on_tab_refresh(tab);
471 ui_on_tab_loaded(tab);
474 static void
475 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
477 int res;
479 if (datalen != sizeof(res))
480 die();
482 memcpy(&res, imsg->data, sizeof(res));
483 if (res == 0)
484 message("Added to bookmarks!");
485 else
486 message("Failed to add to bookmarks: %s",
487 strerror(res));
490 static void
491 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
493 int res;
495 if (datalen != sizeof(res))
496 die();
497 memcpy(&res, imsg->data, datalen);
498 if (res != 0)
499 message("Failed to save the cert for: %s",
500 strerror(res));
503 static void
504 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
506 int res;
508 if (datalen != sizeof(res))
509 die();
510 memcpy(&res, imsg->data, datalen);
511 if (!res)
512 message("Failed to update the certificate");
515 static void
516 handle_dispatch_imsg(int fd, short ev, void *d)
518 struct imsgev *iev = d;
519 dispatch_imsg(iev, ev, handlers, sizeof(handlers));
522 static void
523 load_page_from_str(struct tab *tab, const char *page)
525 erase_buffer(&tab->buffer);
526 gemtext_initparser(&tab->buffer.page);
527 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
528 die();
529 if (!tab->buffer.page.free(&tab->buffer.page))
530 die();
531 ui_on_tab_refresh(tab);
532 ui_on_tab_loaded(tab);
535 void
536 load_about_url(struct tab *tab, const char *url)
538 tab->trust = TS_VERIFIED;
540 gemtext_initparser(&tab->buffer.page);
542 ui_send_fs(IMSG_GET, tab->id,
543 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
546 void
547 load_gemini_url(struct tab *tab, const char *url)
549 struct get_req req;
551 stop_tab(tab);
552 tab->id = tab_new_id();
554 memset(&req, 0, sizeof(req));
555 strlcpy(req.host, tab->uri.host, sizeof(req.host));
556 strlcpy(req.port, tab->uri.port, sizeof(req.host));
558 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
559 strlcat(req.req, "\r\n", sizeof(req.req));
561 req.proto = PROTO_GEMINI;
563 ui_send_net(IMSG_GET_RAW, tab->id,
564 &req, sizeof(req));
567 void
568 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
570 struct get_req req;
572 stop_tab(tab);
573 tab->id = tab_new_id();
574 tab->proxy = p;
576 memset(&req, 0, sizeof(req));
577 strlcpy(req.host, p->host, sizeof(req.host));
578 strlcpy(req.port, p->port, sizeof(req.host));
580 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
581 strlcat(req.req, "\r\n", sizeof(req.req));
583 req.proto = p->proto;
585 ui_send_net(IMSG_GET_RAW, tab->id,
586 &req, sizeof(req));
589 /*
590 * Effectively load the given url in the given tab. Return 1 when
591 * loading the page asynchronously, and thus when an erase_buffer can
592 * be done right after this function return, or 0 when loading the
593 * page synchronously. In this last case, erase_buffer *MUST* be
594 * called by the handling function (such as load_page_from_str).
595 */
596 static int
597 do_load_url(struct tab *tab, const char *url)
599 struct phos_uri uri;
600 struct proto *p;
601 struct proxy *proxy;
602 char *t;
604 tab->proxy = NULL;
606 if (tab->fd != -1) {
607 close(tab->fd);
608 tab->fd = -1;
609 free(tab->path);
610 tab->path = NULL;
613 tab->trust = TS_UNKNOWN;
615 memcpy(&uri, &tab->uri, sizeof(tab->uri));
616 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
617 if (asprintf(&t, "#error loading %s\n>%s\n",
618 url, "Can't parse the URI") == -1)
619 die();
620 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
621 load_page_from_str(tab, t);
622 free(t);
623 return 0;
626 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
627 sizeof(tab->hist_cur->h));
629 for (p = protos; p->schema != NULL; ++p) {
630 if (!strcmp(tab->uri.scheme, p->schema)) {
631 p->loadfn(tab, url);
632 return 1;
636 TAILQ_FOREACH(proxy, &proxies, proxies) {
637 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
638 load_via_proxy(tab, url, proxy);
639 return 1;
643 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
644 return 0;
647 /*
648 * Load url in tab. If tab is marked as lazy, only prepare the url
649 * but don't load it. If tab is lazy and a url was already prepared,
650 * do load it!
651 */
652 void
653 load_url(struct tab *tab, const char *url)
655 int lazy;
657 lazy = tab->flags & TAB_LAZY;
659 if (lazy && tab->hist_cur != NULL) {
660 lazy = 0;
661 tab->flags &= ~TAB_LAZY;
664 if (!lazy || tab->hist_cur == NULL) {
665 if (tab->hist_cur != NULL)
666 hist_clear_forward(&tab->hist,
667 TAILQ_NEXT(tab->hist_cur, entries));
669 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
670 event_loopbreak();
671 return;
674 strlcpy(tab->buffer.page.title, url,
675 sizeof(tab->buffer.page.title));
676 hist_push(&tab->hist, tab->hist_cur);
678 if (lazy)
679 strlcpy(tab->hist_cur->h, url,
680 sizeof(tab->hist_cur->h));
683 if (!lazy && do_load_url(tab, url))
684 erase_buffer(&tab->buffer);
687 int
688 load_previous_page(struct tab *tab)
690 struct hist *h;
692 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
693 return 0;
694 tab->hist_cur = h;
695 do_load_url(tab, h->h);
696 return 1;
699 int
700 load_next_page(struct tab *tab)
702 struct hist *h;
704 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
705 return 0;
706 tab->hist_cur = h;
707 do_load_url(tab, h->h);
708 return 1;
711 void
712 stop_tab(struct tab *tab)
714 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
716 if (tab->fd != -1) {
717 close(tab->fd);
718 tab->fd = -1;
719 free(tab->path);
720 tab->path = NULL;
721 load_page_from_str(tab, "Stopped.\n");
725 void
726 add_to_bookmarks(const char *str)
728 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
729 str, strlen(str)+1);
732 void
733 save_session(void)
735 struct tab *tab;
736 char *t;
737 int flags;
739 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
741 TAILQ_FOREACH(tab, &tabshead, tabs) {
742 flags = tab->flags;
743 if (tab == current_tab)
744 flags |= TAB_CURRENT;
746 t = tab->hist_cur->h;
747 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
749 t = tab->buffer.page.title;
750 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
753 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
756 /*
757 * Parse a line of the session file. The format is:
759 * URL [flags,...] [title]\n
760 */
761 static void
762 parse_session_line(char *line, const char **title, uint32_t *flags)
764 char *s, *t, *ap;
766 *title = "";
767 *flags = 0;
768 if ((s = strchr(line, ' ')) == NULL)
769 return;
771 *s++ = '\0';
773 if ((t = strchr(s, ' ')) != NULL) {
774 *t++ = '\0';
775 *title = t;
778 while ((ap = strsep(&s, ",")) != NULL) {
779 if (*ap == '\0')
781 else if (!strcmp(ap, "current"))
782 *flags |= TAB_CURRENT;
783 else
784 message("unknown tab flag: %s", ap);
788 static void
789 load_last_session(void)
791 const char *title;
792 char *nl, *line = NULL;
793 uint32_t flags;
794 size_t linesize = 0;
795 ssize_t linelen;
796 FILE *session;
797 struct tab *tab, *curr = NULL;
799 if ((session = fopen(session_file, "r")) == NULL) {
800 /* first time? */
801 new_tab("about:new");
802 switch_to_tab(new_tab("about:help"));
803 return;
806 while ((linelen = getline(&line, &linesize, session)) != -1) {
807 if ((nl = strchr(line, '\n')) != NULL)
808 *nl = '\0';
809 parse_session_line(line, &title, &flags);
810 if ((tab = new_tab(line)) == NULL)
811 err(1, "new_tab");
812 strlcpy(tab->buffer.page.title, title,
813 sizeof(tab->buffer.page.title));
814 if (flags & TAB_CURRENT)
815 curr = tab;
818 if (ferror(session))
819 message("error reading %s: %s",
820 session_file, strerror(errno));
821 fclose(session);
822 free(line);
824 if (curr != NULL)
825 switch_to_tab(curr);
827 return;
830 static pid_t
831 start_child(enum telescope_process p, const char *argv0, int fd)
833 const char *argv[4];
834 int argc = 0;
835 pid_t pid;
837 switch (pid = fork()) {
838 case -1:
839 die();
840 case 0:
841 break;
842 default:
843 close(fd);
844 return pid;
847 if (dup2(fd, 3) == -1)
848 err(1, "cannot setup imsg fd");
850 argv[argc++] = argv0;
851 switch (p) {
852 case PROC_UI:
853 errx(1, "Can't start ui process");
854 case PROC_FS:
855 argv[argc++] = "-Tf";
856 break;
857 case PROC_NET:
858 argv[argc++] = "-Tn";
859 break;
862 argv[argc++] = NULL;
863 execvp(argv0, (char *const *)argv);
864 err(1, "execvp(%s)", argv0);
867 static int
868 ui_send_net(int type, uint32_t peerid, const void *data,
869 uint16_t datalen)
871 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
872 datalen);
875 static int
876 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
878 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
879 datalen);
882 static void __attribute__((noreturn))
883 usage(int r)
885 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
886 getprogname());
887 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
888 exit(r);
891 int
892 main(int argc, char * const *argv)
894 struct imsgev net_ibuf, fs_ibuf;
895 int pipe2net[2], pipe2fs[2];
896 int ch, configtest = 0, fail = 0;
897 int has_url = 0;
898 int proc = -1;
899 int sessionfd;
900 char path[PATH_MAX];
901 const char *url = NEW_TAB_URL;
902 const char *argv0;
904 argv0 = argv[0];
906 signal(SIGCHLD, SIG_IGN);
907 signal(SIGPIPE, SIG_IGN);
909 if (getenv("NO_COLOR") != NULL)
910 enable_colors = 0;
912 strlcpy(path, getenv("HOME"), sizeof(path));
913 strlcat(path, "/.telescope/config", sizeof(path));
915 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
916 switch (ch) {
917 case 'C':
918 exit(ui_print_colors());
919 case 'c':
920 fail = 1;
921 strlcpy(path, optarg, sizeof(path));
922 break;
923 case 'n':
924 configtest = 1;
925 break;
926 case 'h':
927 usage(0);
928 case 'T':
929 switch (*optarg) {
930 case 'f':
931 proc = PROC_FS;
932 break;
933 case 'n':
934 proc = PROC_NET;
935 break;
936 default:
937 errx(1, "invalid process spec %c",
938 *optarg);
940 break;
941 case 'v':
942 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
943 exit(0);
944 break;
945 default:
946 usage(1);
950 argc -= optind;
951 argv += optind;
953 if (proc != -1) {
954 if (argc > 0)
955 usage(1);
956 else if (proc == PROC_FS)
957 return fs_main();
958 else if (proc == PROC_NET)
959 return client_main();
960 else
961 usage(1);
964 if (argc != 0) {
965 has_url = 1;
966 url = argv[0];
969 /* setup keys before reading the config */
970 TAILQ_INIT(&global_map.m);
971 global_map.unhandled_input = global_key_unbound;
972 TAILQ_INIT(&minibuffer_map.m);
974 config_init();
975 parseconfig(path, fail);
976 if (configtest){
977 puts("config OK");
978 exit(0);
981 fs_init();
982 if ((sessionfd = lock_session()) == -1)
983 errx(1, "can't lock session, is another instance of "
984 "telescope already running?");
986 /* Start children. */
987 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
988 err(1, "socketpair");
989 start_child(PROC_FS, argv0, pipe2fs[1]);
990 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
991 iev_fs = &fs_ibuf;
992 iev_fs->handler = handle_dispatch_imsg;
994 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
995 err(1, "socketpair");
996 start_child(PROC_NET, argv0, pipe2net[1]);
997 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
998 iev_net = &net_ibuf;
999 iev_net->handler = handle_dispatch_imsg;
1001 setproctitle("ui");
1003 /* initialize tofu & load certificates */
1004 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1005 load_certs(&certs);
1007 event_init();
1009 /* Setup event handlers for pipes to fs/net */
1010 iev_fs->events = EV_READ;
1011 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1012 iev_fs->handler, iev_fs);
1013 event_add(&iev_fs->ev, NULL);
1015 iev_net->events = EV_READ;
1016 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1017 iev_net->handler, iev_net);
1018 event_add(&iev_net->ev, NULL);
1020 if (ui_init()) {
1021 load_last_session();
1022 if (has_url || TAILQ_EMPTY(&tabshead))
1023 new_tab(url);
1025 sandbox_ui_process();
1026 ui_main_loop();
1027 ui_end();
1030 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1031 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1032 imsg_flush(&iev_fs->ibuf);
1033 imsg_flush(&iev_net->ibuf);
1035 close(sessionfd);
1037 return 0;