aboutsummaryrefslogtreecommitdiff
path: root/gmi.pl
blob: 3eb79beff588693eb96e39b36e40bca7dc4af5a8 (plain) (blame)
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
#!/usr/bin/perl

# this is a gemini client

use strict;
use warnings;
#use diagnostics;
#use utf8;
#use bytes;
use feature qw(refaliasing);
no warnings qw(experimental::refaliasing);

our $VERSION = 'v0.0.27';

# TODO: 
# back() only works once; should fix this

# Modules
use IO::Socket::SSL; # CPAN
use URL::XS qw(parse_url split_url_path parse_url_query); # CPAN
use IO::Pager; # CPAN
require Text::Wrapper; # CPAN
use Term::ReadKey; # CPAN
use Term::ANSIColor; # Core
use Path::Naive qw(normalize_path); # CPAN
use Text::ParseWords; # Core
use Term::ReadLine; # CPAN
use Smart::Comments; # CPAN
use URI::Encode qw(uri_encode); # CPAN
use IO::Socket::SSL::Utils; # CPAN
use File::Slurper qw(read_dir); # CPAN

# sudo cpanm IO::Socket::SSL URL::XS IO::Pager Text::Wraper Term::ReadKey Path::Naive  Text::ParseWords Term::ReadLine Smart::Comments URI::Encode IO::Socket::SSL::Utils File::Slurper

my $wrapper = Text::Wrapper->new(columns=>70, body_start=>'');
#$ENV{PAGER} = 'most';
$ENV{PAGER} = 'less -R';
my $use_pager = 1;
my $pager_text_wrap_auto = 1;
my $doc_out = 1; # display doc for human consumption?
my @doc;
my @links;
my $current_url = "";
my @history;
my $prompt = "";
my $pretty_links = 1;
my $pretty_headers = 1;
my $pre_block = 0;
my @status_code;
my $status_code1;
my $status_code2;
my $auto_redirect = 2;
my $auto_redirect_count = 0;
my $sleep;
my $timeout = 3;
my $use_cert = 0;
my $cert;
my $key;

my $term=new Term::ReadLine "hmm, what goes here?";
my $OUT = $term->OUT || \*STDOUT;

