forked from kieselsteini/delve
-
Notifications
You must be signed in to change notification settings - Fork 2
/
gplaces.c
1837 lines (1506 loc) · 58.5 KB
/
gplaces.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
================================================================================
gplaces - a simple terminal Gemini client
Copyright (C) 2022 - 2024 Dima Krasner
Copyright (C) 2019 Sebastian Steinhauer
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
================================================================================
*/
/*============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <wchar.h>
#include <locale.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <regex.h>
#include <sys/mman.h>
#include <dirent.h>
#include "queue.h"
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/x509.h>
#include <openssl/ec.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <curl/curl.h>
#ifdef GPLACES_USE_LIBIDN2
#include <idn2.h>
#elif defined(GPLACES_USE_LIBIDN)
#include <idna.h>
#endif
#ifdef GPLACES_USE_LIBMAGIC
#include <magic.h>
#endif
#include "bestline/bestline.h"
/*============================================================================*/
typedef struct Selector Selector;
typedef SIMPLEQ_HEAD(, Selector) SelectorList;
typedef struct URL URL;
typedef struct Page Page;
typedef TAILQ_HEAD(PageList, Page) PageList;
typedef void (*Parser)(char *, int *pre, Selector **, SelectorList *);
typedef struct Protocol {
const char *scheme, *port;
int (*read)(void *, void *, int);
int (*peek)(void *, void *, int);
int (*error)(const URL *, void *, int);
void (*close)(void *);
void *(*download)(const Selector *, URL *, char **mime, Parser *, unsigned int redirs, int ask);
int (*set_input)(URL *url, const char *input);
} Protocol;
struct Selector {
SIMPLEQ_ENTRY(Selector) next;
int level;
#if defined(GPLACES_WITH_SPARTAN)
char prompt;
#endif
char type, *repr, *rawurl;
CURLU *cu;
};
struct URL {
char *scheme, *host, *port, *path, *url;
CURLU *cu;
const Protocol *proto;
};
struct Page {
char prompt[256];
SelectorList menu;
time_t fetched;
char *url;
TAILQ_ENTRY(Page) next;
};
typedef struct Variable {
LIST_ENTRY(Variable) next;
char *name, *data;
} Variable;
typedef LIST_HEAD(, Variable) VariableList;
typedef struct Command {
const char *name;
void (*func)(char *line);
} Command;
/*============================================================================*/
const Protocol gemini;
#ifdef GPLACES_WITH_TITAN
const Protocol titan;
#endif
#ifdef GPLACES_WITH_GOPHERS
const Protocol gophers;
#endif
#ifdef GPLACES_WITH_GOPHER
const Protocol gopher;
#endif
#ifdef GPLACES_WITH_SPARTAN
const Protocol spartan;
#endif
#ifdef GPLACES_WITH_FINGER
const Protocol finger;
#endif
#ifdef GPLACES_WITH_GUPPY
const Protocol guppy;
#endif
/*============================================================================*/
static VariableList variables = LIST_HEAD_INITIALIZER(variables);
static SelectorList subscriptions = SIMPLEQ_HEAD_INITIALIZER(subscriptions);
static PageList history = TAILQ_HEAD_INITIALIZER(history);
static const Selector feed_sel = {.rawurl = "gplaces://sub/"};
SelectorList blank = SIMPLEQ_HEAD_INITIALIZER(blank);
#define currentmenu TAILQ_EMPTY(&history) ? blank : TAILQ_FIRST(&history)->menu
#define currenturl TAILQ_EMPTY(&history) ? NULL : TAILQ_FIRST(&history)->url
static int depth;
static int interactive;
static int color;
static int inshell;
/*============================================================================*/
__attribute__((format(printf, 2, 3)))
static void error(int fatal, const char *fmt, ...) {
va_list va;
if (color) fwrite("\33[31m\n", 1, 6, stderr);
else fputc('\n', stderr);
va_start(va, fmt);
vfprintf(stderr, fmt, va);
va_end(va);
if (color) fwrite("\33[0m\n", 1, 5, stderr);
else fputc('\n', stderr);
if (fatal) exit(EXIT_FAILURE);
}
/*============================================================================*/
static char *str_copy(const char *str) {
char *new;
if ((new = strdup(str)) == NULL) error(1, "cannot allocate new string");
return new;
}
/*============================================================================*/
static void free_variables(VariableList *vars) {
Variable *var, *tmp;
LIST_FOREACH_SAFE(var, vars, next, tmp) {
free(var->name);
free(var->data);
free(var);
}
}
static char *set_var(VariableList *list, const char *name, const char *value) {
Variable *var;
if (name == NULL) return NULL;
LIST_FOREACH(var, list, next) {
if (!strcasecmp(var->name, name)) break;
}
if (value) {
if (var == NULL) {
if ((var = malloc(sizeof(Variable))) == NULL) error(1, "cannot allocate new variable");
var->name = str_copy((char*)name);
var->data = str_copy(value);
LIST_INSERT_HEAD(list, var, next);
} else {
free(var->data);
var->data = str_copy(value);
}
}
return var ? var->data : NULL;
}
static int get_var_integer(const char *name, int def) {
int value;
char *data = set_var(&variables, name, NULL);
if (data == NULL || sscanf(data, "%d", &value) != 1) return def;
return value;
}
/*============================================================================*/
static void *map_file(const char *name, int *fd, size_t *size) {
static char path[1024];
struct stat stbuf;
const char *home;
void *p;
if ((home = getenv("XDG_DATA_HOME")) != NULL) snprintf(path, sizeof(path), "%s/gplaces_%s", home, name);
else if ((home = getenv("HOME")) != NULL) snprintf(path, sizeof(path), "%s/.gplaces_%s", home, name);
else return NULL;
if ((*fd = open(path, O_RDWR | O_CREAT | O_APPEND, 0600)) == -1) return NULL;
if (fstat(*fd, &stbuf) == -1) { close(*fd); return NULL; }
if ((*size = (size_t)stbuf.st_size) == 0) return NULL;
if ((p = mmap(NULL, stbuf.st_size % SIZE_MAX, PROT_READ | PROT_WRITE, MAP_SHARED, *fd, 0)) == MAP_FAILED) { close(*fd); return NULL; }
return p;
}
__attribute__((format(printf, 2, 3)))
static int append_line(int fd, const char *fmt, ...) {
va_list va;
FILE *fp;
int ret;
if ((fp = fdopen(fd, "a")) == NULL) return 0;
va_start(va, fmt);
ret = vfprintf(fp, fmt, va) > 0;
va_end(va);
fclose(fp);
return ret;
}
/*============================================================================*/
static Selector *new_selector(const char type) {
Selector *new = calloc(1, sizeof(Selector));
if (new == NULL) error(1, "cannot allocate new selector");
new->type = type;
return new;
}
static void free_selector(Selector *sel) {
free(sel->repr);
free(sel->rawurl);
free(sel);
}
static void free_url(URL *url) {
curl_free(url->scheme);
curl_free(url->host);
if (url->proto != NULL && url->port != url->proto->port) curl_free(url->port);
curl_free(url->path);
curl_free(url->url);
if (url->cu != NULL) curl_url_cleanup(url->cu);
}
static void free_selectors(SelectorList *list) {
Selector *sel, *tmp;
SIMPLEQ_FOREACH_SAFE(sel, list, next, tmp) free_selector(sel);
}
static int set_query(URL *url, const char *input) {
char *query, *tmp;
if ((query = curl_easy_escape(NULL, input, 0)) == NULL) return 0;
if (curl_url_set(url->cu, CURLUPART_QUERY, query, CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK || curl_url_get(url->cu, CURLUPART_URL, &tmp, 0) != CURLUE_OK) { curl_free(query); return 0; }
curl_free(url->url); url->url = tmp;
curl_free(query);
return 1;
}
#if defined(GPLACES_WITH_TITAN) || defined(GPLACES_WITH_GOPHER) || defined(GPLACES_WITH_GOPHERS) || defined(GPLACSE_WITH_FINGER)
static int set_fragment(URL *url, const char *input) {
char *tmp;
if (curl_url_set(url->cu, CURLUPART_FRAGMENT, input, CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK || curl_url_get(url->cu, CURLUPART_URL, &tmp, 0) != CURLUE_OK) return 0;
curl_free(url->url); url->url = tmp;
return 1;
}
#endif
static int parse_url(URL *url, const char *rawurl, const char *from, const char *input) {
static char buffer[1024];
#if defined(GPLACES_USE_LIBIDN2) || defined(GPLACES_USE_LIBIDN)
char *host;
#endif
int file;
if ((url->cu == NULL && (url->cu = curl_url()) == NULL) || (from != NULL && curl_url_set(url->cu, CURLUPART_URL, from, CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK)) return 0;
/* TODO: why does curl_url_set() return CURLE_OUT_OF_MEMORY if the scheme is missing, but only inside the Flatpak sandbox? */
if (curl_url_set(url->cu, CURLUPART_URL, rawurl, CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK) {
#if defined(GPLACES_WITH_GOPHER) && defined(CURLU_ALLOW_SPACE)
if (strncmp(rawurl, "gopher://", 9) == 0) {
if (curl_url_set(url->cu, CURLUPART_URL, rawurl, CURLU_NON_SUPPORT_SCHEME | CURLU_ALLOW_SPACE) == CURLUE_OK) goto valid;
return 0;
}
#endif
#if defined(GPLACES_WITH_GOPHERS) && defined(CURLU_ALLOW_SPACE)
if (strncmp(rawurl, "gophers://", 10) == 0) {
if (curl_url_set(url->cu, CURLUPART_URL, rawurl, CURLU_NON_SUPPORT_SCHEME | CURLU_ALLOW_SPACE) == CURLUE_OK) goto valid;
return 0;
}
#endif
snprintf(buffer, sizeof(buffer), "gemini://%s", rawurl);
if (curl_url_set(url->cu, CURLUPART_URL, buffer, CURLU_NON_SUPPORT_SCHEME) != CURLUE_OK) return 0;
}
#if (defined(GPLACES_WITH_GOPHER) || defined(GPLACES_WITH_GOPHERS)) && defined(CURLU_ALLOW_SPACE)
valid:
#endif
if (curl_url_get(url->cu, CURLUPART_SCHEME, &url->scheme, 0) != CURLUE_OK) return 0;
if (strcmp(url->scheme, "gemini") == 0) {
url->proto = &gemini;
#ifdef GPLACES_WITH_TITAN
} else if (strcmp(url->scheme, "titan") == 0) {
url->proto = &titan;
#endif
#ifdef GPLACES_WITH_GOPHER
} else if (strcmp(url->scheme, "gopher") == 0) {
url->proto = &gopher;
#endif
#ifdef GPLACES_WITH_GOPHERS
} else if (strcmp(url->scheme, "gophers") == 0) {
url->proto = &gophers;
#endif
#ifdef GPLACES_WITH_SPARTAN
} else if (strcmp(url->scheme, "spartan") == 0) {
url->proto = &spartan;
#endif
#ifdef GPLACES_WITH_FINGER
} else if (strcmp(url->scheme, "finger") == 0) {
url->proto = &finger;
#endif
#ifdef GPLACES_WITH_GUPPY
} else if (strcmp(url->scheme, "guppy") == 0) {
url->proto = &guppy;
#endif
}
if (input != NULL && input[0] != '\0' && !url->proto->set_input(url, input)) return 0;
else if ((input == NULL || input[0] == '\0') && curl_url_get(url->cu, CURLUPART_URL, &url->url, 0) != CURLUE_OK) return 0;
if (!(file = (strcmp(url->scheme, "file")) == 0) && curl_url_get(url->cu, CURLUPART_HOST, &url->host, 0) != CURLUE_OK) return 0;
#if defined(GPLACES_USE_LIBIDN2) || defined(GPLACES_USE_LIBIDN)
#ifdef GPLACES_USE_LIBIDN2
if (!file && (idn2_to_ascii_8z(url->host, &host, IDN2_NONTRANSITIONAL) == IDN2_OK || idn2_to_ascii_8z(url->host, &host, IDN2_TRANSITIONAL) == IDN2_OK)) {
#elif defined(GPLACES_USE_LIBIDN)
if (!file && idna_to_ascii_8z(url->host, &host, 0) == IDNA_SUCCESS) {
#endif
if (curl_url_set(url->cu, CURLUPART_HOST, host, 0) != CURLUE_OK) { free(host); return 0; }
free(host);
curl_free(url->host); url->host = NULL;
if (curl_url_get(url->cu, CURLUPART_HOST, &url->host, 0) != CURLUE_OK) return 0;
}
#endif
if (curl_url_get(url->cu, CURLUPART_PATH, &url->path, 0) != CURLUE_OK) return 0;
if (file) return 1;
switch (curl_url_get(url->cu, CURLUPART_PORT, &url->port, 0)) {
case CURLUE_OK: break;
case CURLUE_NO_PORT:
if (url->proto != NULL) url->port = str_copy(url->proto->port);
break;
/* fall through */
default: return 0;
}
return 1;
}
static int redirect(URL *url, const char *to, size_t len, int ask) {
URL tmp = {0};
char *rawurl;
if ((rawurl = len > 0 ? strndup(to, len) : strdup(to)) == NULL) error(1, "cannot allocate new string");
if (!parse_url(&tmp, rawurl, url->url, NULL)) { free(rawurl); return 40; }
free(rawurl);
free_url(url);
memcpy(url, &tmp, sizeof(URL));
fprintf(stderr, "redirected to `%s`\n", url->url);
if (ask) bestlineHistoryAdd(url->url);
return 31;
}
static int perm_redirect(URL *url, const char *to, int ask) {
size_t size = 1, len;
const char *p, *start, *end;
int fd, ret = 20, found = 0;
len = strlen(url->url);
if ((p = map_file("redirs", &fd, &size)) == NULL && size > 0) return 40;
else if (p != NULL) {
for (end = p; !found && (start = memmem(end, size - (end - p), url->url, len)) != NULL; end = start + len + 1) {
if (!(found = ((start == p || *(start - 1) == '\n') && size - (start - p) >= len + 2 && start[len] == ' ' && start[len + 1] != '\n'))) continue;
ret = redirect(url, &start[len + 1], strcspn(&start[len + 1], " \n"), ask);
}
munmap((void *)p, size);
}
if (to != NULL && !found) ret = append_line(fd, "%s %s\n", url->url, to) ? redirect(url, to, -1, ask) : 40;
close(fd);
return ret;
}
static const Selector *find_selector(const SelectorList list, int index) {
const Selector *sel;
long i = 0;
SIMPLEQ_FOREACH(sel, &list, next) if (sel->type == 'l' && ++i == index) return sel;
return NULL;
}
static int copy_url(Selector *sel, const char *url) {
if (url == NULL || *url == '\0') return 0;
sel->rawurl = str_copy(url);
return 1;
}
/*============================================================================*/
static void free_page(Page *page) {
free_selectors(&page->menu);
free(page->url);
free(page);
}
static void free_history(PageList *pages) {
Page *page, *tmp;
TAILQ_FOREACH_SAFE(page, pages, next, tmp) free_page(page);
}
static void history_pop(void) {
Page *page = TAILQ_LAST(&history, PageList);
TAILQ_REMOVE(&history, page, next);
free_selectors(&page->menu);
free(page->url);
free(page);
}
static void history_push(const char *url, SelectorList menu, const char *fmt, ...) {
va_list va;
Page *page;
int max;
if ((max = get_var_integer("HISTSIZE", 10)) < 1) max = 1;
if ((page = malloc(sizeof(Page))) == NULL) error(1, "cannot allocate new page");
page->url = url == NULL ? NULL : str_copy(url);
va_start(va, fmt);
vsnprintf(page->prompt, sizeof(page->prompt), fmt, va);
va_end(va);
page->menu = menu;
if (time(&page->fetched) == -1) page->fetched = 0;
for (; depth > 0 && depth >= max; --depth) history_pop();
TAILQ_INSERT_HEAD(&history, page, next);
++depth;
}
static Page *history_lookup(const char *url) {
Page *page, *tmp;
TAILQ_FOREACH_SAFE(page, &history, next, tmp) {
if (page->url == NULL || strcmp(page->url, url) != 0) continue;
TAILQ_REMOVE(&history, page, next);
TAILQ_INSERT_HEAD(&history, page, next);
return page;
}
return NULL;
}
/*============================================================================*/
static int socket_connect(const URL *url, int socktype) {
struct addrinfo hints = {.ai_family = AF_UNSPEC, .ai_socktype = socktype}, *result, *it;
struct timeval tv = {0};
int timeout, err, fd = -1;
if ((timeout = get_var_integer("TIMEOUT", 15)) < 1) timeout = 15;
tv.tv_sec = timeout;
if ((err = getaddrinfo(url->host, url->port, &hints, &result)) != 0) {
error(0, "cannot resolve hostname `%s`: %s", url->host, gai_strerror(err));
return -1;
}
for (it = result; it && err != EINTR; it = it->ai_next) {
if ((fd = socket(it->ai_family, it->ai_socktype, it->ai_protocol)) == -1) { err = errno; continue; }
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == 0 && setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == 0 && setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == 0 && connect(fd, it->ai_addr, it->ai_addrlen) == 0) break;
err = errno;
close(fd); fd = -1;
}
freeaddrinfo(result);
if (fd == -1 && err == EINPROGRESS) error(0, "cannot connect to `%s`:`%s`: cancelled", url->host, url->port);
else if (fd == -1 && err != 0) error(0, "cannot connect to `%s`:`%s`: %s", url->host, url->port, strerror(err));
return fd;
}
static int tcp_connect(const URL *url) {
return socket_connect(url, SOCK_STREAM);
}
/*============================================================================*/
static void parse_plaintext_line(char *line, int *pre, Selector **sel, SelectorList *list) {
(void)pre;
(void)index;
*sel = new_selector('`');
(*sel)->repr = str_copy(line);
SIMPLEQ_INSERT_TAIL(list, *sel, next);
}
static void parse_gemtext_line(char *line, int *pre, Selector **sel, SelectorList *list) {
char *url;
int level;
*sel = NULL;
if (strncmp(line, "```", 3) == 0) {
*pre = !*pre;
return;
}
if (*pre) {
*sel = new_selector('`');
(*sel)->repr = str_copy(line);
} else if (line[0] == '=' && line[1] == '>') {
*sel = new_selector('l');
url = line + 2 + strspn(line + 2, " \t");
line = url + strcspn(url, " \t");
if (*line != '\0') {
*line = '\0';
line += 1 + strspn(line + 1, " \t");
}
if (!copy_url(*sel, url)) { free_selector(*sel); *sel = NULL; return; }
if (*line) (*sel)->repr = str_copy(line);
else (*sel)->repr = str_copy(url);
} else if (line[0] == '#' && (level = 1 + strspn(&line[1], "#")) <= 3) {
*sel = new_selector('#');
(*sel)->repr = str_copy(line + level + strspn(line + level, " \t"));
(*sel)->level = level;
} else if (*line == '>' || (line[0] == '*' && line[1] == ' ')) {
*sel = new_selector(*line);
(*sel)->repr = str_copy(line + 1 + strspn(line + 1, " \t"));
} else {
*sel = new_selector('i');
(*sel)->repr = str_copy(line);
}
SIMPLEQ_INSERT_TAIL(list, *sel, next);
}
static SelectorList parse_file(FILE *fp, const Parser parser) {
static char buffer[LINE_MAX];
char *line;
SelectorList list = SIMPLEQ_HEAD_INITIALIZER(list);
size_t len;
Selector *sel;
int pre = 0, start = 1;
for (sel = NULL; (line = fgets(buffer, sizeof(buffer), fp)) != NULL; sel = NULL, start = 0) {
if ((len = strlen(line)) > 1 && buffer[len - 2] == '\r') buffer[len - 2] = '\0';
else if (line[len - 1] == '\n') line[len - 1] = '\0';
parser((start && strncmp(line, "\xef\xbb\xbf", 3) == 0) ? line + 3: line, &pre, &sel, &list);
}
return list;
}
/*============================================================================*/
static char *next_token(char **str) {
char *begin;
if (*str == NULL) return NULL;
*str += strspn(*str, " \v\t");
switch (**str) {
case '\0': case '#': return NULL;
case '"': ++*str; return strtok_r(*str, "\"", str);
default:
begin = *str;
*str += strcspn(*str, " \v\t");
if (**str != '\0') { **str = '\0'; ++*str; }
return begin;
}
}
static int get_terminal_width() {
struct winsize wz;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &wz);
return wz.ws_col > 20 ? wz.ws_col : 20;
}
/*============================================================================*/
static const char *find_mime_handler(const char *mime) {
Variable *var;
const char *handler = NULL;
size_t length, longest = 0;
LIST_FOREACH(var, &variables, next) {
if ((length = strlen(var->name)) > longest && !strncasecmp(mime, var->name, length)) {
longest = length;
handler = var->data;
}
}
if (!handler) fprintf(stderr, "no handler for `%s`\n", mime);
return handler;
}
static void reap(const char *command, pid_t pid, int silent) {
pid_t ret;
int status;
while ((ret = waitpid(pid, &status, 0)) < 0 && errno == EINTR);
if (!silent && ret == pid && WIFEXITED(status)) fprintf(stderr, "`%s` has exited with exit status %d\n", command, WEXITSTATUS(status));
else if (ret == pid && !WIFEXITED(status)) fprintf(stderr, "`%s` has exited abnormally\n", command);
}
static pid_t start_handler(const char *handler, const char *filename, char *command, size_t length, const Selector *sel, const URL *url, int stdin) {
static char buffer[sizeof("/proc/self/fd/2147483647")];
size_t i;
pid_t pid;
if (stdin != -1) {
sprintf(buffer, "/proc/self/fd/%d", stdin);
filename = buffer;
}
for (i = 0; *handler && i < length - 1; ) {
if (handler[0] == '%' && handler[1] != '\0') {
const char *append = "";
switch (handler[1]) {
case '%': append = "%"; break;
case 's': append = url->scheme; break;
case 'h': append = url->host; break;
case 'p': append = url->port; break;
case 'P': append = url->path; break;
case 'r': append = sel->repr; break;
case 'u': append = url->url; break;
case 'f': append = filename; break;
}
handler += 2;
while (*append && i < length - 1) command[i++] = *append++;
} else command[i++] = *handler++;
}
command[i] = '\0';
if ((pid = fork()) == 0) {
#ifdef GPLACES_USE_FLATPAK_SPAWN
if (stdin == -1) execl("/usr/bin/flatpak-spawn", "flatpak-spawn", "--host", "--", "sh", "-c", command, (char *)NULL);
else {
sprintf(buffer, "--forward-fd=%d", stdin);
execl("/usr/bin/flatpak-spawn", "flatpak-spawn", "--host", buffer, "--", "sh", "-c", command, (char *)NULL);
}
#else
execl("/bin/sh", "sh", "-c", command, (char *)NULL);
#endif
exit(EXIT_FAILURE);
} else if (pid < 0) error(0, "could not execute `%s`", command);
return pid;
}
static void execute_handler(const char *handler, const char *filename, const Selector *sel, const URL *url) {
static char command[1024];
pid_t pid;
if ((pid = start_handler(handler, filename, command, sizeof(command), sel, url, -1)) > 0) reap(command, pid, 0);
}
/*============================================================================*/
static int ndigits(int n) {
int digits = 0;
for ( ; n > 0; n /= 10, ++digits);
return digits;
}
static void print_line(FILE *fp, const Selector *sel, const regex_t *filter, int width, int *links) {
mbstate_t ps;
size_t size, mbs;
wchar_t wchar;
const char *p;
int w, wchars, out, extra, i = 0;
if (sel->type == 'l') ++*links;
if (filter && regexec(filter, sel->repr, 0, NULL, 0) != 0 && (sel->rawurl == NULL || regexec(filter, sel->rawurl, 0, NULL, 0) != 0)) return;
if (!interactive) { fprintf(fp, "%s\n", sel->repr); return; }
size = strlen(sel->repr);
do {
out = (int)size;
extra = 0;
switch (sel->type) {
case 'l': if (i == 0) extra = 3 + ndigits(*links); break;
case '`': goto print;
case '>':
case '*': extra = 2; break;
case '#': if (i == 0) extra = sel->level + 1;
}
memset(&ps, 0, sizeof(ps));
for (wchars = 0, out = 0, p = &sel->repr[i]; out < (int)size - i && wchars < width - extra; out += mbs, p = &sel->repr[i + out], wchars += w) {
if ((mbs = mbrtowc(&wchar, p, size - i - out, &ps)) == (size_t)-1 || mbs == (size_t)-2 || mbs == 0 || (w = wcwidth(wchar)) < 0) {
/* best-effort, we assume 1 character == 1 byte */
mbs = 1;
w = 1;
} else if (wchars + w > width - extra) break;
}
/* if it's a full line followed by a non-whitespace character, drop the cut word from the end */
if (wchars + extra == width && i + out < (int)size && sel->repr[i + out] != ' ' && sel->repr[i + out] != '\t') {
for (p = &sel->repr[i + out - 1]; p >= &sel->repr[i] && *p != ' ' && *p != '\t'; --p);
if (p > &sel->repr[i]) out = p - &sel->repr[i];
}
print:
switch (sel->type) {
case 'l':
if (i == 0) {
if (color) fprintf(fp, "\33[4;36m[%d]\33[0;39m %.*s\n", *links, out, &sel->repr[i]);
else fprintf(fp, "[%d] %.*s\n", *links, out, &sel->repr[i]);
break;
}
/* fall through */
case 'i': fprintf(fp, "%.*s\n", out, &sel->repr[i]); break;
case '#':
if (i == 0 && color) fprintf(fp, "\33[4m%.*s %.*s\33[0m\n", sel->level, "###", out, &sel->repr[i]);
else if (i == 0 && !color) fprintf(fp, "%.*s %.*s\n", sel->level, "###", out, &sel->repr[i]);
else if (color) fprintf(fp, "\33[4m%.*s\33[0m\n", out, &sel->repr[i]);
else fprintf(fp, "%.*s\n", out, &sel->repr[i]);
break;
case '`':
fprintf(fp, "%s\n", &sel->repr[i]);
break;
case '>':
fprintf(fp, "%c %.*s\n", sel->type, out, &sel->repr[i]);
break;
default:
if (i == 0) fprintf(fp, "%c %.*s\n", sel->type, out, &sel->repr[i]);
else fprintf(fp, " %.*s\n", out, &sel->repr[i]);
}
i += out + strspn(&sel->repr[i + out], " ");
} while (i < (int)size);
}
static void print_text(FILE *fp, const SelectorList list, const char *filter) {
regex_t re;
const Selector *sel;
int width, links = 0;
if (filter && regcomp(&re, filter, REG_NOSUB) != 0) filter = NULL;
width = get_terminal_width();
SIMPLEQ_FOREACH(sel, &list, next) print_line(fp, sel, filter ? &re : NULL, width, &links);
if (filter) regfree(&re);
}
/*============================================================================*/
static int tofu(X509 *cert, const URL *url, int ask) {
static char buffer[1024], hex[EVP_MAX_MD_SIZE * 2 + 1];
static unsigned char md[EVP_MAX_MD_SIZE];
size_t size = 1, hlen, plen;
const char *p, *end;
char *line, *start;
unsigned int mdlen, i;
int fd = -1, found = 0, trust = 0;
if (X509_digest(cert, EVP_sha512(), md, &mdlen) == 0) return 0;
for (i = 0; i < mdlen; ++i) {
hex[i * 2] = "0123456789ABCDEF"[md[i] >> 4];
hex[i * 2 + 1] = "0123456789ABCDEF"[md[i] & 0xf];
}
hex[mdlen * 2] = '\0';
hlen = strlen(url->host);
plen = strlen(url->port);
if ((p = map_file("hosts", &fd, &size)) == NULL && size > 0) return 0;
else if (p != NULL) {
for (end = p; !found && (start = memmem(end, size - (end - p), url->host, hlen)) != NULL; end = start + hlen + 1) {
if (!(found = ((start == p || *(start - 1) == '\n') && size - (start - p) >= hlen + 1 + plen + 1 + mdlen * 2 + 1 && start[hlen] == ':' && memcmp(&start[hlen + 1], url->port, plen) == 0 && start[hlen + 1 + plen] == ' ' && start[hlen + 1 + plen + 1 + mdlen * 2] == '\n'))) continue;
if ((trust = memcmp(&start[hlen + 1 + plen + 1], hex, mdlen * 2) == 0) || !ask) break;
if (color) snprintf(buffer, sizeof(buffer), "\33[35mTrust new certificate for `%s:%s`? (y/n)>\33[0m ", url->host, url->port);
else snprintf(buffer, sizeof(buffer), "Trust new certificate for `%s:%s`? (y/n)> ", url->host, url->port);
if ((line = bestline(buffer)) != NULL) {
if (*line == 'y' || *line == 'Y') {
memcpy(&start[hlen + 1 + plen + 1], hex, mdlen * 2);
trust = 1;
}
free(line);
}
munmap((void *)p, size);
}
}
if (!found) trust = append_line(fd, "%s:%s %s\n", url->host, url->port, hex);
close(fd);
return trust;
}
static SSL *ssl_connect(const URL *url, SSL_CTX *ctx, int ask) {
BIO *bio = NULL;
SSL *ssl = NULL;
X509 *cert = NULL;
int fd = -1, ok = 0, err;
if ((fd = tcp_connect(url)) == -1) goto out;
if ((ssl = SSL_new(ctx)) == NULL || (bio = BIO_new_socket(fd, BIO_CLOSE)) == NULL || SSL_set_tlsext_host_name(ssl, url->host) == 0) {
error(0, "cannot establish secure connection to `%s`:`%s`", url->host, url->port);
goto out;
}
SSL_set_bio(ssl, bio, bio);
SSL_set_connect_state(ssl);
if ((err = SSL_get_error(ssl, SSL_do_handshake(ssl))) != SSL_ERROR_NONE) {
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) error(0, "cannot establish secure connection to `%s`:`%s`: cancelled", url->host, url->port);
else error(0, "cannot establish secure connection to `%s`:`%s`: error %d", url->host, url->port, err);
goto out;
}
if ((cert = SSL_get_peer_certificate(ssl)) == NULL) {
error(0, "cannot establish secure connection to `%s`:`%s`: no peer certificate", url->host, url->port);
goto out;
}
if (!(ok = tofu(cert, url, ask))) error(0, "cannot establish secure connection to `%s`:`%s`: bad certificate", url->host, url->port);
out:
if (cert) X509_free(cert);
if (!ok && ssl) SSL_free(ssl);
else if (!ok && bio) BIO_free(bio);
else if (!ok && fd != -1) close(fd);
return ok ? ssl : NULL;
}
static void mkcert(const char *crtpath, const char *keypath) {
EVP_PKEY *key = NULL;
#if OPENSSL_VERSION_NUMBER < 0x30000000L
EC_KEY *eckey = NULL;
#endif
X509 *cert = NULL;
X509_NAME *name;
const char *curve, *digest, *cn;
const EVP_MD *md;
FILE *crtf = NULL, *keyf = NULL;
long days;
int ok = 0;
#if OPENSSL_VERSION_NUMBER < 0x30000000L
int assigned = 0, nid;
#endif
if ((days = get_var_integer("DAYS", 1825)) <= 0) days = 1825;
if ((curve = set_var(&variables, "CURVE", NULL)) == NULL || *curve == '\0') curve = SN_X9_62_prime256v1;
if ((digest = set_var(&variables, "DIGEST", NULL)) == NULL || *digest == '\0') digest = LN_sha256;
#if OPENSSL_VERSION_NUMBER < 0x30000000L
ok = ((((cn = set_var(&variables, "CN", NULL)) != NULL && *cn != '\0') || ((cn = getenv("USER")) != NULL && *cn != '\0')) && (md = EVP_get_digestbyname(digest)) != NULL && (cert = X509_new()) != NULL && X509_set_version(cert, 2) == 1 && X509_gmtime_adj(X509_get_notBefore(cert), 0) != NULL && X509_gmtime_adj(X509_get_notAfter(cert), 60 * 60 * 24 * days) != NULL && (name = X509_get_subject_name(cert)) != NULL && X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const unsigned char *)cn, -1, -1, 0) == 1 && (key = EVP_PKEY_new()) != NULL && (nid = OBJ_sn2nid(curve)) != NID_undef && (eckey = EC_KEY_new_by_curve_name(nid)) != NULL && EC_KEY_generate_key(eckey) == 1 && (assigned = EVP_PKEY_assign_EC_KEY(key, eckey)) == 1 && X509_set_pubkey(cert, key) == 1 && X509_sign(cert, key, md) != 0 && (crtf = fopen(crtpath, "w")) != NULL && (keyf = fopen(keypath, "w")) != NULL && PEM_write_X509(crtf, cert) != 0 && PEM_write_PrivateKey(keyf, key, NULL, NULL, 0, NULL, NULL) != 0);
#else
ok = ((((cn = set_var(&variables, "CN", NULL)) != NULL && *cn != '\0') || ((cn = getenv("USER")) != NULL && *cn != '\0')) && (md = EVP_get_digestbyname(digest)) != NULL && (cert = X509_new()) != NULL && X509_set_version(cert, X509_VERSION_3) == 1 && X509_gmtime_adj(X509_get_notBefore(cert), 0) != NULL && X509_gmtime_adj(X509_get_notAfter(cert), 60 * 60 * 24 * days) != NULL && (name = X509_get_subject_name(cert)) != NULL && X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const unsigned char *)cn, -1, -1, 0) == 1 && (key = EVP_EC_gen(curve)) != NULL && X509_set_pubkey(cert, key) == 1 && X509_sign(cert, key, md) != 0 && (crtf = fopen(crtpath, "w")) != NULL && (keyf = fopen(keypath, "w")) != NULL && PEM_write_X509(crtf, cert) != 0 && PEM_write_PrivateKey(keyf, key, NULL, NULL, 0, NULL, NULL) != 0);
#endif
if (keyf) {
fclose(keyf);
if (ok == 0) unlink(keypath);
}
if (crtf) {
fclose(crtf);
if (ok == 0) unlink(crtpath);
}
#if OPENSSL_VERSION_NUMBER < 0x30000000L
if (!assigned && eckey) EC_KEY_free(eckey);
#endif
if (key) EVP_PKEY_free(key);
if (cert) X509_free(cert);
}
static int ssl_error(const URL *url, void *c, int err) {
if ((err = SSL_get_error((SSL *)c, err)) == SSL_ERROR_ZERO_RETURN) return 0;
if (err == SSL_ERROR_SSL) error(0, "protocol error while downloading `%s`", url->url);
else if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) error(0, "failed to download `%s`: cancelled", url->url);
else error(0, "failed to download `%s`: error %d", url->url, err);
return 1;
}
static int ssl_read(void *c, void *buffer, int length) {
return SSL_read((SSL *)c, buffer, length);
}
static int ssl_peek(void *c, void *buffer, int length) {
return SSL_peek((SSL *)c, buffer, length);
}
static void ssl_close(void *c) {
SSL_free((SSL *)c);
}
static int save_body(const URL *url, void *c, FILE *fp) {
static char buffer[2048];
size_t total;
int received, prog = 0;
for (total = 0; total < SIZE_MAX - sizeof(buffer) && (received = url->proto->read(c, buffer, sizeof(buffer))) > 0 && fwrite(buffer, 1, received, fp) == (size_t)received; total += received) {
if ((total > 2048 && total - prog > total / 20)) { fputc('.', stderr); prog = total; }
}
if (prog > 0) fputc('\n', stderr);
if (ferror(fp)) { error(0, "failed to download `%s`: failed to write", url->url); return 0; }
return !url->proto->error(url, c, received);
}
static int ssl_download(URL *url, SSL **body, char **mime, int request(const URL *, SSL *, void *), void *p, int ask) {
static char crtpath[1024], keypath[1024], suffix[1024], buffer[1024], data[2 + 1 + 1024 + 2 + 1]; /* 99 meta\r\n\0 */
struct stat stbuf;
const char *home;
SSL_CTX *ctx = NULL;
char *crlf, *meta = &data[3], *line;
int redir, off, len, i, total, received, ret = 40, err = 0;
SSL *ssl = NULL;
if ((redir = perm_redirect(url, NULL, ask)) == 31) return 31;
else if (redir == 40) goto fail;
if ((home = getenv("XDG_DATA_HOME")) != NULL) {
if ((off = snprintf(crtpath, sizeof(crtpath), "%s/gplaces_%s_%s", home, url->host, url->port)) >= (int)sizeof(crtpath)) goto fail;;
} else if ((home = getenv("HOME")) == NULL || (off = snprintf(crtpath, sizeof(crtpath), "%s/.gplaces_%s_%s", home, url->host, url->port)) >= (int)sizeof(crtpath)) goto fail;
if ((ctx = SSL_CTX_new(TLS_client_method())) == NULL) goto fail;
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1);
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
/*
* If the user requests gemini://example.com/foo/bar/baz.gmi, try to load: