-
Notifications
You must be signed in to change notification settings - Fork 1
/
u
executable file
·8157 lines (7392 loc) · 217 KB
/
u
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
#!/usr/bin/env perl
# If you use a cPanel-based hosting service, change perl to perlml in the above
# line (#!/usr/bin/env perlml) to allow Perl to find modules installed in the
# user directory. You can revert this change if you have "use
# cPanelUserConfig;" in u.cfg.
#
################################################################################
# Uniqki: Unique Wiki <https://uniqki.isnew.info/>
# Author: Huidae Cho
# Since: May 23, 2007
#
# Copyright (C) 2007-2008, 2010-2011, 2016-2020, Huidae Cho
# <https://idea.isnew.info/>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
################################################################################
use strict;
# The document root directory relative to the server's URL including /~user, if
# any. For example, if the full URL path to index.html is
# http://example.com/~user/index.html, $doc_root should be set to ".". Leave it
# blank if you can run this script outside of the cgi-bin directory.
my $doc_root = "";
# Temporary admin user: admin, password: admin. DO NOT CHANGE THIS VARIABLE.
my $tmp_adminpw = 'admin:7352327a53727a65613d7a4cb055d722c21f1a0f17ad676daccd4ad8bf728134c9ee739e5f51c9af822da15b69985908148c55b6fdea4bc0bcd5aff660a53db428a9898c12743c7d:admin:@:Administrator:';
# Running this script for the first time will create the password file u.pw
# using the $adminpw credential, which is set to $tmp_adminpw by default. Since
# this password is public, make sure to change the admin password after the
# first login to update the password file. If $adminpw in the following line is
# not the same as $tmp_adminpw, Uniqki will assume that you have changed
# $adminpw to remove the password file and use this script instead for login,
# and will not create the password file again. Using this feature, it is
# possible to operate a Uniqki site with this file alone by removing the
# password file after setting the $adminpw variable to your new credential in
# u.pw. Make sure to back up this variable when updating the script.
# Optionally, you can create u.cfg and template files in u.tpl by running
# u?install_config and u?install_template, respectively, but these files are
# only used for customizations and are not required.
my $adminpw = $tmp_adminpw;
################################################################################
# HTTP server environment variables
use vars qw(
$CFG
$HTTPS $HTTP_COOKIE $HTTP_HOST $SERVER_NAME $SCRIPT_NAME $PATH_INFO
$QUERY_STRING $REQUEST_METHOD $CONTENT_TYPE $CONTENT_LENGTH $REMOTE_ADDR
);
# Useful variables
use vars qw(
$HTTP_BASE $DOC_BASE $CGI $PAGE $FILE $USER $NAME $AUTHOR
);
# Template variables
use vars qw(
$MAIN $TITLE $TEXT $START $COUNT $PREVIEW $VERSION $TIME
$PASSWORD_RESET_TOKEN $MESSAGE $PARSING_TIME
);
# Config and messages variables
use vars qw(
$SITE_TITLE $SITE_DESCRIPTION $SITE_URL
$INDEX_PAGE $LANG $CHARSET $LOCALE $TIME_ZONE $TIME_FORMAT
$SHARE_COOKIES
$PASSWORD_FILE $SESSIONS_FILE $MESSAGES_FILE $TEMPLATE_DIRECTORY
$PAGE_NAME_STYLE
$SECTION_NUMBER_PREFIX $SECTION_NUMBER_SEPARATOR $SECTION_NUMBER_SUFFIX
$SECTION_REFERENCE_PREFIX $SECTION_REFERENCE_SUFFIX
$TABLE_NUMBER_PREFIX $TABLE_NUMBER_SUFFIX
$TABLE_REFERENCE_PREFIX $TABLE_REFERENCE_SUFFIX
$FIGURE_NUMBER_PREFIX $FIGURE_NUMBER_SUFFIX
$FIGURE_REFERENCE_PREFIX $FIGURE_REFERENCE_SUFFIX
$INACTIVE_TIMEOUT $SET_PASSWORD_TIMEOUT $RESET_PASSWORD_TIMEOUT
$EMAIL_ADDRESS $SMTP $MIME_TYPE_COMMAND
$READ_ACCESS $WRITE_ACCESS $HIDE_SOURCE
$PAGES_NOT_ALLOWED
$USER_PARSERS_FILE
$HEADER_FILE $FOOTER_FILE
$NONWIKI_HEADER_FILE $NONWIKI_FOOTER_FILE
$WIKI_HEADER_FILE $WIKI_FOOTER_FILE
$WIKI_PAGES_ALLOWED $WIKI_FILES_ALLOWED
$MINIMUM_COMMENT_TIME
%MESSAGES
);
# parse_file() global variables
use vars qw(
@begin_parsing
@parse_line
@end_parsing
@process_raw_block
@preprocess_line
@process_block
@process_asis_lines
@skip_comment
@process_wiki_command
@process_nonwiki_command
@skip_unknown_command
@start_block
@process_collected_lines
@process_paragraph_break
@escape_inline_syntax
@process_inline_syntax
@collect_lines
@process_line_syntax
@start_paragraph
@postprocess_line
@close_all_open
);
# parse_file() local variables
use vars qw(
$lineno $text $url_chars $url_puncts $fresh_block $code_block
$syntax_block $block_indent @parsed_blocks $re_block $re_start $re_n
@re_pat @re_rep @re_opts $p $asis $nosyntax $pre $pre_code $blockquote
$list $table $figure @h_lines %h_n $h_top $h_prev %h_secs %secs_no $toc
$toc_dep $tab_no %tabs_n %tabs $lot $nolot $fig_no %figs_n %figs $lof
$nolof
);
# Other global variables
# $is_wiki
# 0 non-wiki
# 1 wiki
# $is_preview
# 0 non-preview
# 1 entire document
# 2 partial not current section
# 3 current section
# $is_block
# 0 main text
# 1 syntax block
# 2 fresh block
use vars qw(
$is_wiki
$is_preview
$is_block
$preprocess_text
$verify_input
);
umask 022;
my $win = $^O eq "MSWin32" ? 1 : 0;
eval "use Time::HiRes";
my $show_parsing_time = $@ ? 0 : 1;
if(!defined $ENV{GATEWAY_INTERFACE}){
my $cmd = "";
my %opt;
for(my $i = 0; $i <= $#ARGV; $i++){
if("-" eq substr $ARGV[$i], 0, 1){
my $name = substr $ARGV[$i], 1;
if($name eq "p" || $name eq "c" || $name eq "k" ||
$name eq "i" || $name eq "f"){
die "$ARGV[$i] option requires a value"
if $i + 1 > $#ARGV;
$opt{$name} = $ARGV[++$i];
}else{
$opt{$name} = 1;
}
}elsif($cmd eq ""){
$cmd = $ARGV[$i];
}else{
die "Provide only one command";
}
}
if($opt{p} ne "" && $opt{p} !~ /^[0-9]+$/){
die "Port must be a number";
}
if($opt{p} eq ""){
$opt{p} = $opt{c} eq "" ? 80 : 443;
}
if($opt{c} ne "" && !-f $opt{c}){
die "$opt{c}: File not found";
}
if($opt{k} ne "" && !-f $opt{k}){
die "$opt{k}: File not found";
}
if(($opt{c} eq "" && $opt{k} ne "") ||
($opt{c} ne "" && $opt{k} eq "")){
die "Both cert and key files must be specified";
}
if($opt{i} eq ""){
$opt{i} = "index.html";
}
if($opt{f} eq ""){
$opt{f} = '(?:^u\.(?:cfg|pw|msg|pid|log)|^\.sessions|\.(?:tpl|txt|txt\.v))$';
}
if($opt{r} && $opt{s}){
die "-r and -s are mutually exclusive";
}
my $u = $0;
if($u =~ m#^(.*)[\\/](.+)#){
chdir $1;
$u = $2;
}
my $pid_file = "u.pid";
my $log_file = "u.log";
my $foreground = 0;
sub logger{
my @msg = @_;
local *FH;
open FH, ">>$log_file";
printf FH @msg;
close FH;
printf @msg if $foreground;
}
sub die_logger{
logger @_;
die;
}
sub get_pid{
return 0 unless -f $pid_file;
local *FH;
open FH, $pid_file;
my $pid = <FH>;
close FH;
chomp $pid;
my $alive = kill 0, $pid;
unlink $pid_file unless $alive;
return $alive ? $pid : 0;
}
sub stop_server{
my $pid = get_pid();
if($pid > 0){
kill 9, $pid;
logger "Stopped by the user.\n";
}
unlink $pid_file;
}
sub respond_error{
my ($client, $code_msg) = @_;
(my $msg = $code_msg) =~ s/^[0-9]+ //;
logger "$code_msg\n\n";
select $client;
print "HTTP/1.1 $code_msg\n";
print "Content-Type: text/plain\n\n";
print "$msg\n";
}
sub respond_location{
my ($client, $url) = @_;
logger "Redirecting to $url...\n\n";
select $client;
print "HTTP/1.1 302 Found\n";
print "Location: $url\n\n";
}
sub respond_file{
my ($client, $file) = @_;
logger "Sending $file...\n\n";
my $mime_type = get_mime_type($file);
select $client;
print "HTTP/1.1 200 OK\n";
print "Content-Type: $mime_type\n\n";
local *FH;
open FH, $file;
binmode FH;
print <FH>;
close FH;
}
if($cmd eq "start" || $cmd eq "restart"){
################################################################################
# Tiny HTTP server to self-serve Uniqki
my $pid;
unless($win){
$pid = get_pid();
if($pid > 0){
if($cmd eq "start"){
die "Process $pid is still running";
}else{
stop_server();
}
}
}
$ENV{GATEWAY_INTERFACE} = "CGI/1.1";
eval "use IO::Socket::INET;1" or
die "The IO::Socket::INET module is required to self-serve Uniqki";
my $server = IO::Socket::INET->new(
Proto=>"tcp",
LocalPort=>$opt{p},
Listen=>SOMAXCONN(),
Reuse=>1) || die "Cannot create a socket";
if($opt{c} ne ""){
$ENV{HTTPS} = "on";
eval "use IO::Socket::SSL;1" or
die "The IO::Socket::SSL module is required to self-serve Uniqki";
}else{
$ENV{HTTPS} = "off";
}
if($win){
print "Close this window to terminate the service.\n";
$foreground = 1;
}else{
$pid = fork();
# $pid > 0 on Unix: Background process
# $pid < 0 on Windows: Multi-threaded
if(defined $pid && $pid > 0){
# Parent of successful fork on Unix
local *FH;
print "Running in the background. Kill process $pid later to terminate the service.\n";
print "The process ID $pid is stored in $pid_file.\n";
print "Log messages are being written to $log_file.\n";
open FH, ">$pid_file";
print FH "$pid\n";
close FH;
exit;
}elsif(!defined $pid){
# Unsuccessful fork
print "Cannot fork the server. Running in the foreground.\n";
$foreground = 1;
} # else child of successful fork on Unix
}
while(my $client = $server->accept()){
$pid = fork();
die_logger "Cannot fork the client.\n"
unless defined $pid;
if($pid){
# Parent closes the client and listens again
close $client;
next;
}
if($opt{c} ne ""){
IO::Socket::SSL->start_SSL($client,
SSL_server=>1,
SSL_cert_file=>$opt{c},
SSL_key_file=>$opt{k}) ||
die_logger "Failed to SSL handshake.\n";
}
$client->autoflush(1);
$ENV{REMOTE_ADDR} = $client->peerhost();
logger "========== %s ==========\n", scalar localtime;
logger "Request from %s\n", $ENV{REMOTE_ADDR};
while(<$client>){
logger $_;
s/\r\n//;
if(m#^([A-Z]+) (.*?)(?:\?(.*))? HTTP\/[0-9.]+$#){
$ENV{REQUEST_METHOD} = $1;
$ENV{REQUEST_URI} = $2;
$ENV{QUERY_STRING} = $3;
}elsif(/^([^:]+): (.*)$/){
my $field = uc $1;
if($field eq "HOST"){
$ENV{HTTP_HOST} = $2;
($ENV{SERVER_NAME} = $2) =~ s/:[0-9]+$//;
}elsif($field eq "CONTENT-TYPE"){
$ENV{CONTENT_TYPE} = $2;
}elsif($field eq "CONTENT-LENGTH"){
$ENV{CONTENT_LENGTH} = $2;
}elsif($field eq "COOKIE"){
$ENV{HTTP_COOKIE} = $2;
}
}elsif($_ eq ""){
last;
}
}
logger "Processing $ENV{REQUEST_URI}...\n";
$ENV{REQUEST_URI} =~ s#^/+#/#;
(my $request_uri = $ENV{REQUEST_URI}) =~ s#^/##;
my $request_file = $request_uri eq "" ? $opt{i} :
decode_url($request_uri);
if(($ENV{REQUEST_METHOD} ne "GET" &&
$ENV{REQUEST_METHOD} ne "POST") ||
"/" ne substr($ENV{REQUEST_URI}, 0, 1) ||
($ENV{REQUEST_METHOD} eq "POST" &&
$request_uri !~ m#^$u(?:/.*)?$#)){
respond_error($client, "400 Bad Request");
}elsif(($win &&
(($opt{c} ne "" && lc $request_file eq lc $opt{c}) ||
($opt{k} ne "" && lc $request_file eq lc $opt{k}) ||
$request_file =~ /$opt{f}/i)) ||
(!$win &&
(($opt{c} ne "" && $request_file eq $opt{c}) ||
($opt{k} ne "" && $request_file eq $opt{k}) ||
$request_file =~ /$opt{f}/))){
respond_error($client, "403 Forbidden");
}elsif($request_uri =~ m#^$u(/.*)?$#){
logger "Executing $u...\n\n";
$ENV{SCRIPT_NAME} = "/$u";
$ENV{PATH_INFO} = decode_url($1);
*STDIN = $client
if $ENV{REQUEST_METHOD} eq "POST";
local *OUTPUT;
my $output;
open OUTPUT, ">", \$output;
select OUTPUT;
do $u;
close OUTPUT;
select $client;
my @items = split /\n\n/, $output;
if($items[0] =~ /^Location: /m){
print "HTTP/1.1 302 Found\n";
}else{
print "HTTP/1.1 200 OK\n";
}
print $output;
}elsif($opt{r} && ".html" eq substr($request_file, -5)
&& !-f $request_file){
my $url = "/$u/".substr($request_uri, 0,
length($request_uri) - 5);
respond_location($client, $url);
}elsif($opt{r} && ".html" ne substr($request_file, -5)
&& -f "$request_file.html"){
my $url = "/$request_uri.html";
respond_location($client, $url);
}elsif($opt{s}){
(my $page = $request_uri) =~ s/\.html$//;
my $url = "/$u";
$url .= "/$page" if $page ne "";
respond_location($client, $url);
}elsif(-f $request_file){
respond_file($client, $request_file);
}else{
respond_error($client, "404 Not Found");
}
close $client;
exit;
}
exit;
}elsif($cmd eq "stop"){
stop_server();
exit;
}elsif($cmd eq "password"){
eval "use Digest::HMAC_SHA1 qw(hmac_sha1);1" or
die "The Digest::HMAC_SHA1 module is required to hash passwords";
printf "my \$tmp_adminpw = 'admin:%s:admin:\@:Administrator:';\n", hash_password("admin", "admin");
exit;
}
print <<EOT;
Usage: $u COMMAND [OPTIONS]
start Start the server
-p <port> Port number (default: 80 for HTTP and 443 for HTTPS)
-c <cert.pem> SSL certificate file
-k <key.pem> SSL key file
-i <index.html> Index HTML
-f <forbidden> Regular expression for forbidden files (default:
(^u\\.(cfg|pw|msg|pid|log)|^\\.sessions|\\.(tpl|txt|txt\\.v))\$)
-r Redirect non-existing HTML requests to $u and non-HTML
requests to existing HTML files
-s Secure the server by redirecting all requests to $u; Any
of \$READ_ACCESS or \$WRITE_ACCESS must be closed to avoid
infinite redirections
EOT
unless($win){
print <<EOT;
restart Restart the server
stop Stop the server
EOT
}
print <<EOT;
password Print a new admin password hash
Please run this script from a web browser or with one of the above commands.
EOT
exit;
}
################################################################################
# CGI variables
$CFG = $ENV{HTTP_UNIQKI_CONFIG};
$HTTPS = $ENV{HTTPS};
$HTTP_COOKIE = $ENV{HTTP_COOKIE};
$HTTP_HOST = $ENV{HTTP_HOST};
$SERVER_NAME = $ENV{SERVER_NAME};
$SCRIPT_NAME = $ENV{SCRIPT_NAME};
$PATH_INFO = $ENV{PATH_INFO};
$QUERY_STRING = $ENV{QUERY_STRING};
$REQUEST_METHOD = $ENV{REQUEST_METHOD};
$CONTENT_TYPE = $ENV{CONTENT_TYPE};
$CONTENT_LENGTH = $ENV{CONTENT_LENGTH};
$REMOTE_ADDR = $ENV{REMOTE_ADDR};
################################################################################
# Useful variables
# Supported URLs:
# This script outside cgi-bin: $doc_root = ""
# * https?://host/~user/dir/u/page/path/to/file?query
# * CGI: u
# * DOC_BASE: https?://host/~user/dir
# This script inside cgi-bin: $doc_root != ""
# * https?://host/~user/cgi-bin/u/page/path/to/file?query
# * CGI: /~user/cgi-bin/u
# * DOC_BASE: https?://host/~user/doc_root
# * HTTP_BASE: https?://host
# * PAGE: page
# * FILE: path/to/file
$CGI = $SCRIPT_NAME;
$HTTP_BASE = ($HTTPS eq "on" ? "https" : "http")."://$HTTP_HOST";
$DOC_BASE = "$HTTP_BASE$CGI"; $DOC_BASE =~ s#/[^/]*$##;
$PAGE = substr $PATH_INFO, 1; $PAGE =~ s#/.*$##;
$PAGE =~ s#\.(?:html|txt|txt\.v)$##;
$FILE = $PATH_INFO; $FILE =~ s#^/[^/]+##; $FILE =~ s#^/##;
################################################################################
# Awardspace.com free web hosting
my $hosting = "";
if(-d "/home/www/$SERVER_NAME"){
$hosting = "awardspace";
$_ = "/home/www/$SERVER_NAME$SCRIPT_NAME";
s#/[^/]*$##;
chdir $_;
}
if($doc_root eq ""){
$CGI =~ s#^.*/##;
}else{
($_ = $CGI) =~ s#/[^/]+$##;
s#^/~[^/]+##;
if($_ eq ""){
chdir $doc_root;
}else{
s#^/##; s#[^/]+#..#g;
chdir "$_/$doc_root";
}
$DOC_BASE = $HTTP_BASE.($CGI =~ m#(^/~[^/]+)# ? $1 : "")."/$doc_root";
}
################################################################################
# Prepare the default parser
prepare_parser();
################################################################################
# Read the config file
process_cfg();
$INDEX_PAGE = "index" if $INDEX_PAGE eq "";
if($TIME_ZONE ne ""){
if($TIME_ZONE =~ /^gmt([+-])([0-9]+)$/i){
$TIME_ZONE = "GMT".($1 eq "+" ? "-" : "+").$2;
}
$ENV{TZ} = $TIME_ZONE;
}
eval "use POSIX qw(setlocale LC_ALL tzset strftime);";
my $use_posix = $@ ? 0 : 1;
if($use_posix){
setlocale(LC_ALL(), $LOCALE) if $LOCALE ne "";
tzset() if $TIME_ZONE ne "";
$TIME_FORMAT =~ s/%e/%#d/g if $win;
}
my $smtp_server = "";
my $smtp_port;
my $smtp_username;
my $smtp_password;
if($SMTP =~ /^([a-z0-9.-]+\.[a-z]{2,}):([0-9]*):([^:]*):(.*)$/i){
$smtp_server = $1;
$smtp_port = $2;
$smtp_username = $3;
$smtp_password = $4;
}
my ($page_name_case, $page_name_dots, $page_name_spaces) =
config_page_name_style();
my ($nonwiki_read_access, $wiki_read_access) = config_access($READ_ACCESS);
my ($nonwiki_comment_access, $wiki_write_access) = config_access($WRITE_ACCESS);
################################################################################
# Messages
process_msg();
################################################################################
# hmac_sha1 subroutine for password hashing
eval "use Digest::HMAC_SHA1 qw(hmac_sha1);1" or
die_message("perl_module_not_installed", "Digest::HMAC_SHA1");
################################################################################
# Initialization
$USER = "";
$NAME = "Visitor";
my $admin = 0;
my $rebuild = 0;
my $insecure_pw = 1;
my $sessions_file = $SESSIONS_FILE eq "" ? ".sessions" : $SESSIONS_FILE;
my $debug_started = 0;
my %locked_files = ();
my $cookie_attributes = get_cookie_attributes();
my $strip_query_string = 1;
################################################################################
# Non-user-replaceable subroutines
sub debug{
my $msg = shift;
unless($debug_started){
$debug_started = 1;
print "Content-Type: text/plain\n\n";
}
printf "%s\n", $msg;
}
sub format_time{
my $time = shift;
my $ftime;
if($use_posix && $TIME_FORMAT ne ""){
$ftime = strftime($TIME_FORMAT, localtime $time);
}else{
$ftime = scalar localtime $time;
}
return $ftime;
}
sub config_page_name_style{
my ($case, $dots, $spaces);
foreach my $item (split /:/, $PAGE_NAME_STYLE){
if("_case" eq substr $item, -5){
$case = $item;
if($case eq "lower_camel_case"){
$dots = "no_dots";
$spaces = "no_spaces";
}elsif($case eq "upper_camel_case"){
$case = "start_case";
$dots = "no_dots";
$spaces = "no_spaces";
}
}elsif("dots" eq substr $item, -4){
$dots = $item;
}else{
$spaces = $item;
}
}
if($case ne "upper_case" && $case ne "mixed_case" &&
$case ne "start_case" && $case ne "lower_camel_case" &&
$case ne "upper_camel_case"){
# Default lower_case
$case = "lower_case";
}
if($dots ne "no_dots"){
# Default dots
$dots = "dots";
}
if($spaces ne "no_spaces" && $spaces ne "underscores"){
# Default hyphens
$spaces = "hyphens";
}
return ($case, $dots, $spaces);
}
sub config_access{
my $access = shift;
my @items = split /:/, $access;
my $nonwiki_access = $items[0] ne "open" && $items[0] ne "closed" ?
"admin" : $items[0];
my $wiki_access = index($access, ":") == -1 ?
$nonwiki_access :
($items[1] ne "open" && $items[1] ne "closed" ?
"admin" : $items[1]);
return ($nonwiki_access, $wiki_access);
}
sub run_file_mime_type{
my $file = shift;
return "" if $MIME_TYPE_COMMAND eq "" || !-f $file;
(my $mime_type = `$MIME_TYPE_COMMAND $file`) =~ y/\r\n//d;
return $mime_type;
}
sub get_mime_type{
my $file = shift;
return "" unless -f $file;
my $mime_type;
eval "use MIME::Types;";
if($@){
$mime_type = run_file_mime_type($file);
}else{
$mime_type = MIME::Types->new(only_iana=>1)->mimeTypeOf($file);
$mime_type = run_file_mime_type($file)
if $mime_type eq "";
}
$mime_type = "application/octet-stream" if $mime_type eq "";
return $mime_type;
}
sub die_path{
(my $path = shift) =~ s#/+$##;
unless(-e $path){
# Inside a file listing (u/page/)? strip out the page name. Its
# main purpose is to be able to use relative paths in the
# template.
# e.g., "u.tpl/..." inside u/page/?
# page/u.tpl/... does not exist. Try to find u.tpl/... instead.
if($path =~ m#^([^/]*)/(.*)$# && $1 eq $PAGE){
# handle a deep path
# e.g., "u.tpl/..." inside u/page/dir/?
# page/dir/u.tpl/... => u.tpl/...
do{
$path = $2;
}while(!-e $path && $path =~ m#^([^/]*)/(.*)$#);
}
die_redirect("$DOC_BASE/$CGI/$path") unless -e $path;
}
if($nonwiki_read_access eq "open" && $wiki_read_access eq "open"){
# Don't handle a file or a deep $path (page/dir). Just pass it
# to the web server for security reasons. Remember Uniqki does
# not support a hierarchical page structure. It's always page/
# or page/file, not page/dir/... The only exception is for
# template files (see the deep path code in the above unless
# block.
die_redirect("$DOC_BASE/$path") if !-d $path || $path =~ m#/#;
}else{
# Closed site, so we cannot redirect to the file URL. Handle
# file downloads.
my $mime_type = get_mime_type($path);
(my $file = $path) =~ s#^.*/##;
my $content = read_file($path);
print qq(Content-Type: $mime_type\nContent-Disposition: inline; filename="$file"\n\n$content);
die;
}
# Don't allow arbitrary directories to be listed. No page, no listing.
die_redirect("$HTTP_BASE$SCRIPT_NAME/$PAGE") unless page_exists();
my $title = get_msg("page_files", $path);
(local $TITLE = $title) =~ s/<[^>]*>//g;
my $base_tpl = print_base(2);
print_header($base_tpl);
print qq(<div class="list">\n<h1>$title</h1>\n<ul>\n);
foreach(<$path/*>){
my $is_dir = -d $_;
my $item = $_;
s#^.*/##;
my $url = encode_url_safe($_).($is_dir ? "/" : "");
s/&/&/g; s/</</g; s/>/>/g;
my $name = $_.($is_dir ? "/" : "");
my @stat = stat $item;
my $size = $stat[7];
while($size =~ s/([0-9]+)([0-9]{3})/\1,\2/){};
my @t = localtime($stat[9]);
my $time = sprintf "%d-%02d-%02d %02d:%02d:%02d",
$t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0];
print qq(<li><a href="$url">$name</a> <span class="list-size">$size</span> <span class="list-time">$time</span></li>\n);
}
print qq(</ul></div>\n);
print_footer($base_tpl);
die;
}
sub die_message{
local $MESSAGE = get_msg(@_);
(local $TITLE = $MESSAGE) =~ s/<[^>]*>//g;
print_html(print_message(2));
die;
}
sub die_rebuild{
my $PAGE = shift;
if(-f "$PAGE.txt"){
make_html($PAGE);
die_redirect("$HTTP_BASE$SCRIPT_NAME/$PAGE");
}
die_redirect("$HTTP_BASE$SCRIPT_NAME/$INDEX_PAGE");
}
sub die_redirect{
printf "Location: %s\n\n", shift;
die;
}
sub die_text{
print "Content-Type: text/plain\n\n";
print shift;
die;
}
sub start_html{
print "Content-Type: text/html\n\n";
}
sub convert_page_name{
my $page_name = shift;
my $forbidden_chars = q(`~!@#\$%^&*=+\\\\|;:'",\/?()\[\]{}<>);
# from parse_line
# escaped html codes
$page_name =~ s/(\x00?&[^;]*;)+/ /g;
$page_name =~ y/\x01/&/;
$page_name =~ y/\x02/</;
$page_name =~ y/\x03/>/;
$page_name =~ s/[$forbidden_chars \t_-]+/ /og;
if($page_name_dots eq "dots"){
$page_name =~ s/\.+/./g;
$page_name =~ s/(?:\.? \.?)+/ /g;
}else{
$page_name =~ y/.//d;
$page_name =~ s/ +/ /g;
}
# Allow page names starting with a dot
$page_name =~ s/^ |[. ]$//g;
return "" if $page_name eq "";
if($page_name_case eq "mixed_case"){
# case as is
}elsif($page_name_case eq "upper_case"){
$page_name = uc $page_name;
}elsif($page_name_case eq "start_case"){
$page_name =~ s/(?:^|(?<=[ .]))([^ .])([^ .]*)/@{[(uc $1).(lc $2)]}/g;
}elsif($page_name_case eq "lower_camel_case"){
$page_name =~ s/^([^ .]*)/@{[lc $1]}/;
$page_name =~ s/(?<=[ .])([^ .])([^ .]*)/@{[(uc $1).(lc $2)]}/g;
}else{
# Default lower_case
$page_name = lc $page_name;
}
if($page_name_spaces eq "no_spaces"){
$page_name =~ y/ //d;
}elsif($page_name_spaces eq "underscores"){
$page_name =~ y/ /_/;
}else{
# Default hyphens
$page_name =~ y/ /-/;
}
return $page_name;
}
sub unescape_comment{
my $text = shift;
$text =~ y/\x00//d;
return $text;
}
sub escape_comment{
my $text = shift;
$text =~ s/^([#%])/\x00$1/mg;
$text =~ s/``(.*?)``/`\x00`$1`\x00`/g;
$text =~ s/^(---+)$/\x00$1/mg;
$text =~ s/^\x00(---+)\n(.*?)\n\x00\1$/$1\n@{[unescape_comment($2)]}\n$1/smg;
$text =~ s/\x00/''''/g;
return $text;
}
sub link_page{
my ($page, $section, $title) = @_;
$page =~ s/^[ \t]+|[ \t]+$//g;
$section =~ s/^[ \t]+|[ \t]+$//g;
$title =~ s/^[ \t]+|[ \t]+$//g;
my $enc_page = encode_url_safe(convert_page_name($page));
my $enc_section = encode_url_safe(convert_page_name($section));
$enc_section = "-$enc_section" if $enc_section ne "";
if($enc_page eq ""){
return "" if $enc_section eq "";
return qq(<a class="auto-title" href="#$enc_section">$section</a>) if $title eq "";
return qq(<a href="#$enc_section">$title</a>);
}
if($enc_section eq ""){
return qq(<a class="auto-title" href="$enc_page.html">$page</a>) if $title eq "";
return qq(<a href="$enc_page.html">$title</a>);
}
return qq(<a class="auto-title" href="$enc_page.html#$enc_section">$section</a>) if $title eq "";
return qq(<a href="$enc_page.html#$enc_section">$title</a>);
}
sub link_image{
# file: current page's file
# ./file: current page's file
# page/file: page's file
# /file: DOC_BASE's file
my ($path, $title, $style) = @_;
$path =~ s/^[ \t]+|[ \t]+$//g;
$title =~ s/^[ \t]+|[ \t]+$//g;
$style =~ s/^[ \t]+|[ \t]+$//g;
return "" if $path eq "." || $path eq "";
$style = qq( style="$style") if $style ne "";
my $page = $PAGE;
my $file = "";
my $i = rindex($path, "/");
if($i >= 0){
my $p = substr $path, 0, $i;
if($p eq ""){
# /file
$page = ".";
}elsif($p ne "."){
# page/file
$page = convert_page_name($p);
return "" if $page eq "";
}
# else ./file
$file = substr $path, $i + 1;
return "" if $file eq "";
}else{
# file
$file = $path;
}
my $enc_path = encode_url_safe("$page/$file");
return qq(<img class="auto-title" src="$enc_path" alt="$file" title="$file"$style />) if $title eq "";
return qq(<img src="$enc_path" alt="$title" title="$title"$style />);
}
sub link_file{
# .: current page's directory
# ./: current page's directory
# file: current page's file
# ./file: current page's file
# page/: page's directory
# page/file: page's file
# /: DOC_BASE
# /file: DOC_BASE's file
my ($path, $title) = @_;
$path =~ s/^[ \t]+|[ \t]+$//g;
$title =~ s/^[ \t]+|[ \t]+$//g;
my $page = $PAGE;
my $file = "";
my $i = rindex($path, "/");
if($i >= 0){
my $p = substr $path, 0, $i;
if($p eq ""){
# /, /file
$page = ".";
}elsif($p ne "."){
# page/, page/file
$page = convert_page_name($p);
return "" if $page eq "";
}
# else ./, ./file
$file = substr $path, $i + 1;
}elsif($path eq "."){
# .
$file = "";
}else{
# file
$file = $path;
}
if($file eq ""){
return qq(<a class="auto-title" href="$page/">$page/</a>) if $title eq "";
return qq(<a href="$page/">$title</a>);
}
my $enc_path = encode_url_safe("$page/$file");
return qq(<a class="auto-title" href="$enc_path">$file</a>) if $title eq "";
return qq(<a href="$enc_path">$title</a>);
}
sub link_url_image{
my ($url, $title, $style) = @_;
$url =~ s/^[ \t]+|[ \t]+$//g;
$title =~ s/^[ \t]+|[ \t]+$//g;
$style =~ s/^[ \t]+|[ \t]+$//g;