my %commands = (
	'url' => [sub { url($_[0]) }, 'Go to the specified URL.'],
	'u' => [sub { url($_[0]) }, 'Alias of `url\''],
	
	'urlrelative' => [sub { urlrelative($_[0]) }, "Navigate the current URL relatively.\n\n"
		."Note: if the current path is '/blog/my-post1.gmi' and 'my-post2.gmi'\n" .
		"was supplied then the resulting path will be: '/blog/my-post2.gmi'\n" .
		"which is probably what you want. You can also use './my-post2.gmi'.\n" .
		"'.', of course, means 'same directory', in this case '/blog/'.\n\n" .
		"To remove the forward slash ('/') at the end of the current url,\n" . 
		"type the back-slash ('\\') by itself.\n\n" .
		"urlrelative without an argument will remove the ending '/' or go\n" .
		"up a directory without appending a forward slash.\n" .
		"IE: '/blog/drafts/secret/post.gmi -> '/blog/drafts/secret' -> '/blog/drafts'"],
	'ur' => [sub { urlrelative($_[0]) }, 'Alias of `urlrelative\''],

	'cwu' => [sub { print $OUT "$current_url\n"; }, 'Returns the current working URL.'],
	'c' => [sub { print $OUT "$current_url\n"; }, 'Alias of `cwu\'.'],

	'links' => [sub { links() }, 'Returns the links on the current page.'],
	'l' => [sub { links() }, 'Alias of `links\'.'],

	'nav' => [sub { nav(0, $_[0]) }, 'Navigate to a link that is on the current page (use links)'],
	'n' => [sub { nav(0, $_[0]) }, 'Alias of `nav\'.'],

	'navh' => [sub { nav(1, $_[0]) }, 'Navigate to a URL specified from history (use hist)'],
	'nh' => [sub { nav(1, $_[0]) }, 'Alias of `navh\'.'],

	'root' => [sub { root() }, 'Go to the root of the current URL.\n' .
		'Exp: gemini://capsule.com/blog/2020112.gmi -> gemini://capsule.com/' ],

	'hist' => [sub { hist() }, 'Returns history.' ],
	'h' => [sub { hist() }, 'Alias of `hist\'.' ],

	'back' => [sub { back(0) }, 'Go back in history.' ],
	'b' => [sub { back(0) }, 'Alias of `back\'.' ],

	'backnodisplay' => [sub { back(1) }, 'Go back in history but do not display the page' .
		'(still accesses the resource).' ],
	'bd' => [sub { back(1) }, 'Alias of `backnodisplay\'.'],

	'display' => [sub { display() }, 'Display the current page.' ],
	'd' => [sub { display() }, 'Alias of `display\'.' ],

	'usepager' => [sub { toggle($use_pager) }, 'This toggles pager use. 1 = use pager, 0 = stdout.' ],
	'pretty_links' => [sub { toggle($pretty_links) }, "0 = do nothing, 1 = pretty."],
	'pretty_headers' => [sub { toggle($pretty_headers) }, "0 = do nothing, 1 = pretty."],
	'textwrap' => [sub { textwrap($_[0]) }, "Set textwrap length.\nGiving 'auto' will " .
		"automatically determine the appropriate length."],
	'pager' => [sub { pager($_[0]) }, "Set which pager to use. (currently $ENV{PAGER})"],
	'save' => [sub { ; }, 'Save the config settings. (Not yet implimented)'],
	'help' => [sub { help($_[0]); }, 'Use help before a command to get extra info. (cmds to see commands)'],
	'ver' => [sub {print $OUT "$VERSION\n"}, "Returns the version ($VERSION)"],
	'exit' => [sub {exit 0;}, "This exits the program with a status code of 0."],

	'autoredirection' => [sub { value_number($auto_redirect,$_[0],'autoredirect') },
		"The amount of times this program is allowed to auto redirect. 0 = none."],
	'timeout' => [sub { value_number($timeout,$_[0],'timeout') },
		"The client will time out when the server takes too long." ],

	'clearquery' => [sub { clear_query() }, "Removes query from current URL"],
	'cq' => [sub { clear_query() }, "Alias of `clearquery'"],

	'reload' => [sub {url($current_url)}, "Reload the current URL."],
	'r' => [sub {url($current_url)}, "Alias of `reload'."],

	'cert-create' => [sub { cert_create() }, "Create a cert. Interactive."],
	'cert-use' => [sub { cert_use() }, "Use a cert. Interactive.\n" . 
		"If a cert has already been loaded, it will unload it."],
	'cert-del' => [sub {cert_del() }, "Delete a cert. Interactive." ],
);

my @completions = keys %commands;

$term->Attribs->{'do_expand'}=1;
$term->Attribs->{'completion_entry_function'} = $term->Attribs->{'list_completion_function'};
$term->Attribs->{'completion_word'} = \@completions;
$term->ornaments(0);

$prompt = "$current_url > ";

print $OUT "Press <tab><tab> to see available commands.\n";
while ( defined ($_ = $term->readline($prompt)) ) {
	if ($_) {
		my ($command, $detail) = split(/\s/, $_);
		do_command(\$command, \$detail);
	}
	$prompt = "$current_url > ";
}

sub do_command {
	# referenced command, referenced arg
	my ($rCmd, $rArg) = @_; 

	# ## @_
	# checking if %commands even has the command
	if (exists $commands{$$rCmd}) {

		# assigning a reference to a subroutine to the value
		my $rsub = $commands{$$rCmd}[0];

		#running the subroutine
		&$rsub($$rArg);
	}
	# options doesn't have the command
	else {
		print $OUT "Command is invalid.\n";
	}	
}

sub help {
	my ($cmd) = @_;
	### @_
	if ($cmd and exists $commands{$cmd}) {
		print $OUT "$commands{$cmd}[1]\n";
	} elsif ($cmd) {
		print $OUT "`$cmd' isn't an avaliable command.\n";
	}
	else {
		print $OUT "$commands{help}[1]\n"
	}
}

sub url {
	my ($url) = @_;
	### $url
	if (!$url) { print("Example: [gemini://]capsule.com/\n"); return 1;}
	if (! has_scheme($url) ) {
		$url = "gemini://$url";
	}
	 
	eval {
		$url = parse_url($url);
	};
	if ($@) {
		print $OUT "$@\n";
		return 1;
	}

	### $url
	if (! $url->{port} or $url->{port} eq 0) {
		$url->{port} = '1965';
	}
	
	my $cl;
	if ($use_cert and $cert and $key) {
		$cl = IO::Socket::SSL->new(
			PeerHost => "$url->{host}",
			PeerPort => "$url->{port}",
	
			SSL_verify_mode => SSL_VERIFY_NONE,
			SSL_verifycn_name => "$url->{host}",
			SSL_version => '!SSLv2:!SSLv3:!TLSv1:!TLSv1_1',
			SSL_fast_shutdown => 1,
	
			SSL_cert_file => "$cert",
			SSL_key_file => "$key",
	
			Timeout => 2,
		);
	}
	else {
		$cl = IO::Socket::SSL->new(
			PeerHost => "$url->{host}",
			PeerPort => "$url->{port}",
	
			SSL_verify_mode => SSL_VERIFY_NONE,
			SSL_verifycn_name => "$url->{host}",
			SSL_version => '!SSLv2:!SSLv3:!TLSv1:!TLSv1_1',
			SSL_fast_shutdown => 1,
	
			Timeout => 2,
		);
	}

	if ($cl) {
		$current_url = return_url($url);
		### $current_url
		### $url

		undef(@doc);
	
		eval {
			local $SIG{ALRM} = sub {close ($cl); unshift(@doc,""); die "TIMEOUT";};
			alarm $timeout;

			# gemini spec: <URL><CR><LF>
			# <URL> is an absolute path
			print $cl "$current_url\r\n";

			@doc = <$cl>;

			close($cl); # if this isnt here, the kernel will have to clean up unused ports

			alarm 0;
		};

		if ($@) {
			print $OUT "Timed out after $timeout seconds - server is taking too long.\n";
			update_history( ["$current_url", "timed out"] );
			### @doc
		} else {
			follow_status_code();
		}
	}
	
	else {
		print $OUT "error=$!, ssl_error=$SSL_ERROR\n";
	}
}

sub follow_status_code {
	return 1 if (!@doc);
	@status_code = split(' ', $doc[0]);
	$status_code1 = substr($doc[0],0,1);
	$status_code2 = substr($doc[0],1,1);
	update_history( ["$current_url", "$status_code1$status_code2"] );
	my $bad_code = "The server sent an invalid status code, not defined by gemini specifications.\n@doc";

	if ($status_code1 == 2) { # 2 will probably be the most common server reply
		if ($status_code2 == 0) {
			shift(@doc); # user probably doesn't want to see the 20 */* every time
			             # at some point deal with image/* and other media
			get_links();
			pretty_links() if ($pretty_links);
			pretty_headers() if ($pretty_headers);

			if ($doc_out) {
				display();
			}
		}
		else {
			print $OUT $bad_code;
		}

	} elsif ($status_code1 == 1) {
		if ($status_code2 == 0) {
			print $OUT "Server wants you to type something:\n@doc";
		} elsif ($status_code2 == 1) {
			print $OUT "Server wants you to type something secretly (do note: not secure):\n@doc";
			ReadMode 2;
		} else {
			print $bad_code;
			print $OUT "\nPresumably, the server wants you to type something:\n";
		}
		chomp(my $input = <STDIN>);
		$input = uri_encode($input);
		ReadMode 1;
		url("$current_url?$input");
		clear_query();

	} elsif ($status_code1 == 3) { 
		print $bad_code if ($status_code2 !~ m/^0|1$/); # not worrying about permanent/temporary yet
		print $OUT "Redirecting anyway.\n" if ($status_code2 !~ m/^0|1$/);
		if ($auto_redirect) {
			$auto_redirect_count++;
			if ($auto_redirect_count < $auto_redirect) {
				print $OUT "Redirection...\n";
				### @status_code
				access_resource($status_code[1]); # redirection can be './hello.gmi'
			}
			else {
				print $OUT "Reached limit for auto redirection.\n@doc";
			}
		}
		else {
			print $OUT "The server wants to redirect us, however, autoredirect has turned off.\n@doc";
		}
		$auto_redirect_count = 0;

	} elsif ($status_code1 == 4) {
		if ($status_code2 == 0) {
			print $OUT "Temporary failure.\n@doc";
		} elsif  ($status_code2 == 1) {
			print $OUT "Server is unavailable (yet somehow sent a reply to us).\n@doc";
		} elsif ($status_code2 == 2) {
			print $OUT "Server's CGI script is broken.\n@doc";
		} elsif ($status_code2 == 3) {
			print $OUT "Server was unable to proxy content.\n@doc";
		} elsif ($status_code2 == 4) {
			if (!$sleep) {
				$sleep = 5;
				print $OUT "Server wants us to slow down.\n" .
				"Reconnecting after $sleep seconds\n" .
				"Press 'ctrl-C' to cancel sleep\n" .
				"@doc\n";
				eval {
					local $SIG{INT} = sub { die "Cancelling Sleep!\n" };
					sleep ($sleep); # give the server an extra second
					url($current_url);
				}
			}
			else {
				print $OUT "The server is asking us to slow down and try again.\n" .
				"We have already done this once: not doing it again.\n";
			}
			undef($sleep);
		}
		else {
			print $bad_code;
		}

	} elsif ($status_code1 == 5) {
		if ($status_code2 == 0) {
			print $OUT "Permanent failure. Requests to this URI will reliably fail.\n@doc";
		} elsif ($status_code2 == 1) {
			print $OUT "Not found. Not available but *may* be in the future\n@doc";
		} elsif ($status_code2 == 2) {
			print $OUT "Gone. This resource will not be available again.\n@doc";
		} elsif ($status_code2 == 3) {
			print $OUT "Proxy Request Refused. Resource not served by this server and this\n" .
			"server does not accept proxy requests.\n@doc";
		} elsif ($status_code2 == 9) {
			print $OUT "Bad Request. The server is unable to parse our request.\n@doc";
		}
		else {
			print $bad_code;
		}

	} elsif ($status_code1 == 6) {
		if ($status_code2 == 0) {
			print $OUT "The server is asking you for a certificate. (cert-use to load a cert)\n@doc";
		} elsif ($status_code2 == 1) {
			print $OUT "The certificate you supplied is not authorized to access this resource.\n@doc";
		} elsif ($status_code2 == 2) {
			print $OUT "The certificate you supplied is malformed. There is something wrong with it.\n@doc";
		}
		else {
			print $OUT $bad_code;
		}
	}
	else {
		print $OUT $bad_code;
	}
	### @status_code;
}

sub urlrelative {
	my ($urlr) = @_;
	if (! $urlr) { $urlr = ""}
	if (! $current_url) {print $OUT "Relative movement impossible: no current URL.\n"; return 1;}
	my $end_with_slash = 1 if ($urlr =~ m|/$|);
	my $dot_only = 1 if ($urlr =~ m|^\.$|);
	my $dot_2_only = 1 if ($urlr =~ m|^\.\.$|); # since we are going up into a dir
	my $c_url_directory = 1 if ($current_url =~ m|/$|);
	my $remove_slash = 1 if ($urlr =~ m|^\\$|);  # back slash \ not a forward slash /

	### is urlr a slash only ?
	if ($urlr =~ m|^/$|) { # if slash only
		$current_url .= "/";
		url("$current_url");
		return 0;
	}

	### remove slash ?
	if ($remove_slash) {
		substr($current_url,-1,1,'');
		### $current_url
		url($current_url);
		return 0;
	}

	### is the current url a directory?
	if ($c_url_directory) {
		$current_url .= "$urlr";
		my $c_p_url = parse_url($current_url);
		### $c_p_url
		# if $urlr has '..' then normalize_path will not go beyond the last element
		# which is why prefixing a '/' and then taking it away (parse_url doesnt have
		# the forward / ) will result in expected behavior as host always end with '/'
		$c_p_url->{path} = normalize_path("/" . $c_p_url->{path});
		if ($end_with_slash or $dot_only or $dot_2_only) {
			$c_p_url->{path} .= "/"; # normalize path will remove it
		}
		substr($c_p_url->{path},0,1,'');
		if ($c_p_url->{path} eq '/') {
			delete $c_p_url->{path}; # dont want to ask for 'gemini://host.com//'
		}
		url(return_url($c_p_url));
		return 0;
	}

	### current url is not a directory, so should be fine to remove last item on path
	# ^ some servers serve index page on 'dir' rather than 'dir/'  :v annoying
	# authors using servers like that will notice that the links on index page need to be
	# carefully managed, because ALL clients (that handle links correctly) *will* mess up. 
	if (! $c_url_directory) {
		my $c_p_url = parse_url($current_url);
		### $c_p_url
		my $c_paths_url = split_url_path($c_p_url->{path}, 256);
		### $c_paths_url
		pop(@$c_paths_url);
		### $c_paths_url
		delete ($c_p_url->{path});
		for (@$c_paths_url) {
			$c_p_url->{path} .= "$_/";
		}
		### $c_p_url
		$c_p_url->{path} .= "$urlr";
		$c_p_url->{path} = normalize_path("/" . "$c_p_url->{path}");
		if ($end_with_slash or $dot_only or $dot_2_only) {
			$c_p_url->{path} .= "/"; # normalize path will remove it
		}
		substr($c_p_url->{path},0,1,'');
		if ($c_p_url->{path} eq '/') {
			delete $c_p_url->{path}; # dont want to ask for 'gemini://host.com//'
		}
		### $c_p_url
		url(return_url($c_p_url));
		return 0;
	}
}

sub return_url {
	my ($url) = @_;
	my $url_string;
	# ## @_
	if (ref($url) ne 'HASH') { # assuming string
		if ($url !~ m|.*://|) {
			$url =~ s|(.*)|gemini://$1|;
		}
		$url = parse_url($url);
	}
	my $scheme = $url->{scheme};
	my $username = $url->{username};
	my $password = $url->{password};
	my $host = $url->{host};
	my $port = $url->{port};
	my $path = $url->{path};
	my $query = $url->{query};
	my $fragment = $url->{fragment};
	
	# 'https://peter:bro@localhost:8989/some/path/to/resource?q1=yes&q2=no&q3=maybe#frag=1';
	# a valid url ^^
	if (! $scheme) {
		$url_string .= "gemini://";
	} 
	else {
		$url_string .= "$scheme://";
	}
	if ($username and $password) {
		$url_string .= "$username:$password@";
	} elsif ($username) {
		$url_string .= "$username@";
	}
	$url_string .= "$host" if ($host);
	if ($port and $port ne 1965) {
		$url_string .= ":$port";
	}
	$url_string .= "/";
	$url_string .= "$path" if ($path);
	$url_string .= "?$query" if ($query);
	$url_string .= "#$fragment" if ($fragment);

	return $url_string;
}

