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 "minibuffer.h"
30 #include "parser.h"
31 #include "telescope.h"
32 #include "ui.h"
34 static struct option longopts[] = {
35 {"colors", no_argument, NULL, 'c'},
36 {"help", no_argument, NULL, 'h'},
37 {"version", no_argument, NULL, 'v'},
38 {NULL, 0, NULL, 0},
39 };
41 static const char *opts = "Cc:hnT:v";
43 static struct imsgev *iev_fs, *iev_net;
45 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
46 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
48 enum telescope_process {
49 PROC_UI,
50 PROC_FS,
51 PROC_NET,
52 };
54 /* the first is also the fallback one */
55 static struct proto protos[] = {
56 { "gemini", load_gemini_url },
57 { "about", load_about_url },
58 { NULL, NULL },
59 };
62 #define CANNOT_FETCH 0
63 #define TOO_MUCH_REDIRECTS 1
64 #define MALFORMED_RESPONSE 2
65 #define UNKNOWN_TYPE_OR_CSET 3
66 #define UNKNOWN_PROTOCOL 4
68 /* XXX: keep in sync with telescope.c:/^normalize_code/ */
69 const char *err_pages[70] = {
70 [CANNOT_FETCH] = "# Couldn't load the page\n",
71 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
72 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
73 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
74 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
76 [10] = "# Input required\n",
77 [11] = "# Input required\n",
78 [40] = "# Temporary failure\n",
79 [41] = "# Server unavailable\n",
80 [42] = "# CGI error\n",
81 [43] = "# Proxy error\n",
82 [44] = "# Slow down\n",
83 [50] = "# Permanent failure\n",
84 [51] = "# Not found\n",
85 [52] = "# Gone\n",
86 [53] = "# Proxy request refused\n",
87 [59] = "# Bad request\n",
88 [60] = "# Client certificate required\n",
89 [61] = "# Certificate not authorised\n",
90 [62] = "# Certificate not valid\n"
91 };
93 static void die(void) __attribute__((__noreturn__));
94 static struct tab *tab_by_id(uint32_t);
95 static void handle_imsg_err(struct imsg*, size_t);
96 static void handle_imsg_check_cert(struct imsg*, size_t);
97 static void handle_check_cert_user_choice(int, struct tab *);
98 static void handle_maybe_save_new_cert(int, struct tab *);
99 static void handle_imsg_got_code(struct imsg*, size_t);
100 static void handle_imsg_got_meta(struct imsg*, size_t);
101 static void handle_maybe_save_page(int, struct tab *);
102 static void handle_save_page_path(const char *, struct tab *);
103 static void handle_imsg_file_opened(struct imsg*, size_t);
104 static void handle_imsg_buf(struct imsg*, size_t);
105 static void handle_imsg_eof(struct imsg*, size_t);
106 static void handle_imsg_bookmark_ok(struct imsg*, size_t);
107 static void handle_imsg_save_cert_ok(struct imsg*, size_t);
108 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
109 static void handle_dispatch_imsg(int, short, void*);
110 static void load_page_from_str(struct tab*, const char*);
111 static int do_load_url(struct tab*, const char *, const char *);
112 static void parse_session_line(char *, const char **, uint32_t *);
113 static void load_last_session(void);
114 static pid_t start_child(enum telescope_process, const char *, int);
115 static int ui_send_net(int, uint32_t, const void *, uint16_t);
116 static int ui_send_fs(int, uint32_t, const void *, uint16_t);
118 static imsg_handlerfn *handlers[] = {
119 [IMSG_ERR] = handle_imsg_err,
120 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
121 [IMSG_GOT_CODE] = handle_imsg_got_code,
122 [IMSG_GOT_META] = handle_imsg_got_meta,
123 [IMSG_BUF] = handle_imsg_buf,
124 [IMSG_EOF] = handle_imsg_eof,
125 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
126 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
127 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
128 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
129 };
131 static struct ohash certs;
133 static void __attribute__((__noreturn__))
134 die(void)
136 abort(); /* TODO */
139 static struct tab *
140 tab_by_id(uint32_t id)
142 struct tab *t;
144 TAILQ_FOREACH(t, &tabshead, tabs) {
145 if (t->id == id)
146 return t;
149 return NULL;
152 static void
153 handle_imsg_err(struct imsg *imsg, size_t datalen)
155 struct tab *tab;
156 char *page;
158 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
159 return;
161 page = imsg->data;
162 page[datalen-1] = '\0';
164 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
165 tab->hist_cur->h, page) == -1)
166 die();
167 load_page_from_str(tab, page);
168 free(page);
171 static void
172 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
174 const char *hash, *host, *port;
175 int tofu_res;
176 struct tofu_entry *e;
177 struct tab *tab;
179 hash = imsg->data;
180 if (hash[datalen-1] != '\0')
181 abort();
183 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
184 return;
186 if (tab->proxy != NULL) {
187 host = tab->proxy->host;
188 port = tab->proxy->port;
189 } else {
190 host = tab->uri.host;
191 port = tab->uri.port;
194 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
195 /* TODO: an update in libressl/libretls changed
196 * significantly. Find a better approach at storing
197 * the certs! */
198 if (datalen > sizeof(e->hash))
199 abort();
201 tofu_res = 1; /* trust on first use */
202 if ((e = calloc(1, sizeof(*e))) == NULL)
203 abort();
204 strlcpy(e->domain, host, sizeof(e->domain));
205 if (*port != '\0' && strcmp(port, "1965")) {
206 strlcat(e->domain, ":", sizeof(e->domain));
207 strlcat(e->domain, port, sizeof(e->domain));
209 strlcpy(e->hash, hash, sizeof(e->hash));
210 tofu_add(&certs, e);
211 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
212 } else
213 tofu_res = !strcmp(hash, e->hash);
215 if (tofu_res) {
216 if (e->verified == -1)
217 tab->trust = TS_TEMP_TRUSTED;
218 else if (e->verified == 1)
219 tab->trust = TS_VERIFIED;
220 else
221 tab->trust = TS_TRUSTED;
223 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
224 &tofu_res, sizeof(tofu_res));
225 } else {
226 tab->trust = TS_UNTRUSTED;
227 load_page_from_str(tab, "# Certificate mismatch\n");
228 if ((tab->cert = strdup(hash)) == NULL)
229 die();
230 ui_yornp("Certificate mismatch. Proceed?",
231 handle_check_cert_user_choice, tab);
235 static void
236 handle_check_cert_user_choice(int accept, struct tab *tab)
238 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
239 sizeof(accept));
241 if (accept) {
242 /*
243 * trust the certificate for this session only. If
244 * the page results in a redirect while we're asking
245 * the user to save, we'll end up with an invalid
246 * tabid (one request == one tab id) and crash. It
247 * also makes sense to save it for the current session
248 * if the user accepted it.
249 */
250 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port, tab->cert);
252 ui_yornp("Save the new certificate?",
253 handle_maybe_save_new_cert, tab);
254 } else {
255 free(tab->cert);
256 tab->cert = NULL;
260 static void
261 handle_maybe_save_new_cert(int accept, struct tab *tab)
263 struct tofu_entry *e;
264 const char *host, *port;
266 if (tab->proxy != NULL) {
267 host = tab->proxy->host;
268 port = tab->proxy->port;
269 } else {
270 host = tab->uri.host;
271 port = tab->uri.port;
274 if (!accept)
275 goto end;
277 if ((e = calloc(1, sizeof(*e))) == NULL)
278 die();
280 strlcpy(e->domain, host, sizeof(e->domain));
281 if (*port != '\0' && strcmp(port, "1965")) {
282 strlcat(e->domain, ":", sizeof(e->domain));
283 strlcat(e->domain, port, sizeof(e->domain));
285 strlcpy(e->hash, tab->cert, sizeof(e->hash));
286 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
288 tofu_update(&certs, e);
290 tab->trust = TS_TRUSTED;
292 end:
293 free(tab->cert);
294 tab->cert = NULL;
297 static inline int
298 normalize_code(int n)
300 if (n < 20) {
301 if (n == 10 || n == 11)
302 return n;
303 return 10;
304 } else if (n < 30) {
305 return 20;
306 } else if (n < 40) {
307 if (n == 30 || n == 31)
308 return n;
309 return 30;
310 } else if (n < 50) {
311 if (n <= 44)
312 return n;
313 return 40;
314 } else if (n < 60) {
315 if (n <= 53 || n == 59)
316 return n;
317 return 50;
318 } else if (n < 70) {
319 if (n <= 62)
320 return n;
321 return 60;
322 } else
323 return MALFORMED_RESPONSE;
326 static void
327 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
329 struct tab *tab;
331 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
332 return;
334 if (sizeof(tab->code) != datalen)
335 die();
337 memcpy(&tab->code, imsg->data, sizeof(tab->code));
338 tab->code = normalize_code(tab->code);
339 if (tab->code != 30 && tab->code != 31)
340 tab->redirect_count = 0;
343 static void
344 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
346 struct tab *tab;
348 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
349 return;
351 if (sizeof(tab->meta) <= datalen)
352 die();
354 memcpy(tab->meta, imsg->data, datalen);
356 if (tab->code < 10) { /* internal errors */
357 load_page_from_str(tab, err_pages[tab->code]);
358 } else if (tab->code < 20) { /* 1x */
359 load_page_from_str(tab, err_pages[tab->code]);
360 ui_require_input(tab, tab->code == 11);
361 } else if (tab->code == 20) {
362 if (setup_parser_for(tab)) {
363 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
364 } else {
365 load_page_from_str(tab, err_pages[UNKNOWN_TYPE_OR_CSET]);
366 ui_yornp("Can't display page, wanna save?",
367 handle_maybe_save_page, tab);
369 } else if (tab->code < 40) { /* 3x */
370 tab->redirect_count++;
372 /* TODO: make customizable? */
373 if (tab->redirect_count > 5) {
374 load_page_from_str(tab,
375 err_pages[TOO_MUCH_REDIRECTS]);
376 } else
377 do_load_url(tab, tab->meta, NULL);
378 } else { /* 4x, 5x & 6x */
379 load_page_from_str(tab, err_pages[tab->code]);
383 static void
384 handle_maybe_save_page(int dosave, struct tab *tab)
386 if (dosave)
387 ui_read("Save to path", handle_save_page_path, tab);
388 else
389 stop_tab(tab);
392 static void
393 handle_save_page_path(const char *path, struct tab *tab)
395 if (path == NULL) {
396 stop_tab(tab);
397 return;
400 tab->path = strdup(path);
402 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
405 static void
406 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
408 struct tab *tab;
409 char *page;
410 const char *e;
411 int l;
413 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL) {
414 if (imsg->fd != -1)
415 close(imsg->fd);
416 return;
419 if (imsg->fd == -1) {
420 stop_tab(tab);
422 e = imsg->data;
423 if (e[datalen-1] != '\0')
424 die();
425 l = asprintf(&page, "# Can't open file\n\n> %s: %s\n",
426 tab->path, e);
427 if (l == -1)
428 die();
429 load_page_from_str(tab, page);
430 free(page);
431 } else {
432 tab->fd = imsg->fd;
433 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
437 static void
438 handle_imsg_buf(struct imsg *imsg, size_t datalen)
440 struct tab *tab;
441 int l;
442 char *page, buf[FMT_SCALED_STRSIZE] = {0};
444 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
445 return;
447 tab->bytes += datalen;
448 if (tab->fd == -1) {
449 if (!tab->buffer.page.parse(&tab->buffer.page,
450 imsg->data, datalen))
451 die();
452 } else {
453 write(tab->fd, imsg->data, datalen);
454 fmt_scaled(tab->bytes, buf);
455 l = asprintf(&page, "Saving 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);
464 ui_on_tab_refresh(tab);
467 static void
468 handle_imsg_eof(struct imsg *imsg, size_t datalen)
470 struct tab *tab;
471 int l;
472 char *page, buf[FMT_SCALED_STRSIZE] = {0};
474 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
475 return;
477 if (tab->fd == -1) {
478 if (!tab->buffer.page.free(&tab->buffer.page))
479 die();
480 } else {
481 fmt_scaled(tab->bytes, buf);
482 l = asprintf(&page, "Saved to \"%s\" (%s)\n",
483 tab->path,
484 buf);
485 if (l == -1)
486 die();
487 load_page_from_str(tab, page);
488 free(page);
490 close(tab->fd);
491 tab->fd = -1;
492 free(tab->path);
493 tab->path = NULL;
496 ui_on_tab_refresh(tab);
497 ui_on_tab_loaded(tab);
500 static void
501 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
503 int res;
505 if (datalen != sizeof(res))
506 die();
508 memcpy(&res, imsg->data, sizeof(res));
509 if (res == 0)
510 message("Added to bookmarks!");
511 else
512 message("Failed to add to bookmarks: %s",
513 strerror(res));
516 static void
517 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
519 int res;
521 if (datalen != sizeof(res))
522 die();
523 memcpy(&res, imsg->data, datalen);
524 if (res != 0)
525 message("Failed to save the cert for: %s",
526 strerror(res));
529 static void
530 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
532 int res;
534 if (datalen != sizeof(res))
535 die();
536 memcpy(&res, imsg->data, datalen);
537 if (!res)
538 message("Failed to update the certificate");
541 static void
542 handle_dispatch_imsg(int fd, short ev, void *d)
544 struct imsgev *iev = d;
546 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
547 err(1, "connection closed");
550 static void
551 load_page_from_str(struct tab *tab, const char *page)
553 erase_buffer(&tab->buffer);
554 gemtext_initparser(&tab->buffer.page);
555 if (!tab->buffer.page.parse(&tab->buffer.page, page, strlen(page)))
556 die();
557 if (!tab->buffer.page.free(&tab->buffer.page))
558 die();
559 ui_on_tab_refresh(tab);
560 ui_on_tab_loaded(tab);
563 void
564 load_about_url(struct tab *tab, const char *url)
566 tab->trust = TS_VERIFIED;
568 gemtext_initparser(&tab->buffer.page);
570 ui_send_fs(IMSG_GET, tab->id,
571 tab->hist_cur->h, strlen(tab->hist_cur->h)+1);
574 void
575 load_gemini_url(struct tab *tab, const char *url)
577 struct get_req req;
579 stop_tab(tab);
580 tab->id = tab_new_id();
582 memset(&req, 0, sizeof(req));
583 strlcpy(req.host, tab->uri.host, sizeof(req.host));
584 strlcpy(req.port, tab->uri.port, sizeof(req.host));
586 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
587 strlcat(req.req, "\r\n", sizeof(req.req));
589 req.proto = PROTO_GEMINI;
591 ui_send_net(IMSG_GET_RAW, tab->id,
592 &req, sizeof(req));
595 void
596 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
598 struct get_req req;
600 stop_tab(tab);
601 tab->id = tab_new_id();
602 tab->proxy = p;
604 memset(&req, 0, sizeof(req));
605 strlcpy(req.host, p->host, sizeof(req.host));
606 strlcpy(req.port, p->port, sizeof(req.host));
608 strlcpy(req.req, tab->hist_cur->h, sizeof(req.req));
609 strlcat(req.req, "\r\n", sizeof(req.req));
611 req.proto = p->proto;
613 ui_send_net(IMSG_GET_RAW, tab->id,
614 &req, sizeof(req));
617 /*
618 * Effectively load the given url in the given tab. Return 1 when
619 * loading the page asynchronously, and thus when an erase_buffer can
620 * be done right after this function return, or 0 when loading the
621 * page synchronously. In this last case, erase_buffer *MUST* be
622 * called by the handling function (such as load_page_from_str).
623 */
624 static int
625 do_load_url(struct tab *tab, const char *url, const char *base)
627 struct phos_uri uri;
628 struct proto *p;
629 struct proxy *proxy;
630 char *t;
632 tab->proxy = NULL;
634 if (tab->fd != -1) {
635 close(tab->fd);
636 tab->fd = -1;
637 free(tab->path);
638 tab->path = NULL;
641 tab->trust = TS_UNKNOWN;
643 if (base == NULL)
644 memcpy(&uri, &tab->uri, sizeof(tab->uri));
645 else
646 phos_parse_absolute_uri(base, &uri);
648 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
649 if (asprintf(&t, "#error loading %s\n>%s\n",
650 url, "Can't parse the URI") == -1)
651 die();
652 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
653 load_page_from_str(tab, t);
654 free(t);
655 return 0;
658 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
659 sizeof(tab->hist_cur->h));
661 for (p = protos; p->schema != NULL; ++p) {
662 if (!strcmp(tab->uri.scheme, p->schema)) {
663 p->loadfn(tab, url);
664 return 1;
668 TAILQ_FOREACH(proxy, &proxies, proxies) {
669 if (!strcmp(tab->uri.scheme, proxy->match_proto)) {
670 load_via_proxy(tab, url, proxy);
671 return 1;
675 load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
676 return 0;
679 /*
680 * Load url in tab. If tab is marked as lazy, only prepare the url
681 * but don't load it. If tab is lazy and a url was already prepared,
682 * do load it!
683 */
684 void
685 load_url(struct tab *tab, const char *url, const char *base)
687 int lazy;
689 lazy = tab->flags & TAB_LAZY;
691 if (lazy && tab->hist_cur != NULL) {
692 lazy = 0;
693 tab->flags &= ~TAB_LAZY;
696 if (!lazy || tab->hist_cur == NULL) {
697 if (tab->hist_cur != NULL)
698 hist_clear_forward(&tab->hist,
699 TAILQ_NEXT(tab->hist_cur, entries));
701 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur))) == NULL) {
702 event_loopbreak();
703 return;
706 strlcpy(tab->buffer.page.title, url,
707 sizeof(tab->buffer.page.title));
708 hist_push(&tab->hist, tab->hist_cur);
710 if (lazy)
711 strlcpy(tab->hist_cur->h, url,
712 sizeof(tab->hist_cur->h));
715 if (!lazy && do_load_url(tab, url, base))
716 erase_buffer(&tab->buffer);
719 int
720 load_previous_page(struct tab *tab)
722 struct hist *h;
724 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
725 return 0;
726 tab->hist_cur = h;
727 do_load_url(tab, h->h, NULL);
728 return 1;
731 int
732 load_next_page(struct tab *tab)
734 struct hist *h;
736 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
737 return 0;
738 tab->hist_cur = h;
739 do_load_url(tab, h->h, NULL);
740 return 1;
743 /*
744 * Free every resource linked to the tab, including the tab itself.
745 * Removes the tab from the tablist, but doesn't update the
746 * current_tab though.
747 */
748 void
749 free_tab(struct tab *tab)
751 stop_tab(tab);
753 if (evtimer_pending(&tab->loadingev, NULL))
754 evtimer_del(&tab->loadingev);
756 TAILQ_REMOVE(&tabshead, tab, tabs);
757 free(tab);
760 void
761 stop_tab(struct tab *tab)
763 ui_send_net(IMSG_STOP, tab->id, NULL, 0);
765 if (tab->fd != -1) {
766 close(tab->fd);
767 tab->fd = -1;
768 free(tab->path);
769 tab->path = NULL;
770 load_page_from_str(tab, "Stopped.\n");
774 void
775 add_to_bookmarks(const char *str)
777 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
778 str, strlen(str)+1);
781 void
782 save_session(void)
784 struct tab *tab;
785 char *t;
786 int flags;
788 ui_send_fs(IMSG_SESSION_START, 0, NULL, 0);
790 TAILQ_FOREACH(tab, &tabshead, tabs) {
791 flags = tab->flags;
792 if (tab == current_tab)
793 flags |= TAB_CURRENT;
795 t = tab->hist_cur->h;
796 ui_send_fs(IMSG_SESSION_TAB, flags, t, strlen(t)+1);
798 t = tab->buffer.page.title;
799 ui_send_fs(IMSG_SESSION_TAB_TITLE, 0, t, strlen(t)+1);
802 ui_send_fs(IMSG_SESSION_END, 0, NULL, 0);
805 /*
806 * Parse a line of the session file. The format is:
808 * URL [flags,...] [title]\n
809 */
810 static void
811 parse_session_line(char *line, const char **title, uint32_t *flags)
813 char *s, *t, *ap;
815 *title = "";
816 *flags = 0;
817 if ((s = strchr(line, ' ')) == NULL)
818 return;
820 *s++ = '\0';
822 if ((t = strchr(s, ' ')) != NULL) {
823 *t++ = '\0';
824 *title = t;
827 while ((ap = strsep(&s, ",")) != NULL) {
828 if (*ap == '\0')
830 else if (!strcmp(ap, "current"))
831 *flags |= TAB_CURRENT;
832 else
833 message("unknown tab flag: %s", ap);
837 static void
838 load_last_session(void)
840 const char *title;
841 char *nl, *line = NULL;
842 uint32_t flags;
843 size_t linesize = 0;
844 ssize_t linelen;
845 FILE *session;
846 struct tab *tab, *curr = NULL;
848 if ((session = fopen(session_file, "r")) == NULL) {
849 /* first time? */
850 new_tab("about:new", NULL);
851 switch_to_tab(new_tab("about:help", NULL));
852 return;
855 while ((linelen = getline(&line, &linesize, session)) != -1) {
856 if ((nl = strchr(line, '\n')) != NULL)
857 *nl = '\0';
858 parse_session_line(line, &title, &flags);
859 if ((tab = new_tab(line, NULL)) == NULL)
860 err(1, "new_tab");
861 strlcpy(tab->buffer.page.title, title,
862 sizeof(tab->buffer.page.title));
863 if (flags & TAB_CURRENT)
864 curr = tab;
867 if (ferror(session))
868 message("error reading %s: %s",
869 session_file, strerror(errno));
870 fclose(session);
871 free(line);
873 if (curr != NULL)
874 switch_to_tab(curr);
876 if (last_time_crashed())
877 switch_to_tab(new_tab("about:crash", NULL));
879 return;
882 static pid_t
883 start_child(enum telescope_process p, const char *argv0, int fd)
885 const char *argv[4];
886 int argc = 0;
887 pid_t pid;
889 switch (pid = fork()) {
890 case -1:
891 die();
892 case 0:
893 break;
894 default:
895 close(fd);
896 return pid;
899 if (dup2(fd, 3) == -1)
900 err(1, "cannot setup imsg fd");
902 argv[argc++] = argv0;
903 switch (p) {
904 case PROC_UI:
905 errx(1, "Can't start ui process");
906 case PROC_FS:
907 argv[argc++] = "-Tf";
908 break;
909 case PROC_NET:
910 argv[argc++] = "-Tn";
911 break;
914 argv[argc++] = NULL;
915 execvp(argv0, (char *const *)argv);
916 err(1, "execvp(%s)", argv0);
919 static int
920 ui_send_net(int type, uint32_t peerid, const void *data,
921 uint16_t datalen)
923 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
924 datalen);
927 static int
928 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
930 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
931 datalen);
934 static void __attribute__((noreturn))
935 usage(int r)
937 fprintf(stderr, "USAGE: %s [-hnv] [-c config] [url]\n",
938 getprogname());
939 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
940 exit(r);
943 int
944 main(int argc, char * const *argv)
946 struct imsgev net_ibuf, fs_ibuf;
947 int pipe2net[2], pipe2fs[2];
948 int ch, configtest = 0, fail = 0;
949 int has_url = 0;
950 int proc = -1;
951 int sessionfd;
952 char path[PATH_MAX];
953 const char *url = NEW_TAB_URL;
954 const char *argv0;
956 argv0 = argv[0];
958 signal(SIGCHLD, SIG_IGN);
959 signal(SIGPIPE, SIG_IGN);
961 if (getenv("NO_COLOR") != NULL)
962 enable_colors = 0;
964 strlcpy(path, getenv("HOME"), sizeof(path));
965 strlcat(path, "/.telescope/config", sizeof(path));
967 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
968 switch (ch) {
969 case 'C':
970 exit(ui_print_colors());
971 case 'c':
972 fail = 1;
973 strlcpy(path, optarg, sizeof(path));
974 break;
975 case 'n':
976 configtest = 1;
977 break;
978 case 'h':
979 usage(0);
980 case 'T':
981 switch (*optarg) {
982 case 'f':
983 proc = PROC_FS;
984 break;
985 case 'n':
986 proc = PROC_NET;
987 break;
988 default:
989 errx(1, "invalid process spec %c",
990 *optarg);
992 break;
993 case 'v':
994 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
995 exit(0);
996 break;
997 default:
998 usage(1);
1002 argc -= optind;
1003 argv += optind;
1005 if (proc != -1) {
1006 if (argc > 0)
1007 usage(1);
1008 else if (proc == PROC_FS)
1009 return fs_main();
1010 else if (proc == PROC_NET)
1011 return client_main();
1012 else
1013 usage(1);
1016 if (argc != 0) {
1017 has_url = 1;
1018 url = argv[0];
1021 /* setup keys before reading the config */
1022 TAILQ_INIT(&global_map.m);
1023 global_map.unhandled_input = global_key_unbound;
1024 TAILQ_INIT(&minibuffer_map.m);
1026 config_init();
1027 parseconfig(path, fail);
1028 if (configtest){
1029 puts("config OK");
1030 exit(0);
1033 fs_init();
1034 if ((sessionfd = lock_session()) == -1)
1035 errx(1, "can't lock session, is another instance of "
1036 "telescope already running?");
1038 /* Start children. */
1039 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1040 err(1, "socketpair");
1041 start_child(PROC_FS, argv0, pipe2fs[1]);
1042 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1043 iev_fs = &fs_ibuf;
1044 iev_fs->handler = handle_dispatch_imsg;
1046 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1047 err(1, "socketpair");
1048 start_child(PROC_NET, argv0, pipe2net[1]);
1049 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1050 iev_net = &net_ibuf;
1051 iev_net->handler = handle_dispatch_imsg;
1053 setproctitle("ui");
1055 /* initialize tofu & load certificates */
1056 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1057 load_certs(&certs);
1059 event_init();
1061 /* Setup event handlers for pipes to fs/net */
1062 iev_fs->events = EV_READ;
1063 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1064 iev_fs->handler, iev_fs);
1065 event_add(&iev_fs->ev, NULL);
1067 iev_net->events = EV_READ;
1068 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1069 iev_net->handler, iev_net);
1070 event_add(&iev_net->ev, NULL);
1072 if (ui_init()) {
1073 load_last_session();
1074 if (has_url || TAILQ_EMPTY(&tabshead))
1075 new_tab(url, NULL);
1077 sandbox_ui_process();
1078 ui_main_loop();
1079 ui_end();
1082 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1083 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1084 imsg_flush(&iev_fs->ibuf);
1085 imsg_flush(&iev_net->ibuf);
1087 close(sessionfd);
1089 return 0;