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 "compat.h"
19 #include <sys/socket.h>
20 #include <sys/wait.h>
22 #include <errno.h>
23 #include <getopt.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
30 #include "defaults.h"
31 #include "fs.h"
32 #include "minibuffer.h"
33 #include "parser.h"
34 #include "session.h"
35 #include "telescope.h"
36 #include "ui.h"
38 static struct option longopts[] = {
39 {"colors", no_argument, NULL, 'C'},
40 {"colours", no_argument, NULL, 'C'},
41 {"help", no_argument, NULL, 'h'},
42 {"safe", no_argument, NULL, 'S'},
43 {"version", no_argument, NULL, 'v'},
44 {NULL, 0, NULL, 0},
45 };
47 static const char *opts = "Cc:hnST:v";
49 static int has_url;
50 static char url[GEMINI_URL_LEN];
52 /*
53 * Used to know when we're finished loading.
54 */
55 int operating;
57 /*
58 * "Safe" (or "sandobox") mode. If enabled, Telescope shouldn't write
59 * anything to the filesystem or execute external programs.
60 */
61 int safe_mode;
63 static struct imsgev *iev_fs, *iev_net;
65 struct tabshead tabshead = TAILQ_HEAD_INITIALIZER(tabshead);
66 struct proxylist proxies = TAILQ_HEAD_INITIALIZER(proxies);
68 enum telescope_process {
69 PROC_UI,
70 PROC_FS,
71 PROC_NET,
72 };
74 #define CANNOT_FETCH 0
75 #define TOO_MUCH_REDIRECTS 1
76 #define MALFORMED_RESPONSE 2
77 #define UNKNOWN_TYPE_OR_CSET 3
78 #define UNKNOWN_PROTOCOL 4
80 /* XXX: keep in sync with normalize_code */
81 const char *err_pages[70] = {
82 [CANNOT_FETCH] = "# Couldn't load the page\n",
83 [TOO_MUCH_REDIRECTS] = "# Too much redirects\n",
84 [MALFORMED_RESPONSE] = "# Got a malformed response\n",
85 [UNKNOWN_TYPE_OR_CSET] = "# Unsupported type or charset\n",
86 [UNKNOWN_PROTOCOL] = "# Unknown protocol\n",
88 [10] = "# Input required\n",
89 [11] = "# Input required\n",
90 [40] = "# Temporary failure\n",
91 [41] = "# Server unavailable\n",
92 [42] = "# CGI error\n",
93 [43] = "# Proxy error\n",
94 [44] = "# Slow down\n",
95 [50] = "# Permanent failure\n",
96 [51] = "# Not found\n",
97 [52] = "# Gone\n",
98 [53] = "# Proxy request refused\n",
99 [59] = "# Bad request\n",
100 [60] = "# Client certificate required\n",
101 [61] = "# Certificate not authorised\n",
102 [62] = "# Certificate not valid\n"
103 };
105 static void die(void) __attribute__((__noreturn__));
106 static struct tab *tab_by_id(uint32_t);
107 static void handle_imsg_err(struct imsg *, size_t);
108 static void handle_imsg_check_cert(struct imsg *, size_t);
109 static void handle_check_cert_user_choice(int, struct tab *);
110 static void handle_maybe_save_new_cert(int, struct tab *);
111 static void handle_imsg_got_code(struct imsg *, size_t);
112 static void handle_imsg_got_meta(struct imsg *, size_t);
113 static void handle_maybe_save_page(int, struct tab *);
114 static void handle_save_page_path(const char *, struct tab *);
115 static void handle_imsg_file_opened(struct imsg *, size_t);
116 static void handle_imsg_buf(struct imsg *, size_t);
117 static void handle_imsg_eof(struct imsg *, size_t);
118 static void handle_imsg_bookmark_ok(struct imsg *, size_t);
119 static void handle_imsg_save_cert_ok(struct imsg *, size_t);
120 static void handle_imsg_update_cert_ok(struct imsg *, size_t);
121 static void handle_imsg_session(struct imsg *, size_t);
122 static void handle_dispatch_imsg(int, short, void *);
123 static int load_about_url(struct tab *, const char *);
124 static int load_file_url(struct tab *, const char *);
125 static int load_finger_url(struct tab *, const char *);
126 static int load_gemini_url(struct tab *, const char *);
127 static int load_gopher_url(struct tab *, const char *);
128 static int load_via_proxy(struct tab *, const char *,
129 struct proxy *);
130 static int make_request(struct tab *, struct get_req *, int,
131 const char *);
132 static int make_fs_request(struct tab *, int, const char *);
133 static int do_load_url(struct tab *, const char *, const char *);
134 static pid_t start_child(enum telescope_process, const char *, int);
136 static struct proto {
137 const char *schema;
138 const char *port;
139 int (*loadfn)(struct tab *, const char *);
140 } protos[] = {
141 {"about", NULL, load_about_url},
142 {"file", NULL, load_file_url},
143 {"finger", "79", load_finger_url},
144 {"gemini", "1965", load_gemini_url},
145 {"gopher", "70", load_gopher_url},
146 {NULL, NULL, NULL},
147 };
149 static imsg_handlerfn *handlers[] = {
150 [IMSG_ERR] = handle_imsg_err,
151 [IMSG_CHECK_CERT] = handle_imsg_check_cert,
152 [IMSG_GOT_CODE] = handle_imsg_got_code,
153 [IMSG_GOT_META] = handle_imsg_got_meta,
154 [IMSG_BUF] = handle_imsg_buf,
155 [IMSG_EOF] = handle_imsg_eof,
156 [IMSG_BOOKMARK_OK] = handle_imsg_bookmark_ok,
157 [IMSG_SAVE_CERT_OK] = handle_imsg_save_cert_ok,
158 [IMSG_UPDATE_CERT_OK] = handle_imsg_update_cert_ok,
159 [IMSG_FILE_OPENED] = handle_imsg_file_opened,
160 [IMSG_SESSION_TAB] = handle_imsg_session,
161 [IMSG_SESSION_TAB_HIST] = handle_imsg_session,
162 [IMSG_SESSION_END] = handle_imsg_session,
163 };
165 static struct ohash certs;
167 static void __attribute__((__noreturn__))
168 die(void)
170 abort(); /* TODO */
173 static struct tab *
174 tab_by_id(uint32_t id)
176 struct tab *t;
178 TAILQ_FOREACH(t, &tabshead, tabs) {
179 if (t->id == id)
180 return t;
183 return NULL;
186 static void
187 handle_imsg_err(struct imsg *imsg, size_t datalen)
189 struct tab *tab;
190 char *page;
192 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
193 return;
195 page = imsg->data;
196 page[datalen-1] = '\0';
198 if (asprintf(&page, "# Error loading %s\n\n> %s\n",
199 tab->hist_cur->h, page) == -1)
200 die();
201 load_page_from_str(tab, page);
202 free(page);
205 static void
206 handle_imsg_check_cert(struct imsg *imsg, size_t datalen)
208 const char *hash, *host, *port;
209 int tofu_res;
210 struct tofu_entry *e;
211 struct tab *tab;
213 hash = imsg->data;
214 if (hash[datalen-1] != '\0')
215 abort();
217 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
218 return;
220 if (tab->proxy != NULL) {
221 host = tab->proxy->host;
222 port = tab->proxy->port;
223 } else {
224 host = tab->uri.host;
225 port = tab->uri.port;
228 if ((e = tofu_lookup(&certs, host, port)) == NULL) {
229 /* TODO: an update in libressl/libretls changed
230 * significantly. Find a better approach at storing
231 * the certs! */
232 if (datalen > sizeof(e->hash))
233 abort();
235 tofu_res = 1; /* trust on first use */
236 if ((e = calloc(1, sizeof(*e))) == NULL)
237 abort();
238 strlcpy(e->domain, host, sizeof(e->domain));
239 if (*port != '\0' && strcmp(port, "1965")) {
240 strlcat(e->domain, ":", sizeof(e->domain));
241 strlcat(e->domain, port, sizeof(e->domain));
243 strlcpy(e->hash, hash, sizeof(e->hash));
244 tofu_add(&certs, e);
245 ui_send_fs(IMSG_SAVE_CERT, tab->id, e, sizeof(*e));
246 } else
247 tofu_res = !strcmp(hash, e->hash);
249 if (tofu_res) {
250 if (e->verified == -1)
251 tab->trust = TS_TEMP_TRUSTED;
252 else if (e->verified == 1)
253 tab->trust = TS_VERIFIED;
254 else
255 tab->trust = TS_TRUSTED;
257 ui_send_net(IMSG_CERT_STATUS, imsg->hdr.peerid,
258 &tofu_res, sizeof(tofu_res));
259 } else {
260 tab->trust = TS_UNTRUSTED;
261 load_page_from_str(tab, "# Certificate mismatch\n");
262 if ((tab->cert = strdup(hash)) == NULL)
263 die();
264 ui_yornp("Certificate mismatch. Proceed?",
265 handle_check_cert_user_choice, tab);
269 static void
270 handle_check_cert_user_choice(int accept, struct tab *tab)
272 ui_send_net(IMSG_CERT_STATUS, tab->id, &accept,
273 sizeof(accept));
275 if (accept) {
276 /*
277 * trust the certificate for this session only. If
278 * the page results in a redirect while we're asking
279 * the user to save, we'll end up with an invalid
280 * tabid (one request == one tab id). It also makes
281 * sense to save it for the current session if the
282 * user accepted it.
283 */
284 tofu_temp_trust(&certs, tab->uri.host, tab->uri.port,
285 tab->cert);
287 if (!safe_mode)
288 ui_yornp("Save the new certificate?",
289 handle_maybe_save_new_cert, tab);
290 else
291 message("Certificate temporarly trusted");
292 } else {
293 free(tab->cert);
294 tab->cert = NULL;
298 static void
299 handle_maybe_save_new_cert(int accept, struct tab *tab)
301 struct tofu_entry *e;
302 const char *host, *port;
304 if (tab->proxy != NULL) {
305 host = tab->proxy->host;
306 port = tab->proxy->port;
307 } else {
308 host = tab->uri.host;
309 port = tab->uri.port;
312 if (!accept)
313 goto end;
315 if ((e = calloc(1, sizeof(*e))) == NULL)
316 die();
318 strlcpy(e->domain, host, sizeof(e->domain));
319 if (*port != '\0' && strcmp(port, "1965")) {
320 strlcat(e->domain, ":", sizeof(e->domain));
321 strlcat(e->domain, port, sizeof(e->domain));
323 strlcpy(e->hash, tab->cert, sizeof(e->hash));
324 ui_send_fs(IMSG_UPDATE_CERT, 0, e, sizeof(*e));
326 tofu_update(&certs, e);
328 tab->trust = TS_TRUSTED;
330 end:
331 free(tab->cert);
332 tab->cert = NULL;
335 static inline int
336 normalize_code(int n)
338 if (n < 20) {
339 if (n == 10 || n == 11)
340 return n;
341 return 10;
342 } else if (n < 30) {
343 return 20;
344 } else if (n < 40) {
345 if (n == 30 || n == 31)
346 return n;
347 return 30;
348 } else if (n < 50) {
349 if (n <= 44)
350 return n;
351 return 40;
352 } else if (n < 60) {
353 if (n <= 53 || n == 59)
354 return n;
355 return 50;
356 } else if (n < 70) {
357 if (n <= 62)
358 return n;
359 return 60;
360 } else
361 return MALFORMED_RESPONSE;
364 static void
365 handle_imsg_got_code(struct imsg *imsg, size_t datalen)
367 struct tab *tab;
369 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
370 return;
372 if (sizeof(tab->code) != datalen)
373 die();
375 memcpy(&tab->code, imsg->data, sizeof(tab->code));
376 tab->code = normalize_code(tab->code);
377 if (tab->code != 30 && tab->code != 31)
378 tab->redirect_count = 0;
381 static void
382 handle_imsg_got_meta(struct imsg *imsg, size_t datalen)
384 struct tab *tab;
385 char buf[128];
387 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL)
388 return;
390 if (sizeof(tab->meta) <= datalen)
391 die();
393 memcpy(tab->meta, imsg->data, datalen);
395 if (tab->code < 10) { /* internal errors */
396 load_page_from_str(tab, err_pages[tab->code]);
397 } else if (tab->code < 20) { /* 1x */
398 load_page_from_str(tab, err_pages[tab->code]);
399 ui_require_input(tab, tab->code == 11, PROTO_GEMINI);
400 } else if (tab->code == 20) {
401 if (setup_parser_for(tab)) {
402 ui_send_net(IMSG_PROCEED, tab->id, NULL, 0);
403 } else if (safe_mode) {
404 load_page_from_str(tab,
405 err_pages[UNKNOWN_TYPE_OR_CSET]);
406 } else {
407 struct hist *h;
409 if ((h = hist_pop(&tab->hist)) != NULL)
410 tab->hist_cur = h;
411 snprintf(buf, sizeof(buf),
412 "Can't display \"%s\", save it?", tab->meta);
413 ui_yornp(buf, handle_maybe_save_page, tab);
415 } else if (tab->code < 40) { /* 3x */
416 tab->redirect_count++;
418 /* TODO: make customizable? */
419 if (tab->redirect_count > 5) {
420 load_page_from_str(tab,
421 err_pages[TOO_MUCH_REDIRECTS]);
422 } else
423 do_load_url(tab, tab->meta, NULL);
424 } else { /* 4x, 5x & 6x */
425 load_page_from_str(tab, err_pages[tab->code]);
429 static void
430 handle_maybe_save_page(int dosave, struct tab *tab)
432 const char *f;
433 char input[PATH_MAX];
435 /* XXX: this print a message that is confusing */
436 ui_on_tab_loaded(tab);
438 if (!dosave) {
439 stop_tab(tab);
440 return;
443 if ((f = strrchr(tab->uri.path, '/')) == NULL)
444 f = "";
445 else
446 f++;
448 strlcpy(input, download_path, sizeof(input));
449 strlcat(input, f, sizeof(input));
451 ui_read("Save to path", handle_save_page_path, tab, input);
454 static void
455 handle_save_page_path(const char *path, struct tab *tab)
457 if (path == NULL) {
458 stop_tab(tab);
459 return;
462 ui_show_downloads_pane();
464 enqueue_download(tab->id, path);
465 ui_send_fs(IMSG_FILE_OPEN, tab->id, path, strlen(path)+1);
467 /*
468 * Change this tab id, the old one is associated with the
469 * download now.
470 */
471 tab->id = tab_new_id();
474 static void
475 handle_imsg_file_opened(struct imsg *imsg, size_t datalen)
477 struct download *d;
478 const char *e;
480 /*
481 * There are no reason we shouldn't be able to find the
482 * required download.
483 */
484 if ((d = download_by_id(imsg->hdr.peerid)) == NULL)
485 die();
487 if (imsg->fd == -1) {
488 e = imsg->data;
489 if (e[datalen-1] != '\0')
490 die();
491 message("Can't open file %s: %s", d->path, e);
492 } else {
493 d->fd = imsg->fd;
494 ui_send_net(IMSG_PROCEED, d->id, NULL, 0);
498 static void
499 handle_imsg_session(struct imsg *imsg, size_t datalen)
501 static struct tab *curr;
502 static struct tab *tab;
503 struct session_tab st;
504 struct session_tab_hist sth;
505 struct hist *h;
506 int first_time;
508 /*
509 * The fs process tried to send tabs after it has announced
510 * that he's done. Something fishy is going on, better die.
511 */
512 if (operating)
513 die();
515 switch (imsg->hdr.type) {
516 case IMSG_SESSION_TAB:
517 if (datalen != sizeof(st))
518 die();
520 memcpy(&st, imsg->data, sizeof(st));
521 if ((tab = new_tab(st.uri, NULL, NULL)) == NULL)
522 die();
523 strlcpy(tab->buffer.page.title, st.title,
524 sizeof(tab->buffer.page.title));
525 if (st.flags & TAB_CURRENT)
526 curr = tab;
527 break;
529 case IMSG_SESSION_TAB_HIST:
530 if (tab == NULL || datalen != sizeof(sth))
531 die();
533 memcpy(&sth, imsg->data, sizeof(sth));
534 if (sth.uri[sizeof(sth.uri)-1] != '\0')
535 die();
537 if ((h = calloc(1, sizeof(*h))) == NULL)
538 die();
539 strlcpy(h->h, sth.uri, sizeof(h->h));
541 if (sth.future)
542 hist_push(&tab->hist, h);
543 else
544 hist_add_before(&tab->hist, tab->hist_cur, h);
545 break;
547 case IMSG_SESSION_END:
548 if (datalen != sizeof(first_time))
549 die();
550 memcpy(&first_time, imsg->data, sizeof(first_time));
551 if (first_time) {
552 new_tab("about:new", NULL, NULL);
553 curr = new_tab("about:help", NULL, NULL);
556 operating = 1;
557 if (curr != NULL)
558 switch_to_tab(curr);
559 if (has_url || TAILQ_EMPTY(&tabshead))
560 new_tab(url, NULL, NULL);
561 ui_main_loop();
562 break;
564 default:
565 die();
569 static void
570 handle_imsg_buf(struct imsg *imsg, size_t datalen)
572 struct tab *tab = NULL;
573 struct download *d = NULL;
575 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
576 (d = download_by_id(imsg->hdr.peerid)) == NULL)
577 return;
579 if (tab != NULL) {
580 if (!parser_parse(tab, imsg->data, datalen))
581 die();
582 ui_on_tab_refresh(tab);
583 } else {
584 d->bytes += datalen;
585 write(d->fd, imsg->data, datalen);
586 ui_on_download_refresh();
590 static void
591 handle_imsg_eof(struct imsg *imsg, size_t datalen)
593 struct tab *tab = NULL;
594 struct download *d = NULL;
596 if ((tab = tab_by_id(imsg->hdr.peerid)) == NULL &&
597 (d = download_by_id(imsg->hdr.peerid)) == NULL)
598 return;
600 if (tab != NULL) {
601 if (!parser_free(tab))
602 die();
603 ui_on_tab_refresh(tab);
604 ui_on_tab_loaded(tab);
605 } else {
606 close(d->fd);
607 d->fd = -1;
608 ui_on_download_refresh();
612 static void
613 handle_imsg_bookmark_ok(struct imsg *imsg, size_t datalen)
615 int res;
617 if (datalen != sizeof(res))
618 die();
620 memcpy(&res, imsg->data, sizeof(res));
621 if (res == 0)
622 message("Added to bookmarks!");
623 else
624 message("Failed to add to bookmarks: %s",
625 strerror(res));
628 static void
629 handle_imsg_save_cert_ok(struct imsg *imsg, size_t datalen)
631 int res;
633 if (datalen != sizeof(res))
634 die();
635 memcpy(&res, imsg->data, datalen);
636 if (res != 0)
637 message("Failed to save the cert for: %s",
638 strerror(res));
641 static void
642 handle_imsg_update_cert_ok(struct imsg *imsg, size_t datalen)
644 int res;
646 if (datalen != sizeof(res))
647 die();
648 memcpy(&res, imsg->data, datalen);
649 if (!res)
650 message("Failed to update the certificate");
653 static void
654 handle_dispatch_imsg(int fd, short ev, void *d)
656 struct imsgev *iev = d;
658 if (dispatch_imsg(iev, ev, handlers, sizeof(handlers)) == -1)
659 err(1, "connection closed");
662 static int
663 load_about_url(struct tab *tab, const char *url)
665 tab->trust = TS_UNKNOWN;
666 parser_init(tab, gemtext_initparser);
667 return make_fs_request(tab, IMSG_GET, url);
670 static int
671 load_file_url(struct tab *tab, const char *url)
673 tab->trust = TS_UNKNOWN;
674 return make_fs_request(tab, IMSG_GET_FILE, tab->uri.path);
677 static int
678 load_finger_url(struct tab *tab, const char *url)
680 struct get_req req;
681 size_t len;
682 char *at;
684 memset(&req, 0, sizeof(req));
685 strlcpy(req.port, tab->uri.port, sizeof(req.port));
687 /*
688 * Sometimes the finger url have the user as path component
689 * (e.g. finger://thelambdalab.xyz/plugd), sometimes as
690 * userinfo (e.g. finger://cobradile@finger.farm).
691 */
692 if ((at = strchr(tab->uri.host, '@')) != NULL) {
693 len = at - tab->uri.host;
694 memcpy(req.req, tab->uri.host, len);
696 if (len >= sizeof(req.req))
697 die();
698 req.req[len] = '\0';
700 strlcpy(req.host, at+1, sizeof(req.host));
701 } else {
702 strlcpy(req.host, tab->uri.host, sizeof(req.host));
704 /* +1 to skip the initial `/' */
705 strlcpy(req.req, tab->uri.path+1, sizeof(req.req));
707 strlcat(req.req, "\r\n", sizeof(req.req));
709 parser_init(tab, textplain_initparser);
710 return make_request(tab, &req, PROTO_FINGER, NULL);
713 static int
714 load_gemini_url(struct tab *tab, const char *url)
716 struct get_req req;
718 memset(&req, 0, sizeof(req));
719 strlcpy(req.host, tab->uri.host, sizeof(req.host));
720 strlcpy(req.port, tab->uri.port, sizeof(req.port));
722 return make_request(tab, &req, PROTO_GEMINI, tab->hist_cur->h);
725 static inline const char *
726 gopher_skip_selector(const char *path, int *ret_type)
728 *ret_type = 0;
730 if (!strcmp(path, "/") || *path == '\0') {
731 *ret_type = '1';
732 return path;
735 if (*path != '/')
736 return path;
737 path++;
739 switch (*ret_type = *path) {
740 case '0':
741 case '1':
742 case '7':
743 break;
745 default:
746 *ret_type = 0;
747 path -= 1;
748 return path;
751 return ++path;
754 static int
755 load_gopher_url(struct tab *tab, const char *url)
757 struct get_req req;
758 int type;
759 const char *path;
761 memset(&req, 0, sizeof(req));
762 strlcpy(req.host, tab->uri.host, sizeof(req.host));
763 strlcpy(req.port, tab->uri.port, sizeof(req.port));
765 path = gopher_skip_selector(tab->uri.path, &type);
766 switch (type) {
767 case '0':
768 parser_init(tab, textplain_initparser);
769 break;
770 case '1':
771 parser_init(tab, gophermap_initparser);
772 break;
773 case '7':
774 ui_require_input(tab, 0, PROTO_GOPHER);
775 return load_page_from_str(tab, err_pages[10]);
776 default:
777 return load_page_from_str(tab, "Unknown gopher selector");
780 strlcpy(req.req, path, sizeof(req.req));
781 if (*tab->uri.query != '\0') {
782 strlcat(req.req, "?", sizeof(req.req));
783 strlcat(req.req, tab->uri.query, sizeof(req.req));
785 strlcat(req.req, "\r\n", sizeof(req.req));
787 return make_request(tab, &req, PROTO_GOPHER, NULL);
790 static int
791 load_via_proxy(struct tab *tab, const char *url, struct proxy *p)
793 struct get_req req;
795 memset(&req, 0, sizeof(req));
796 strlcpy(req.host, p->host, sizeof(req.host));
797 strlcpy(req.port, p->port, sizeof(req.port));
799 tab->proxy = p;
801 return make_request(tab, &req, p->proto, tab->hist_cur->h);
804 static int
805 make_request(struct tab *tab, struct get_req *req, int proto, const char *r)
807 stop_tab(tab);
808 tab->id = tab_new_id();
809 req->proto = proto;
811 if (r != NULL) {
812 strlcpy(req->req, r, sizeof(req->req));
813 strlcat(req->req, "\r\n", sizeof(req->req));
816 ui_send_net(IMSG_GET_RAW, tab->id, req, sizeof(*req));
818 /*
819 * So the various load_*_url can `return make_request` and
820 * do_load_url is happy.
821 */
822 return 1;
825 static int
826 make_fs_request(struct tab *tab, int type, const char *r)
828 stop_tab(tab);
829 tab->id = tab_new_id();
831 ui_send_fs(type, tab->id, r, strlen(r)+1);
833 /*
834 * So load_{about,file}_url can `return make_fs_request` and
835 * do_load_url is happy.
836 */
837 return 1;
840 void
841 gopher_send_search_req(struct tab *tab, const char *text)
843 struct get_req req;
845 start_loading_anim(tab);
847 memset(&req, 0, sizeof(req));
848 strlcpy(req.host, tab->uri.host, sizeof(req.host));
849 strlcpy(req.port, tab->uri.port, sizeof(req.port));
851 /* +2 to skip /7 */
852 strlcpy(req.req, tab->uri.path+2, sizeof(req.req));
853 if (*tab->uri.query != '\0') {
854 strlcat(req.req, "?", sizeof(req.req));
855 strlcat(req.req, tab->uri.query, sizeof(req.req));
858 strlcat(req.req, "\t", sizeof(req.req));
859 strlcat(req.req, text, sizeof(req.req));
860 strlcat(req.req, "\r\n", sizeof(req.req));
862 erase_buffer(&tab->buffer);
863 parser_init(tab, gophermap_initparser);
865 make_request(tab, &req, PROTO_GOPHER, NULL);
868 /*
869 * Effectively load the given url in the given tab. Return 1 when
870 * loading the page asynchronously, and thus when an erase_buffer can
871 * be done right after this function return, or 0 when loading the
872 * page synchronously.
873 */
874 static int
875 do_load_url(struct tab *tab, const char *url, const char *base)
877 struct phos_uri uri;
878 struct proto *p;
879 struct proxy *proxy;
880 char *t;
882 tab->proxy = NULL;
884 tab->trust = TS_UNKNOWN;
886 if (base == NULL)
887 memcpy(&uri, &tab->uri, sizeof(tab->uri));
888 else
889 phos_parse_absolute_uri(base, &uri);
891 if (!phos_resolve_uri_from_str(&uri, url, &tab->uri)) {
892 if (asprintf(&t, "#error loading %s\n>%s\n",
893 url, "Can't parse the URI") == -1)
894 die();
895 strlcpy(tab->hist_cur->h, url, sizeof(tab->hist_cur->h));
896 load_page_from_str(tab, t);
897 free(t);
898 return 0;
901 phos_serialize_uri(&tab->uri, tab->hist_cur->h,
902 sizeof(tab->hist_cur->h));
904 for (p = protos; p->schema != NULL; ++p) {
905 if (!strcmp(tab->uri.scheme, p->schema)) {
906 /* patch the port */
907 if (*tab->uri.port == '\0' && p->port != NULL)
908 strlcpy(tab->uri.port, p->port,
909 sizeof(tab->uri.port));
911 return p->loadfn(tab, url);
915 TAILQ_FOREACH(proxy, &proxies, proxies) {
916 if (!strcmp(tab->uri.scheme, proxy->match_proto))
917 return load_via_proxy(tab, url, proxy);
920 return load_page_from_str(tab, err_pages[UNKNOWN_PROTOCOL]);
923 /*
924 * Load url in tab and handle history. If a tab is marked as lazy, only
925 * prepare the url but don't load it.
926 */
927 void
928 load_url(struct tab *tab, const char *url, const char *base, int nohist)
930 int lazy = tab->flags & TAB_LAZY;
932 if (!nohist && (!lazy || tab->hist_cur == NULL)) {
933 if (tab->hist_cur != NULL)
934 hist_clear_forward(&tab->hist,
935 TAILQ_NEXT(tab->hist_cur, entries));
937 if ((tab->hist_cur = calloc(1, sizeof(*tab->hist_cur)))
938 == NULL) {
939 event_loopbreak();
940 return;
943 strlcpy(tab->buffer.page.title, url,
944 sizeof(tab->buffer.page.title));
945 hist_push(&tab->hist, tab->hist_cur);
947 if (lazy)
948 strlcpy(tab->hist_cur->h, url,
949 sizeof(tab->hist_cur->h));
952 if (!lazy)
953 do_load_url(tab, url, base);
956 void
957 load_url_in_tab(struct tab *tab, const char *url, const char *base, int nohist)
959 if (!operating) {
960 load_url(tab, url, base, nohist);
961 return;
964 autosave_hook();
966 message("Loading %s...", url);
967 start_loading_anim(tab);
968 load_url(tab, url, base, nohist);
971 int
972 load_previous_page(struct tab *tab)
974 struct hist *h;
976 if ((h = TAILQ_PREV(tab->hist_cur, mhisthead, entries)) == NULL)
977 return 0;
978 tab->hist_cur = h;
979 do_load_url(tab, h->h, NULL);
980 return 1;
983 int
984 load_next_page(struct tab *tab)
986 struct hist *h;
988 if ((h = TAILQ_NEXT(tab->hist_cur, entries)) == NULL)
989 return 0;
990 tab->hist_cur = h;
991 do_load_url(tab, h->h, NULL);
992 return 1;
995 void
996 add_to_bookmarks(const char *str)
998 ui_send_fs(IMSG_BOOKMARK_PAGE, 0,
999 str, strlen(str)+1);
1003 * Given a user-entered URL, apply some heuristics to use it:
1005 * - if it's a proper url use it
1006 * - if it starts with a `./' or a `/' assume its a file:// url
1007 * - assume it's a gemini:// url
1009 * `ret' (of which len is the size) will be filled with the resulting
1010 * url.
1012 void
1013 humanify_url(const char *raw, char *ret, size_t len)
1015 struct phos_uri uri;
1016 char buf[PATH_MAX];
1018 if (phos_parse_absolute_uri(raw, &uri)) {
1019 strlcpy(ret, raw, len);
1020 return;
1023 if (has_prefix(raw, "./")) {
1024 strlcpy(ret, "file://", len);
1025 getcwd(buf, sizeof(buf));
1026 strlcat(ret, buf, len);
1027 strlcat(ret, "/", len);
1028 strlcat(ret, raw+2, len);
1029 return;
1032 if (*raw == '/') {
1033 strlcpy(ret, "file://", len);
1034 strlcat(ret, raw, len);
1035 return;
1038 strlcpy(ret, "gemini://", len);
1039 strlcat(ret, raw, len);
1042 static pid_t
1043 start_child(enum telescope_process p, const char *argv0, int fd)
1045 const char *argv[5];
1046 int argc = 0;
1047 pid_t pid;
1049 switch (pid = fork()) {
1050 case -1:
1051 die();
1052 case 0:
1053 break;
1054 default:
1055 close(fd);
1056 return pid;
1059 if (dup2(fd, 3) == -1)
1060 err(1, "cannot setup imsg fd");
1062 argv[argc++] = argv0;
1063 switch (p) {
1064 case PROC_UI:
1065 errx(1, "Can't start ui process");
1066 case PROC_FS:
1067 argv[argc++] = "-Tf";
1068 break;
1069 case PROC_NET:
1070 argv[argc++] = "-Tn";
1071 break;
1074 if (safe_mode)
1075 argv[argc++] = "-S";
1077 argv[argc++] = NULL;
1078 execvp(argv0, (char *const *)argv);
1079 err(1, "execvp(%s)", argv0);
1082 int
1083 ui_send_net(int type, uint32_t peerid, const void *data,
1084 uint16_t datalen)
1086 return imsg_compose_event(iev_net, type, peerid, 0, -1, data,
1087 datalen);
1090 int
1091 ui_send_fs(int type, uint32_t peerid, const void *data, uint16_t datalen)
1093 return imsg_compose_event(iev_fs, type, peerid, 0, -1, data,
1094 datalen);
1097 static void __attribute__((noreturn))
1098 usage(int r)
1100 fprintf(stderr, "USAGE: %s [-ChnSv] [-c config] [url]\n",
1101 getprogname());
1102 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1103 exit(r);
1106 int
1107 main(int argc, char * const *argv)
1109 struct imsgev net_ibuf, fs_ibuf;
1110 pid_t pid;
1111 int pipe2net[2], pipe2fs[2];
1112 int ch, configtest = 0, fail = 0;
1113 int proc = -1;
1114 int sessionfd = -1;
1115 int status;
1116 const char *argv0;
1118 argv0 = argv[0];
1120 signal(SIGCHLD, SIG_IGN);
1121 signal(SIGPIPE, SIG_IGN);
1123 if (getenv("NO_COLOR") != NULL)
1124 enable_colors = 0;
1126 fs_init();
1128 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
1129 switch (ch) {
1130 case 'C':
1131 exit(ui_print_colors());
1132 case 'c':
1133 fail = 1;
1134 strlcpy(config_path, optarg, sizeof(config_path));
1135 break;
1136 case 'n':
1137 configtest = 1;
1138 break;
1139 case 'h':
1140 usage(0);
1141 case 'S':
1142 safe_mode = 1;
1143 break;
1144 case 'T':
1145 switch (*optarg) {
1146 case 'f':
1147 proc = PROC_FS;
1148 break;
1149 case 'n':
1150 proc = PROC_NET;
1151 break;
1152 default:
1153 errx(1, "invalid process spec %c",
1154 *optarg);
1156 break;
1157 case 'v':
1158 printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1159 exit(0);
1160 break;
1161 default:
1162 usage(1);
1166 argc -= optind;
1167 argv += optind;
1169 if (proc != -1) {
1170 if (argc > 0)
1171 usage(1);
1172 else if (proc == PROC_FS)
1173 return fs_main();
1174 else if (proc == PROC_NET)
1175 return net_main();
1176 else
1177 usage(1);
1180 if (argc != 0) {
1181 has_url = 1;
1182 humanify_url(argv[0], url, sizeof(url));
1185 /* setup keys before reading the config */
1186 TAILQ_INIT(&global_map.m);
1187 global_map.unhandled_input = global_key_unbound;
1188 TAILQ_INIT(&minibuffer_map.m);
1190 config_init();
1191 parseconfig(config_path, fail);
1192 if (configtest) {
1193 puts("config OK");
1194 exit(0);
1197 if (download_path == NULL &&
1198 (download_path = strdup("/tmp/")) == NULL)
1199 errx(1, "strdup");
1201 if (!safe_mode && (sessionfd = lock_session()) == -1)
1202 errx(1, "can't lock session, is another instance of "
1203 "telescope already running?");
1205 /* Start children. */
1206 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2fs) == -1)
1207 err(1, "socketpair");
1208 start_child(PROC_FS, argv0, pipe2fs[1]);
1209 imsg_init(&fs_ibuf.ibuf, pipe2fs[0]);
1210 iev_fs = &fs_ibuf;
1211 iev_fs->handler = handle_dispatch_imsg;
1213 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe2net) == -1)
1214 err(1, "socketpair");
1215 start_child(PROC_NET, argv0, pipe2net[1]);
1216 imsg_init(&net_ibuf.ibuf, pipe2net[0]);
1217 iev_net = &net_ibuf;
1218 iev_net->handler = handle_dispatch_imsg;
1220 setproctitle("ui");
1222 /* initialize tofu & load certificates */
1223 tofu_init(&certs, 5, offsetof(struct tofu_entry, domain));
1224 load_certs(&certs);
1226 event_init();
1228 /* Setup event handler for the autosave */
1229 autosave_init();
1231 /* Setup event handlers for pipes to fs/net */
1232 iev_fs->events = EV_READ;
1233 event_set(&iev_fs->ev, iev_fs->ibuf.fd, iev_fs->events,
1234 iev_fs->handler, iev_fs);
1235 event_add(&iev_fs->ev, NULL);
1237 iev_net->events = EV_READ;
1238 event_set(&iev_net->ev, iev_net->ibuf.fd, iev_net->events,
1239 iev_net->handler, iev_net);
1240 event_add(&iev_net->ev, NULL);
1242 if (ui_init()) {
1243 sandbox_ui_process();
1244 event_dispatch();
1245 ui_end();
1248 ui_send_fs(IMSG_QUIT, 0, NULL, 0);
1249 ui_send_net(IMSG_QUIT, 0, NULL, 0);
1250 imsg_flush(&iev_fs->ibuf);
1251 imsg_flush(&iev_net->ibuf);
1253 /* wait for children to terminate */
1254 do {
1255 pid = wait(&status);
1256 if (pid == -1) {
1257 if (errno != EINTR && errno != ECHILD)
1258 err(1, "wait");
1259 } else if (WIFSIGNALED(status))
1260 warnx("child terminated; signal %d", WTERMSIG(status));
1261 } while (pid != -1 || (pid == -1 && errno == EINTR));
1263 if (!safe_mode && close(sessionfd) == -1)
1264 err(1, "close(sessionfd = %d)", sessionfd);
1266 return 0;