sub get_links {
	undef(@links);
	#for my $line (split('\n', $doc)) {
	for (@doc) {
		#if ($line =~ m/^=>[\s]*([\w\d\-\\\/\.\:\~\?\=\#]+)[\s]*(.+)?$/gm) {
		_pre_block($_);
		if ($_ =~ m/^=>[\s]*([\w\d\-\\\/\.\:\~\?\=\#]+)[\s]*(.+)?$/gm and not $pre_block) {
			if ($2) {
				push(@links, ["$1", "$2"]);
			}
			else {
				push(@links, ["$1", "$1"]);
			}
		}
	}
}

sub hist {
	my $hist;
	my $counter = 1;
	for my $item (@history) {
		$hist .= "[$counter] ". colored("$$item[0]", 'underline') ." $$item[1]\n";
		$counter++;
	}
	if ($hist) {
		print $OUT $hist;
	}
	else {
		print $OUT "\n";
	}
}

sub update_history {
	my ($history) = @_;
	push(@history, $history);
}

sub links {
	my $d;
	my $counter = 1;
	for my $item (@links) {
		$d .= "[$counter] ". colored($$item[0], 'underline') . " $$item[1]\n";
		$counter++;
	}
	if ($d) {
		print $OUT $d;
	}
	else {
		print $OUT "No links.\n";
	}
}

sub nav {
	# Setting 0: from links
	# Setting 1: from history
	my ($setting,$n) = @_;
	### $n
	### $setting
	### @_
	if (! $n or $n !~ /\d+/) {
		print $OUT "Try 'links' or 'hist' then 'nav x', where x is the number.\n";
		return 1;
	}
	$n -= 1;

	my $link;

	if ($setting == 0 and @links and exists $links[$n][0]) {
		$link = $links[$n][0];
	} elsif ($setting == 1 and @history and exists $history[$n][0]) {
		$link = $history[$n][0];
	}
	else {
		print $OUT "'" . ($n+1) ."' isn't available.\n";
		return 1;
	}
	access_resource($link);
}

sub access_resource {
	my ($link) = @_;
	# This implies it is valid fqdn
	if (has_scheme($link)) {
		url("$link");
	} elsif (substr($link,0,2) eq '//') { # technically valid
		url("gemini:$link");
	}
	else {
		my $c_url = parse_url($current_url);
		my $end_with_slash = 1 if ($link =~ m|.*/$|);
		my $begin_with_slash = 1 if ($link =~ m|^/.*|);

		### absolute location ?
		if ($begin_with_slash) {
			delete($c_url->{path});
			$c_url->{path} = $link;
			#if ($end_with_slash){
			#	$c_url->{path} .= "/";
			#}
			substr($c_url->{path},0,1,'');
			url(return_url($c_url));
			return 	0;
		}

		### current url is a directory ?
		if ($current_url =~ m|.*/$|) {
			$current_url .= $link;
			#if ($end_with_slash) {
			#	$current_url .= "/";
			#}
			url(return_url($current_url));
			return 0;
		} 
		else { 
			### current url must NOT be a directory
			my $d;
			if ($c_url->{path}) {
				my $cp_url = split_url_path($c_url->{path}, 256);
				pop(@$cp_url);
				for (@$cp_url) {
					$d .= "$_/";
				}
			}
			$d .= $link;
			$c_url->{path} = normalize_path($d);
			if ($end_with_slash) {
				$c_url->{path} .= "/";
			}
			url(return_url($c_url));
			return 0;
		}
	}
}

sub has_scheme {
	return ($_[0] =~ m|^.*(://)|);
}

sub root {
	my $new_url = parse_url($current_url);
	url("$new_url->{scheme}://$new_url->{host}/");
}

sub back {
	my ($display) = @_;

	### @_
	### $display
	my $dok_out = $doc_out;

	$doc_out = 0 if ($display == 1);

	if (@history >= 2) {
		url("$history[-2][0]");
	}
	else {
		print $OUT "No such history there.";
	}
	### @history

	$doc_out = $dok_out if ($display == 1);
}

sub display {
	if ($pager_text_wrap_auto) {
		my ($wc) = GetTerminalSize();
		$wrapper->columns($wc);
	}
	if ($use_pager) {
		IO::Pager::open(my $FH) or warn($!);
		for (@doc) {
			_pre_block($_);
			if ($pre_block) {
				print $FH $_;
			} 
			else {
				print $FH $wrapper->wrap($_);
			}
		}
	}
	else { 
		for (@doc) {
			_pre_block($_);
			if ($pre_block) {
				print $OUT $_;
			}
			else {
				print $OUT $wrapper->wrap($_);
			}
		}
	}
}

sub toggle {
	# refaliasing
	\my $t = \$_[0];
	if ($t == 1) {
		$t = 0;
	}
	else {
		$t = 1;
	}
	if (! $_[1]) {
		print $OUT "$t\n";
	}
}

sub textwrap {
	my ($c) = @_;
	if ($c and $c =~ m/^\d+$/) {
		$wrapper->columns($c);
		$pager_text_wrap_auto = 0;
	} elsif ($c and $c eq 'auto') {
		$pager_text_wrap_auto = 1;
	}
	else {
		if ($pager_text_wrap_auto) {
			my ($c) = GetTerminalSize();
			print("[AUTO] $c\n");
		}
		else {
			print("$wrapper->{columns}\n");
		}
	}
}

sub pager {
	my ($p) = @_;
	if ($p) {
		$ENV{pager} = $p;
		0;
	}
	else {
		print("$ENV{pager}\n");
	}
}

sub pretty_links {
	my $counter = 1;
	for (@doc) {
		_pre_block($_);
		if ((substr($_,0,2)) eq '=>' and not $pre_block) {
			$_ =~ m/^=>[\s]*([\w\d\-\\\/\.\:\~\?\=\#]+)[\s]*(.+)?$/;
			if ($2) {
				$_ = colored("[$counter" . _is_not_scheme_gemini($1) . "]",'underline') . " $2\n";
			}
			else {
				$_ = colored("[$counter" . _is_not_scheme_gemini($1) . "]",'underline') . " $1\n";
			}
			$counter++;
		}
	}
}

sub pretty_headers {
	for (@doc) {
		_pre_block($_);
		if ((substr($_,0,3)) eq '###' and not $pre_block) {
			$_ =~ s/^###[\s]*(.*)$/colored("$1",'underline')/e;
		}
		if ((substr($_,0,2)) eq '##' and not $pre_block) {
			$_ =~ s/^##[\s]*(.*)$/colored("$1",'bold')/e;
		}
		if ((substr($_,0,1)) eq '#' and not $pre_block) {
			$_ =~ s/^#[\s]*(.*)$/colored("$1",'bold', 'underline')/e;
		}
	}
}

sub _is_not_scheme_gemini {
	### @_
	my ($thing) = $_[0];
	if (has_scheme($thing)) {
			$_[0] =~ m|(.*)://.*|;
			if ($1 ne 'gemini') {
				return " $1";
			}
	}
	return '';
}

sub _pre_block {
	if (substr($_[0],0,3) eq '```') {
		toggle($pre_block,1);
		return 1;
	}
}

sub value_number {
	# refaliasing
	\my $v = \$_[0];
	my $numb = $_[1];
	my $k = $_[2];
	$v = $numb if ($numb =~ m/^\d*$/);
	print $OUT "$k is now: $v\n";
	### @_
}

sub clear_query {
	return 1 if (!$current_url);
	my @url = split('\?', $current_url);
	$current_url = $url[0];
}

sub cert_create {
	# this should create certs somewhere more optimal, rather than the working directory 

	my $old_umask = umask(077);

	if (! -e './certs') {
		mkdir('./certs');
	}
	print $OUT "What should the profile name be? ";
	chomp(my $input = <STDIN>);
	$input =~ tr|/|.|;
	if (-e "./certs/$input") {
		print $OUT "Sorry, but that already exists.\n";
	}
	else {
		mkdir("./certs/$input");
		print $OUT "What should the commonName be? (it will be used to identify you easily) ";
		chomp(my $common_name = <STDIN>);
		#print $OUT "When should this expire (in seconds ('31536000' = 1 year))? ";
		my $expire;
		while (1) {
			print $OUT "When should this expire? (1s, 1h, 1d, 1m, 1y, 0s (cancel)) ";
			chomp($expire = <STDIN>);
			if ($expire =~ m/^(\d+)+(\w)$/) {
				if (lc $2 eq 's') {
					if ($1 == 0) {
						print $OUT "Cancelling.\n";
						umask($old_umask);
						return 1;
					}
					else {
						$expire = $1 + time();
					}
				} elsif (lc $2 eq 'h') {
					$expire = ($1*3600) + time(); # 3600 seconds in an hour
				} elsif (lc $2 eq 'd') {
					$expire = ($1*86400) + time(); # 86400 seconds in a day
				} elsif (lc $2 eq 'm') {
					$expire = ($1*2592000) + time(); # 2592000 seconds in 30 days (month)
				} elsif (lc $2 eq 'y') {
					$expire = ($1*31536000) + time(); # 31536000 seconds in 365 days (year)
				} else {
					next;
				}
			}
			else {
				next;
			}
			last;
		}
		my $not_before = time();
		### $expire
		### $not_before
		my %cert = (
			'subject' => {
				'commonName' => "$common_name",
			},
			'not_before' => $not_before,
			'not_after' => $expire,
		);
		my ($cert, $key) = CERT_create(%cert);
		PEM_cert2file($cert,"./certs/$input/cert.pem");
		PEM_key2file($key,"./certs/$input/key.pem");
		CERT_free($cert);
		KEY_free($key);
	}
	umask($old_umask);
}

sub cert_use {
	if (! $use_cert) {

		my $counter = 1;
		my @profiles;
		# this should read dirs from a more optimal location, rather than working directory
		if (! -e './certs') {
			print $OUT "You need to create a cert first: 'cert-create'.\n";
			return 1;
		}
		for (read_dir('./certs')) { 
			print $OUT "[$counter] $_\n";
			push(@profiles, "$_");
			$counter++;
		}
		if (! @profiles) {
			print $OUT "You need to create a cert first: 'cert-create'.\n";
			return 1;
		}

		print $OUT "Which profile? ";
		chomp(my $input = <STDIN>);

		if ($input) {
			print $OUT "Loading 'certs/$profiles[$input-1]/cert.pem' and 'certs/$profiles[$input-1]/key.pem'\n";
			eval {
				$cert = PEM_file2cert("certs/$profiles[$input-1]/cert.pem");
					$key = PEM_file2key("certs/$profiles[$input-1]/key.pem");
				CERT_free($cert);
				KEY_free($key);
				$cert = "certs/$profiles[$input-1]/cert.pem";
				$key = "certs/$profiles[$input-1]/key.pem";
			};
			if ($@) {
				print $OUT "Something is wrong with the certificate/key. Will not use.\n$@";
				$cert = "";
				$key = "";
			}
			else {
				print $OUT "Cert and Key loaded.\n";
				toggle($use_cert);
			}
		}
		else {
			print $OUT "Did not load anything.\n";
		}
	}
	else {
		print $OUT "Unloading cert and key.\n";
		toggle($use_cert);
	}
}

sub cert_del {
	# cert dir should be in a more optimal place, not working directory.
	if (! -e './certs') {
		print $OUT "You have no certs/ directory.\n";
		return 0;
	}

	my $counter = 1;
	my @profiles;
	for (read_dir('./certs')) { 
		print $OUT "[$counter] $_\n";
		push(@profiles, "$_");
		$counter++;
	}
	if (! @profiles) {
		print $OUT "You need to create a cert first: 'cert-create'.\n";
		return 1;
	}
	print $OUT "Delete which profile? ";
	chomp(my $input = <STDIN>);
	if ($input) {
		print $OUT "Are you sure you want to delete certs/$profiles[$input-1]/? y/N\n";
		chomp(my $yORn = <STDIN>);
		if (lc $yORn eq 'y') {
			unlink("./certs/$profiles[$input-1]/cert.pem","./certs/$profiles[$input-1]/key.pem");
			rmdir("./certs/$profiles[$input-1]");
			if ($!) {
				print $OUT "Unable to delete profile.\n$!\n";
			}
			else {
				print $OUT "Profile '$profiles[$input-1]' succesfully deleted.\n";
			}
		}
		else {
			print $OUT "Nothing is deleted.\n";
		}
	}
	else {
		print $OUT "Nothing is deleted.\n";
	}
}