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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
|
#!/usr/bin/perl
# this is a gemini server
use strict;
use warnings;
use 5.010;
#use diagnostics;
our $VERSION = 'v0.18.0-cgi_WIP';
# Modules
use IO::Socket::SSL; # CPAN
use IO::Socket::SSL::Utils; # CPAN
use IO::Socket::IP -register;
use IO::Socket::UNIX;
use IO::Select;
use URL::XS qw(parse_url split_url_path parse_url_query); # CPAN
use Path::Naive qw(normalize_path); # CPAN
use Smart::Comments; # CPAN
use URI::Encode qw(uri_encode); # CPAN
use IO::Select;
use TOML qw(from_toml);
use Data::Dumper;
use Cwd;
use File::Type;
use English qw( -no_match_vars );
use Const::Fast;
use Carp;
use String::Substitution qw( gsub_modify );
use IPC::Run3;
#$IO::Socket::SSL::DEBUG = 15;
local $PROGRAM_NAME = 'jakes-gemini-server';
# Not worried about fork()-ed children
local $SIG{CHLD} = 'IGNORE';
const my $DEFAULT_GEMINI_PORT => 1965;
const my $KBYTE => 1024;
const my $SECS_IN_YEAR => 3_156_000;
const my $UMASK_FOR_CERTS_KEYS => '077'; # '-rwx------'
const our %GEM_RES_CODES => (
'input' => '10 Input',
'hidden_input' => '11 Sensitive Input',
'success' => '20 !s',
'redirect' => '30 !s',
'redirect_perm' => '31 !s',
'temp_failure' => '40 Temporary Failure',
'server_unavailable' => '41 Server Unavailable',
'cgi_error' => '42 CGI Error',
'proxy_error' => '43 Proxy Error',
'slow_down' => '44 Slow Down',
'failure' => '50 Permament Failure',
'not_found' => '51 Not Found',
'gone' => '52 Gone',
'proxy_req_refused' => '53 Proxy Request Refused',
'bad_request' => '59 Bad Request',
'cert_req' => '60 Certificate Required',
'cert_unauth' => '61 Certificate Unauthorized',
'cert_invalid' => '62 Certificate Invalid',
'custom' => '!s',
);
const our @VALID_DEFAULT_SETTINGS =>
qw/bind ports tls assume_index dir_listing root working_dir cert_key_dir
log_file log_to_stdout default_mime cert_key_dir_write_warning fork timeout
unix redirection redirect/;
const our @VALID_VHOST_SETTINGS =>
qw/auto_cert assume_index dir_listing root cert key default_mime bind ports
unix redirection redirect cert_req/;
my ($config, $err) = from_toml(_slurp('./config.toml'));
if ($err) {
die "TOML config error: $err.";
}
### $config
my $working_dir = working_dir($config);
my $cert_key_dir = cert_key_dir($config);
my $out = logging($config);
select $out; ## no critic (InputOutput::ProhibitOneArgSelect)
local $OUTPUT_AUTOFLUSH = 1;
my $timeout = timeout_secs($config);
my $listen_config = listen_config($config); #, %ssl_config, %ip_config);
### $listen_config
my @srv = ip_config($listen_config);
### @srv
my %ssl_config = ssl_config($config);
ssl_vhost_cert_key(\%ssl_config);
my $fork_toggled = fork_toggle($config);
# let the user know if an invalid option was used
check_config_keys($config);
# ## %ssl_config
my $ft = File::Type->new();
my $log;
my $cl_cert;
my $sel = IO::Select->new();
select_add_listen($sel, @srv);
say "$PROGRAM_NAME ($VERSION) started on ". localtime;
if (! $fork_toggled) {
say 'forking disabled.';
}
# Main server loop
while (my @ready = $sel->can_read) {
my $cl;
my $fh = shift @ready;
$cl = $fh->accept;
my ($fh_sockhost, $fh_port, $clhost, $clport) = get_fh_data($fh, $cl);
### $fh_sockhost
### $fh_port
### $clhost
### $clport
maybe_fork() and next;
### before start_SSL
IO::Socket::SSL->start_SSL($cl, %ssl_config)
or do {
# TODO: user log format
say "$clhost - $SSL_ERROR [". localtime. ']';
$cl->shutdown('SHUT_RDWR');
exit if ($fork_toggled);
next;
};
### nice, start_SSL worked
my $cl_sni = $cl->get_servername();
if (! check_fh_port_with_host_listen_port($cl_sni, $fh_sockhost, $fh_port)) {
# TODO: user log format
$log = "$clhost - ($cl_sni) client request on wrong port";
speak($cl, 'proxy_req_refused');
goto CLOSE;
}
my $url;
my $path;
my $data;
my $timedout = 0;
# We do this because 'naughty' people/bots can clog up the ports doing nothing.
local $SIG{ALRM} = sub { $timedout = 1 };
alarm $timeout;
# ALRM interrupts this
sysread $cl, $data, $KBYTE
or $data = '';
alarm 0;
if ($timedout) {
$log = "$clhost - ($cl_sni) sysread failed";
goto CLOSE;
}
if ($data) {
# removing \r\n
substr $data, -2, 2, '';
}
else {
# TODO: user log format
$log = "$clhost - ($cl_sni) no read";
goto CLOSE;
}
# TODO: user log format
$log = "$clhost - ($cl_sni) $data";
eval {
$url = parse_url($data); # if parse_url() fails, it makes the program die.
} or do {
### parse_url failed
speak($cl, 'bad_request');
goto CLOSE;
};
$path = $url->{path};
### $data
### $url
# ## $path
my $vhost = $url->{host};
my $doc_loc;
# only happens if someone is hacking/cracking
if ($vhost ne $cl_sni) {
speak($cl, 'bad_request');
goto CLOSE;
}
respond_to_client($cl, $vhost, $doc_loc, $path);
CLOSE:
if (ref $fh ne 'IO::Socket::UNIX') {
# stop_SSL doesnt work with IO::Socket::UNIX for some reason,
# but shutdown does. stop_SSL is supposed to return $cl to
# it's original class (ie IO::Socket::UNIX or IO::Socket::IP)
$cl->stop_SSL or warn "error: $ERRNO, ssl_error: $SSL_ERROR";
$cl->shutdown('SHUT_RDWR');
}
else {
$cl->close( (SSL_fast_shutdown=>0) );
}
### $cl
say "$log [". localtime(). ']';
exit if ($fork_toggled);
undef $cl_cert;
}
#$srv->close();
sub respond_to_client {
my ($cl, $vhost, $doc_loc, $path) = @_;
my ($cert_req, $cert_meta, $check_path) = cert_req($vhost, $path);
if ($cert_req) {
if ($cert_meta) {
speak($cl, 'custom', "60 $cert_meta");
}
else {
speak($cl, 'cert_req');
}
goto CLOSE;
}
my $redirection = redirection_parameter($vhost);
if ($redirection) {
my $redirect = check_for_config_redirection($vhost, $path, $redirection);
if ($redirect) {
speak($cl, 'redirect', $redirect);
return;
}
}
if (not $doc_loc = get_request_in_vhost_root($vhost, $path)) {
goto FAILURE;
}
### $doc_loc
### cgi checking
if (check_cgi($doc_loc, $vhost)) {
goto DOC_CGI;
}
# not a directory
if (! -d $doc_loc) {
goto DOC_ASSIGNED;
}
# make sure 'dir' is 'dir/'
if (substr($doc_loc,-1,1) ne '/') {
## no critic (ValuesAndExpressions::ProhibitMagicNumbers)
# if the '256' (maximum array return size) is not there, the program dies.
speak($cl, 'redirect', @{ split_url_path($path, 256) }[-1]. '/');
goto CLOSE;
}
my $cv = check_vhost_settings($vhost);
# if assume_index
if (($cv == 1 or $cv == 3) and file_exists_and_readable($doc_loc. '/index.gmi')) {
$doc_loc .= '/index.gmi';
#$doc = _slurp($doc_loc);
goto DOC_ASSIGNED;
}
# if dir_listing
elsif ($cv == 2 or $cv == 3) {
goto DIR_LISTING;
}
else {
goto FAILURE;
}
DOC_ASSIGNED:
#my $meta = $ft->checktype_contents($doc);
my $meta = detect_mime($doc_loc, $vhost);
speak($cl, 'success', $meta, $doc_loc);
return;
DOC_CGI:
do_cgi($doc_loc, $path, $cl);
return;
DIR_LISTING:
speak($cl, 'success', 'text/gemini', $doc_loc, $path);
return;
FAILURE:
speak($cl, 'failure');
return;
}
sub _slurp {
my $filename = shift;
open my $in, '<', $filename
or carp "Cannot open '$filename' - $ERRNO"
and return;
local $INPUT_RECORD_SEPARATOR = undef; # enable 'slurp mode'
my $contents = <$in>;
close $in
or carp "Cannot close filehandle ($filename): $ERRNO";
return $contents;
}
sub dir_listing {
my ($doc_loc, $path) = @_;
return if (! -d $doc_loc || ! -r $doc_loc);
my $doc = 'Dir listing for /';
if ($path) { $doc .= "$path" };
$doc .= "\n\n";
opendir my $dh, $doc_loc
or warn "Cannot open $doc_loc: $ERRNO"
and return; # No point in continuing.
while (my $i = readdir $dh) {
if (substr($i,0,1) eq '.') { # dont display hidden files
next;
}
# convert space into %20
# (there is probably an edge-case bug here)
$i =~ s/ /%20/g;
$doc .= "=> $i";
if (-d "$doc_loc/$i") {
$doc .= '/';
}
$doc .= "\n";
}
closedir $dh
or warn "Cannot close $doc_loc: $ERRNO";
return $doc;
}
sub gen_cert {
my ($hostname, $path) = @_;
my $cert_loc = "$path/$hostname". '_cert.pem';
my $key_loc = "$path/$hostname". '_key.pem';
my $not_before = time;
my $not_after = 20 * $SECS_IN_YEAR + time;
my %cert = (
'subject' => { 'commonName' => $hostname },
'not_before' => $not_before,
'not_after' => $not_after,
);
my ($cert, $key) = CERT_create(%cert);
my $old_umask = umask oct $UMASK_FOR_CERTS_KEYS;
PEM_cert2file($cert, $cert_loc);
PEM_key2file($key, $key_loc);
CERT_free($cert);
KEY_free($key);
umask $old_umask
or warn "umask: $ERRNO";
return;
}
# return appropriate path that can be sysread -> syswrite
# WARNING: this has not been tested properly for security!! may serve any file somehow!
# rude users can `ln -s /etc/passwd ./passwd` in their capsule directory.
sub get_request_in_vhost_root {
my ($vhost, $request) = @_;
my $r = '';
if ($request) {
# remove '..'
$request =~ s/[.]{2}//g;
# convert %20 into space
$request =~ s/%20/ /g;
$r = normalize_path($request);
if (substr($request, -1, 1) eq '/') {
# normalize_path() removes the trailing '/'
$r .= '/';
}
}
### $r
if (exists $config->{$vhost}{root}) {
my $p = accurate_path($config->{$vhost}{root}, $working_dir);
if (file_exists_and_readable("$p/$r")) {
return "$p/$r";
}
}
# try default's root
elsif (exists $config->{default}{root}) {
my $p = accurate_path($config->{default}{root}, $working_dir);
if (file_exists_and_readable("$p/$r")) {
return "$p/$r";
}
}
else {
serr("default and $vhost have improper root settings.");
return;
}
return;
}
sub file_exists_and_readable {
my ($path) = @_;
if (defined $path and ref \$path eq 'SCALAR') {
(-e $path and -r $path) ? return 1 : return 0;
}
return;
}
sub gem_code {
my ($code, @r) = @_;
exists $GEM_RES_CODES{$code}
or die "'$code' is an invalid Gemini Status.";
my $res = $GEM_RES_CODES{$code};
for (@r) {
$res =~ s/!s/$_/;
}
return $res;
}
sub speak {
my ($cl, $header, $meta, $doc_loc, $path) = @_;
### $meta
my $head = gem_code($header, $meta);
$log .= " $head";
syswrite $cl, "$head\r\n"
or warn "syswrite failed: $ERRNO";
if ($doc_loc) {
if (file_exists_and_readable($doc_loc) and (! -d $doc_loc)) {
my $r;
## no critic (InputOutput::RequireBriefOpen)
open my $fh, '<', $doc_loc
or warn "Cannot open '$doc_loc': $ERRNO"
and return;
# An SSL packet can only have about 16k bytes
# so, read less 16k, send it until eof
while (sysread $fh, $r, 15*$KBYTE) {
syswrite $cl, $r
or $log .= " $ERRNO"
and return;
undef $r;
}
close $fh
or warn "failed to close filehandle: $ERRNO";
}
elsif (file_exists_and_readable($doc_loc) and -d $doc_loc) {
my $doc;
$path ? ($doc = dir_listing($doc_loc, $path)) : ($doc = dir_listing($doc_loc));
# It is possible that a dir listing can produce more than 16k bytes
my $offset = 0;
while (my $w = syswrite $cl, $doc, 15*$KBYTE, $offset) {
$offset += $w;
}
}
}
return;
}
sub check_vhost_settings {
# assume_index first, then dir_listing
# returns:
# 0 = no setting
# 1 = assume_index
# 2 = dir_listing
# 3 = assume_index and dir_listing
my ($vhost) = @_;
my $assume_index = 0;
my $dir_listing = 0;
# Vhost first
if (exists $config->{$vhost}{assume_index}) {
if ($config->{$vhost}{assume_index} eq 'true') {
### vhost assume index is true
$assume_index = 1;
}
elsif ($config->{$vhost}{assume_index} eq 'false') {
### vhost assume index is false
$assume_index = 2;
}
}
if (exists $config->{$vhost}{dir_listing}) {
if ($config->{$vhost}{dir_listing} eq 'true') {
### vhost dir listing is true
$dir_listing = 1;
}
elsif ($config->{$vhost}{dir_listing} eq 'false') {
### vhost dir listing is false
$dir_listing = 2;
}
}
# no vhost option, check default setting.
if ($assume_index == 0 and $dir_listing == 0) {
if (exists $config->{default}{assume_index} and $config->{default}{assume_index} eq 'true') {
### default assume_index is true
$assume_index = 1;
}
if (exists $config->{default}{dir_listing} and $config->{default}{dir_listing} eq 'true') {
### default dir_listing is true
$dir_listing = 1;
}
}
if ($assume_index == 1 and $dir_listing == 1) {
### returning 3
return 3;
} elsif ($assume_index == 1) {
### returning 1
return 1
} elsif ($dir_listing == 1) {
### returning 2
return 2;
}
else {
### returning 0
return 0;
}
return;
}
sub abs_or_rel {
my ($p) = @_;
if (defined $p and ref \$p eq 'SCALAR') {
substr($p,0,1) eq '/'
? return 'abs' : return 'rel';
}
return;
}
# '"config value is invalid" at <line_numb> in <program>' is ugly.
sub serr {
my ($s) = @_;
return say {*STDERR} $s;
}
sub cert_key_dir {
my ($conf_ref) = @_;
my $dir;
if (exists $conf_ref->{default}{cert_key_dir}) {
$dir = accurate_path($conf_ref->{default}{cert_key_dir}, $working_dir);
}
else {
$dir = "$working_dir/certs";
}
# Create cert_key_dir if needed
if (-d $dir and -r $dir and -x $dir) {
if (! -w $dir) {
if (! (exists $conf_ref->{default}{cert_key_dir_write_warning}
and $conf_ref->{default}{cert_key_dir_write_warning} eq 'false'))
{
serr("cert_key_dir ($dir) not writable.");
}
}
} elsif (! -e $dir) {
mkdir $dir
or die "Could not create cert_key_dir ($dir) - $ERRNO";
}
else {
die "cert_key_dir ($dir) is not all of these: ".
'directory, readable, or executeable.';
}
return $dir;
}
sub working_dir {
my ($conf_ref) = @_;
my $dir;
if (exists $conf_ref->{default}{working_dir}) {
$dir = $conf_ref->{default}{working_dir};
if (! (-e $dir and -r $dir and -d $dir) ) {
die "$working_dir is either: not existing, readable, or a directory.";
}
}
else {
$dir = getcwd;
}
return $dir;
}
sub ssl_config {
my ($conf_ref) = @_;
my %ssl = (
SSL_version => '!SSLv2:!SSLv3:!TLSv1:!TLSv1_1',
SSL_server => 1,
Listen => 5,
# If peer sends us a cert, use the callback to accept it for future use.
SSL_verify_mode => SSL_VERIFY_PEER,
SSL_verify_callback => \&verify_cert_callback,
SSL_fast_shutdown => 1,
Timeout => 5, # !! Nothing to do with the config option !!
# used if /no/ SSL was established
SSL_error_trap => 1,
#SSL_server => 1,
);
for my $item (keys %{ $conf_ref->{default} } ) {
if ($item eq 'tls') {
# don't allow any on the assuption the config has specified which to allow
# (only 1.2 and 1.3 per the Gemini Spec)
$ssl{SSL_version} = '!SSLv2:!SSLv3:!TLSv1:!TLSv1_1:!TLSv1_2:!TLSv1_3';
for my $tls ( @{ $conf_ref->{default}{tls} } ) {
if ($tls eq 'v1.2') {
$ssl{SSL_version} =~ s/:!TLSv1_2//;
}
elsif ($tls eq 'v1.3') {
$ssl{SSL_version} =~ s/:!TLSv1_3//;
}
else {
serr("TLS option '$tls' not supported - ignoring.");
}
}
}
}
return %ssl;
}
sub ip_config {
my ($listening_ref) = @_;
my @a;
my %paths;
for my $socket (keys %{ $listening_ref }) {
# if IP socket
if ($socket ne 'unix') {
for my $port (keys %{ $listening_ref->{$socket} }) {
my %listener = (
LocalAddr => $socket,
LocalPort => $port + 0, # coax into number
Listen => 10,
Timeout => 5, # !! Nothing to do with config option !!
# used when a connection to the socket doesnt do anything
);
push @a, \%listener;
}
}
# else an UNIX socket
else {
for my $unix (keys %{ $listening_ref->{unix}{path} }) {
if (exists $paths{ $listening_ref->{unix}{path}{$unix} }) {
next;
}
else {
$paths{ $listening_ref->{unix}{path}{$unix} } = 1;
## no critic (RequireCheckedSyscalls) # doesn't matter if success or not
unlink $listening_ref->{unix}{path}{$unix};
my %listener = (
Type => SOCK_STREAM(),
Local => $listening_ref->{unix}{path}{$unix},
Listen => 1,
);
push @a, \%listener
}
}
### %paths
}
}
return @a;
}
sub logging {
my ($conf_ref) = @_;
if (exists $conf_ref->{default}{log_to_stdout} and $conf_ref->{default}{log_to_stdout} eq 'true') {
return \*STDOUT;
}
elsif (exists $conf_ref->{default}{log_file} and $conf_ref->{default}{log_file}) {
my $p = abs_or_rel($conf_ref->{default}{log_file});
if ($p eq 'abs') {
open my $fh, '>>', "$conf_ref->{default}{log_file}"
or die "Cannot open log file: $ERRNO";
return $fh;
}
elsif ($p eq 'rel') {
open my $fh, '>>', "$working_dir/$conf_ref->{default}{log_file}"
or die "Cannot open log file: $ERRNO";
return $fh;
}
else {
die 'log_file: is neither absolute or relative.'
}
}
else {
serr('default: No log option specified, logging to STDOUT.');
return \*STDOUT;
}
return;
}
sub fork_toggle {
my ($conf_ref) = @_;
if (exists $conf_ref->{default}{fork}) {
if ($conf_ref->{default}{fork} eq 'true') {
return 1;
}
elsif ($conf_ref->{default}{fork} eq 'false') {
return 0;
}
else {
serr("fork value ($conf_ref->{default}{fork}) is not true/false. Assuming true.");
return 1;
}
}
else {
return 1;
}
}
sub ssl_vhost_cert_key {
my ($ssl_ref) = @_;
for my $vhost (keys %{ $config }) {
next if ($vhost eq 'default');
my $error_free = 1;
my $cert_loc;
my $key_loc;
if (exists $config->{$vhost}{cert} and exists $config->{$vhost}{key}) {
$cert_loc = accurate_path($config->{$vhost}{cert}, $cert_key_dir);
if (! -e $cert_loc) {
serr("$vhost: '$cert_loc' does not exist.");
$error_free = 0;
}
$key_loc = accurate_path($config->{$vhost}{key}, $cert_key_dir);
if (! -e $key_loc) {
serr("$vhost: '$key_loc' does not exist.");
$error_free = 0;
}
}
else {
if (exists $config->{$vhost}{auto_cert} and $config->{$vhost}{auto_cert} eq 'true') {
# manage cert for user
$cert_loc = "$cert_key_dir/$vhost". '_cert.pem';
$key_loc = "$cert_key_dir/$vhost". '_key.pem';
if ((! -e $cert_loc) or (! -e $key_loc)) {
gen_cert($vhost, $cert_key_dir);
say "$vhost cert/key pair generated in '$cert_key_dir'.";
}
else {
# TODO: make sure cert is valid, otherwise re-generate them
}
}
else {
serr("$vhost: only has one part of a cert/key pair and/or auto_cert is not true.");
$error_free = 0;
}
}
if ($error_free) {
$ssl_ref->{SSL_cert_file}{$vhost} = $cert_loc;
$ssl_ref->{SSL_key_file}{$vhost} = $key_loc;
}
else {
serr("$vhost: will not listen for incoming requests.");
}
}
return;
}
sub check_config_keys {
my ($conf_ref) = @_;
for my $vhost (keys %{ $conf_ref }) {
## no critic (References::ProhibitDoubleSigils)
my $array_ref = \@VALID_VHOST_SETTINGS;
if ($vhost eq 'default') {
$array_ref = \@VALID_DEFAULT_SETTINGS;
}
for my $option (keys %{ $conf_ref->{$vhost} }) {
my $valid = 0;
for (@$array_ref) {
if ($option eq $_) {
$valid = 1;
last;
}
}
if (! $valid) {
serr("$vhost: '$option' is invalid.");
}
}
}
return;
}
sub accurate_path {
my ($p, $rel) = @_;
my $aor = abs_or_rel($p);
if ($aor eq 'abs') {
return $p;
}
elsif ($aor = 'rel') {
return "$rel/$p";
}
else {
carp "Value is neither absolute or relative: $p";
return;
}
}
sub detect_mime {
my ($doc_loc, $vhost) = @_;
my $meta = $ft->checktype_filename($doc_loc);
# 'text/gemini' is non-standard mime-type
if ($meta eq 'application/octet-stream') {
## no critic (ControlStructures::ProhibitCascadingIfElse)
if ((substr($doc_loc, -4, 4) eq '.gmi') or (substr($doc_loc, -1, 1) eq '/')) {
return 'text/gemini';
}
# Manually support webm until better magic detection is used
elsif (substr($doc_loc, -4, 4) eq 'webm') {
return webm_type($doc_loc);
}
elsif (exists $config->{$vhost}{default_mime}) {
return $config->{$vhost}{default_mime};
}
elsif (exists $config->{default}{default_mime}) {
return $config->{default}{default_mime};
}
### $meta
}
return $meta;
}
sub webm_type {
my ($doc_loc) = @_;
my $mime;
open my $fh, '<', $doc_loc
or warn "Cannot open webm ($doc_loc) for mime detection: $ERRNO"
and return;
read $fh, $mime, 1*$KBYTE
or warn "Cannot read webm ($doc_loc) for mime detection: $ERRNO"
and return;
close $fh
or warn "Cannot close file handle: $ERRNO";
if ($mime =~ m/V_VP9/) {
return 'video/VP9';
} elsif ($mime =~ m/V_VP8/) {
return 'video/VP8';
} else {
# fall back
return 'application/octet-stream';
}
}
sub maybe_fork {
if ($fork_toggled) {
my $pid = fork;
if (not defined $pid) {
warn "Cannot make a child: $ERRNO";
return;
}
if ($pid) {
return 1;
}
else {
local $PROGRAM_NAME = "chld: $PROGRAM_NAME";
return;
}
}
}
sub timeout_secs {
my ($cert_ref) = @_;
if (exists $cert_ref->{default}{timeout}) {
if ($cert_ref->{default}{timeout} =~ /^(\d*)$/) {
return $1;
}
else {
serr("Timeout value ($cert_ref->{default}{timeout}) is invalid. Using 5 seconds.");
return 5;
}
}
else {
return 5;
}
}
sub listen_config {
my ($conf_ref, $ssl_ref, $ip_ref) = @_;
my %listen;
my @default_bind;
my @default_ports;
if (exists $conf_ref->{default}{bind}) {
if ($conf_ref->{default}{bind} ne 'no') {
push @default_bind, give_array($conf_ref->{default}{bind});
}
}
else {
# Listen to all
push @default_bind, '::';
}
if (exists $conf_ref->{default}{ports}) {
push @default_ports, give_array($conf_ref->{default}{ports});
}
else {
push @default_ports, $DEFAULT_GEMINI_PORT;
}
if (exists $conf_ref->{default}{unix} and $conf_ref->{default}{unix} ne 'no') {
$listen{unix}{path}{default} = $conf_ref->{default}{unix};
}
for my $vhost (keys %{ $conf_ref }) {
next if ($vhost eq 'default');
my $binds;
my $ports;
if (exists $conf_ref->{$vhost}{ports}) {
@{ $ports } = give_array($conf_ref->{$vhost}{ports});
}
else {
$ports = \@default_ports;
}
if (exists $conf_ref->{$vhost}{bind}) {
if ($conf_ref->{$vhost}{bind} ne 'no') {
@{ $binds } = give_array($conf_ref->{$vhost}{bind});
}
}
else {
$binds = \@default_bind;
}
### $ports
### $binds
for my $port (give_array($ports)) {
for my $bind (give_array($binds)) {
push @{ $listen{$bind}{$port} }, $vhost;
}
}
# check vhost unix socket otherwise check for default unix socket
if (exists $conf_ref->{$vhost}{unix} and $conf_ref->{$vhost}{unix} ne 'no') {
$listen{unix}{path}{$vhost} = $conf_ref->{$vhost}{unix};
push @{ $listen{unix}{listen} }, $vhost;
}
elsif (exists $listen{unix}{path}{default}) {
push @{ $listen{unix}{listen} }, $vhost;
}
}
# ## %listen
return \%listen;
}
sub give_array {
my ($ref) = @_;
## no critic (Cascading, DoubleSigil)
if (ref $ref eq 'ARRAY') {
return @$ref;
}
elsif (ref $ref eq 'SCALAR') {
return $ref;
}
elsif (ref \$ref eq 'ARRAY') {
return @$ref;
}
elsif (ref \$ref eq 'SCALAR') {
return $ref;
}
else {
confess 'not array or scalar nor a reference to such.';
}
}
sub check_fh_port_with_host_listen_port {
my ($sni, $fh_sockhost, $fh_port) = @_;
if ($fh_sockhost ne 'UNIX') {
for my $dns_host (@{ $listen_config->{$fh_sockhost}{$fh_port} }) {
if ($dns_host eq $sni) {
return 1;
}
}
}
else {
for my $dns_host (@{ $listen_config->{unix}{listen} }) {
### $dns_host
### $sni
# explictly given a unix path
if (($dns_host eq $sni) and exists $listen_config->{unix}{path}{$sni}) {
return 1;
}
# default's unix path
elsif (($dns_host eq $sni) and exists $listen_config->{unix}{path}{default}) {
return 1;
}
}
}
return 0;
}
sub get_fh_data {
my ($fh, $cl) = @_;
my $fh_sockhost;
my $fh_port;
my $clhost;
my $clport;
if (ref $fh eq 'IO::Socket::IP') {
$fh_sockhost = $fh->sockhost;
$fh_port = $fh->sockport;
$clhost = $cl->peerhost();
$clport = $cl->peerport();
} elsif (ref $fh eq 'IO::Socket::UNIX') {
$fh_sockhost = 'UNIX';
$fh_port = 'UNIX';
$clhost = $cl->hostpath();
$clport = 'UNIX';
}
return $fh_sockhost, $fh_port, $clhost, $clport;
}
sub select_add_listen {
my ($sell, @srvv) = @_;
for my $lsn (@srvv) {
## no critic (DoubleSigil)
if (exists $lsn->{LocalAddr}) {
$sell->add(IO::Socket::IP->new(%$lsn))
or die "$ERRNO ($lsn->{LocalAddr}:$lsn->{LocalPort})";
}
elsif (exists $lsn->{Local}) {
$sell->add(IO::Socket::UNIX->new(%$lsn))
or die "$ERRNO ($lsn->{Local})";
}
}
return;
}
sub check_for_config_redirection {
my ($vhost, $path, $redirection) = @_;
if (! $path) {
$path = '/';
}
else {
$path = "/$path";
}
if (exists $config->{$vhost}{redirect}) {
# 'simple'
if ($redirection >= 1 and exists $config->{$vhost}{redirect}{$path}) {
return $config->{$vhost}{redirect}{$path};
}
if ($redirection >= 2) {
# regular expression compiling
for my $redirect (keys %{ $config->{$vhost}{redirect} }) {
# ## $redirect
my $redirect_replace = $config->{$vhost}{redirect}{$redirect};
# ## $redirect_replace
my $regex_match;
#my $regex_replace;
eval {
$regex_match = qr/$redirect$/;
} or serr($EVAL_ERROR) and return;
if ($path =~ m/$regex_match/) {
gsub_modify($path, $regex_match, $redirect_replace);
return $path;
}
}
}
}
return;
}
sub redirection_parameter {
my ($vhost) = @_;
my $r;
if (exists $config->{$vhost}{redirection}) {
$r = $config->{$vhost}{redirection};
}
elsif (exists $config->{default}{redirection}) {
$r = $config->{default}{redirection};
$vhost = 'default';
}
if ($r) {
if ($r eq 'no') {
return 0;
}
elsif ($r eq 'simple') {
return 1;
}
elsif ($r eq 'regex') {
return 2;
}
else {
serr("'$vhost': Given redirection parameter is invalid: $r");
}
}
return;
}
## no critic (unpack)
sub verify_cert_callback {
### @_;
## perl arrays start at 0, not 1
#1. a true/false value that indicates what OpenSSL thinks of the certificate,
#2. a C-style memory address of the certificate store,
#3. a string containing the certificate's issuer attributes and owner attributes, and
#4. a string containing any errors encountered (0 if no errors).
#5. a C-style memory address of the peer's own certificate (convertible to PEM form with Net::SSLeay::PEM_get_string_X509()).
#6. The depth of the certificate in the chain. Depth 0 is the leaf certificate.
## $pem
$cl_cert = CERT_asHash(PEM_string2cert(Net::SSLeay::PEM_get_string_X509($_[4])));
### $cl_cert
return 1;
}
## use critic
## no critic (deep, return, useless, complex)
sub cert_req {
my ($vhost, $path) = @_;
$path ? ($path = "/$path") : ($path = '/');
if (exists $config->{$vhost}{cert_req}) {
my $cert_req = $config->{$vhost}{cert_req};
### $cert_req
for my $key (keys %{ $cert_req }) {
### $key
### $path
my $regex = qr{$key};
if ($path =~ m/$regex/) {
### yep, that path matched that key
my ($req, $meta);
if (ref $cert_req->{$key} eq 'ARRAY') {
$req = $cert_req->{$key}[0];
if ($req eq 'any' and defined $cl_cert) {
return 0;
}
elsif ($req eq 'pubkey' and defined $cl_cert) {
my $cl_cert_f = $cl_cert->{fingerprint_sha256};
$cl_cert_f =~ s/://g;
$cl_cert_f = lc $cl_cert_f;
for my $pubkey (@{ $cert_req->{$key} }) {
my $pk = $pubkey;
$pk =~ s/://g;
$pk = lc $pk;
### $pk
### $cl_cert_f
if ($pk eq $cl_cert_f) {
return 0;
}
}
}
elsif ($req eq 'file' and defined $cl_cert) {
my $cl_cert_f = $cl_cert->{fingerprint_sha256};
$cl_cert_f =~ s/://g;
$cl_cert_f = lc $cl_cert_f;
for my $file (@{ $cert_req->{$key} }) {
### $file
## no critic (RequireBriefOpen)
if (-e $file and -r $file) {
open my $fh, '<', $file
or serr("'$vhost': cert_req: '$file': $ERRNO");
while (<$fh>) {
my $pk = $_;
$pk =~ s/://g;
$pk = lc $pk;
chomp $pk;
### $pk
### $cl_cert_f
if ($pk eq $cl_cert_f) {
close $fh
or warn "$vhost: $file: $ERRNO";
return 0;
}
}
close $fh
or warn "$vhost: $file: $ERRNO";
}
}
}
### $req
if ($cert_req->{$key}[1]) {
return 1, $cert_req->{$key}[1];
}
else {
return 1;
}
}
# must be string, hopefully 'any'
elsif ($cert_req->{$key} eq 'any') {
if (defined $cl_cert) {
return 0;
}
else {
return 1;
}
}
else {
serr("'$vhost': certs: when not an array, it must be 'any'.");
return 1;
}
### fall back to require certificate, the regex *DID* match.
return 1, 'System Error';
}
}
}
return;
}
sub check_cgi {
my ($doc_loc, $vhost) = @_;
# '.cgi' should be a user defined array
if (not -x $doc_loc or substr($doc_loc, -3, 4) eq '.cgi') {
### not -x or ending in '.cgi'.
return 0;
}
if (exists $config->{$vhost}{cgi_enabled}) {
if ($config->{$vhost}{cgi_enabled} eq 'true') {
return 1;
}
}
elsif (exists $config->{default}{cgi_enabled}) {
if ($config->{default}{cgi_enabled} eq 'true') {
return 1;
}
}
### not cgi_enabled
return;
}
sub do_cgi {
my ($doc_loc, $path, $cl) = @_;
$cl_cert ? (local $ENV{'AUTH_TYPE'} = 'cl_cert') : (local $ENV{'AUTH_CERT'} = '');
local $ENV{'CONTENT_LENGTH'} = undef;
local $ENV{'CONTENT_TYPE'} = undef;
local $ENV{'GATEWAY_INTERFACE'} = 'CGI/1.1';
local $ENV{'PATH_INFO'} = $doc_loc;
local $ENV{'PATH_TRANSLATED'} = $path;
local $ENV{'QUERY_STRING'} = ''; # to do - how to get 10 <meta> ?
local $ENV{'REMOTE_ADDR'} = $cl->peerhost(); ## will NOT work with UNIX
local $ENV{'REMOTE_HOST'} = '';
local $ENV{'REMOTE_IDENT'} = undef;
local $ENV{'REMOTE_USER'} = $cl_cert;
local $ENV{'REQUEST_METHOD'} = '';
local $ENV{'SCRIPT_NAME'} = $doc_loc;
local $ENV{'SERVER_NAME'} = $cl->get_servername();
local $ENV{'SERVER_PORT'} = $DEFAULT_GEMINI_PORT; # TODO: FIX
local $ENV{'SERVER_PROTOCOL'} = 'gemini';
local $ENV{'SERVER_SOFTWARE'} = $PROGRAM_NAME. '('. $VERSION. ')';
#my ($run_in, $run_out);
my @cmd;
push @cmd, $doc_loc;
### @cmd
### $doc_loc
run3(\@cmd); #, \$run_in, \$run_out);
# ## $run_in
## # $run_out
}
|