-
Notifications
You must be signed in to change notification settings - Fork 4
/
wakautils.pl
1507 lines (1221 loc) · 34.3 KB
/
wakautils.pl
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
# wakautils.pl v8.13
use strict;
use Time::Local;
use Time::Piece;
use Time::Seconds;
use Socket;
use utf8::all;
my $has_md5=0;
eval 'use Digest::MD5 qw(md5)';
$has_md5=1 unless $@;
my $has_encode=0;
eval 'use Encode qw(decode)';
$has_encode=1 unless $@;
use constant MAX_UNICODE => 1114111;
#
# HTML utilities
#
my $protocol_re=qr{(?:http://|https://|ftp://|mailto:|news:|irc:)};
my $url_re=qr{(${protocol_re}[^\s<>()"]*?(?:\([^\s<>()"]*?\)[^\s<>()"]*?)*)((?:\s|<|>|"|\.||\]|!|\?|,|,|")*(?:[\s<>()"]|$))};
sub protocol_regexp() { return $protocol_re }
sub url_regexp() { return $url_re }
sub abbreviate_html($$$)
{
my ($html,$max_lines,$approx_len)=@_;
my ($lines,$chars,@stack);
return undef unless($max_lines);
while($html=~m!(?:([^<]+)|<(/?)(\w+).*?(/?)>)!g)
{
my ($text,$closing,$tag,$implicit)=($1,$2,lc($3),$4);
if($text) { $chars+=length $text; }
else
{
push @stack,$tag if(!$closing and !$implicit);
pop @stack if($closing);
if(($closing or $implicit) and ($tag eq "p" or $tag eq "blockquote" or $tag eq "pre"
or $tag eq "li" or $tag eq "ol" or $tag eq "ul" or $tag eq "br"))
{
$lines+=int($chars/$approx_len)+1;
$lines++ if($tag eq "p" or $tag eq "blockquote");
$chars=0;
}
if($lines>=$max_lines)
{
# check if there's anything left other than end-tags
return undef if (substr $html,pos $html)=~m!^(?:\s*</\w+>)*\s*$!s;
my $abbrev=substr $html,0,pos $html;
while(my $tag=pop @stack) { $abbrev.="</$tag>" }
return $abbrev;
}
}
}
return undef;
}
sub sanitize_html($%)
{
my ($html,%tags)=@_;
my (@stack,$clean);
my $entity_re=qr/&(?!\#[0-9]+;|\#x[0-9a-fA-F]+;|amp;|lt;|gt;)/;
while($html=~/(?:([^<]+)|<([^<>]*)>|(<))/sg)
{
my ($text,$tag,$lt)=($1,$2,$3);
if($lt)
{
$clean.="<";
}
elsif($text)
{
$text=~s/$entity_re/&/g;
$text=~s/>/>/g;
$clean.=$text;
}
else
{
if($tag=~m!^\s*(/?)\s*([a-z0-9_:\-\.]+)(?:\s+(.*?)|)\s*(/?)\s*$!si)
{
my ($closing,$name,$args,$implicit)=($1,lc($2),$3,$4);
if($tags{$name})
{
if($closing)
{
if(grep { $_ eq $name } @stack)
{
my $entry;
do {
$entry=pop @stack;
$clean.="</$entry>";
} until $entry eq $name;
}
}
else
{
my %args;
$args=~s/\s/ /sg;
while($args=~/([a-z0-9_:\-\.]+)(?:\s*=\s*(?:'([^']*?)'|"([^"]*?)"|['"]?([^'" ]*))|)/gi)
{
my ($arg,$value)=(lc($1),defined($2)?$2:defined($3)?$3:$4);
$value=$arg unless defined($value);
my $type=$tags{$name}{args}{$arg};
if($type)
{
my $passes=1;
if($type=~/url/i) { $passes=0 unless $value=~/(?:^${protocol_re}|^[^:]+$)/ }
if($type=~/number/i) { $passes=0 unless $value=~/^[0-9]+$/ }
if($passes)
{
$value=~s/$entity_re/&/g;
$args{$arg}=$value;
}
}
}
$args{$_}=$tags{$name}{forced}{$_} for (keys %{$tags{$name}{forced}}); # override forced arguments
my $cleanargs=join " ",map {
my $value=$args{$_};
$value=~s/'/%27/g;
"$_='$value'";
} keys %args;
$implicit="/" if($tags{$name}{empty});
push @stack,$name unless $implicit;
$clean.="<$name";
$clean.=" $cleanargs" if $cleanargs;
#$clean.=" $implicit" if $implicit;
$clean.=">";
$clean.="</$name>" if $implicit;
}
}
}
}
}
my $entry;
while($entry=pop @stack) { $clean.="</$entry>" }
return $clean;
}
sub describe_allowed(%)
{
my (%tags)=@_;
return join ", ",map { $_.($tags{$_}{args}?" (".(join ", ",sort keys %{$tags{$_}{args}}).")":"") } sort keys %tags;
}
sub do_wakabamark($;$$)
{
my ($text,$handler,$simplify)=@_;
my $res;
my @lines=split /(?:\r\n|\n|\r)/,$text;
while(defined($_=$lines[0]))
{
if(/^\s*$/) { shift @lines; } # skip empty lines
elsif(/^(1\.|[\*\+\-]) /) # lists
{
my ($tag,$re,$skip,$html);
if($1 eq "1.") { $tag="ol"; $re=qr/[0-9]+\./; $skip=1; }
else { $tag="ul"; $re=qr/\Q$1\E/; $skip=0; }
while($lines[0]=~/^($re)(?: |\t)(.*)/)
{
my $spaces=(length $1)+1;
my $item="$2\n";
shift @lines;
while($lines[0]=~/^(?: {1,$spaces}|\t)(.*)/) { $item.="$1\n"; shift @lines }
$html.="<li>".do_wakabamark($item,$handler,1)."</li>";
if($skip) { while(@lines and $lines[0]=~/^\s*$/) { shift @lines; } } # skip empty lines
}
$res.="<$tag>$html</$tag>";
}
elsif(/^(?: |\t)/) # code sections
{
my @code;
while($lines[0]=~/^(?: |\t)(.*)/) { push @code,$1; shift @lines; }
$res.="<pre><code>".(join "<br />",@code)."</code></pre>";
}
elsif(/^>/) # quoted sections
{
my @quote;
while($lines[0]=~/^(>.*)/) { push @quote,$1; shift @lines; }
$res.="<blockquote>".do_spans($handler,@quote)."</blockquote>";
#while($lines[0]=~/^>(.*)/) { push @quote,$1; shift @lines; }
#$res.="<blockquote>".do_blocks($handler,@quote)."</blockquote>";
}
else # normal paragraph
{
my @text;
while($lines[0]!~/^(?:\s*$|1\. |[\*\+\-] |>| |\t)/) { push @text,shift @lines; }
if(!defined($lines[0]) and $simplify) { $res.=do_spans($handler,@text) }
else { $res.="<p>".do_spans($handler,@text)."</p>" }
}
$simplify=0;
}
return $res;
}
sub do_spans($@)
{
my $handler=shift;
return join "<br />",map
{
my $line=$_;
my @hidden;
# hide <code> sections
$line=~s{ (?<![\x80-\x9f\xe0-\xfc]) (`+) ([^<>]+?) (?<![\x80-\x9f\xe0-\xfc]) \1}{push @hidden,"<code>$2</code>"; "<!--$#hidden-->"}sgex;
# make URLs into links and hide them
$line=~s{$url_re}{push @hidden,"<a href=\"$1\" rel=\"nofollow\">$1\</a>"; "<!--$#hidden-->$2"}sge;
# do <strong>
$line=~s{ (?<![0-9a-zA-Z\*_\x80-\x9f\xe0-\xfc]) (\*\*|__) (?![<>\s\*_]) ([^<>]+?) (?<![<>\s\*_\x80-\x9f\xe0-\xfc]) \1 (?![0-9a-zA-Z\*_]) }{<strong>$2</strong>}gx;
# do <em>
$line=~s{ (?<![0-9a-zA-Z\*_\x80-\x9f\xe0-\xfc]) (\*|_) (?![<>\s\*_]) ([^<>]+?) (?<![<>\s\*_\x80-\x9f\xe0-\xfc]) \1 (?![0-9a-zA-Z\*_]) }{<em>$2</em>}gx;
# do ^H
if($]>5.007)
{
my $regexp;
$regexp=qr/(?:&#?[0-9a-zA-Z]+;|[^&<>])(?<!\^H)(??{$regexp})?\^H/;
$line=~s{($regexp)}{"<del>".(substr $1,0,(length $1)/3)."</del>"}gex;
}
$line=$handler->($line) if($handler);
# fix up hidden sections
$line=~s{<!--([0-9]+)-->}{$hidden[$1]}ge;
$line;
} @_;
}
sub compile_template($;$)
{
my ($str,$nostrip)=@_;
my $code;
unless($nostrip)
{
$str=~s/^\s+//;
$str=~s/\s+$//;
$str=~s/\n\s*/ /sg;
}
while($str=~m!(.*?)(<(/?)(var|const|if|loop)(?:|\s+(.*?[^\\]))>|$)!sg)
{
my ($html,$tag,$closing,$name,$args)=($1,$2,$3,$4,$5);
$html=~s/(['\\])/\\$1/g;
$code.="\$res.='$html';" if(length $html);
$args=~s/\\>/>/g;
if($tag)
{
if($closing)
{
if($name eq 'if') { $code.='}' }
elsif($name eq 'loop') { $code.='$$_=$__ov{$_} for(keys %__ov);}}' }
}
else
{
if($name eq 'var') { $code.='$res.=eval{'.$args.'};' }
elsif($name eq 'const') { my $const=eval $args; $const=~s/(['\\])/\\$1/g; $code.='$res.=\''.$const.'\';' }
elsif($name eq 'if') { $code.='if(eval{'.$args.'}){' }
elsif($name eq 'loop')
{ $code.='my $__a=eval{'.$args.'};if($__a){for(@$__a){my %__v=%{$_};my %__ov;for(keys %__v){$__ov{$_}=$$_;$$_=$__v{$_};}' }
}
}
}
my $sub=eval
'no strict; sub { '.
'my $protocol="http";'.
'if ($ENV{SERVER_PORT}==80 || $ENV{SERVER_PORT}==443) {'.
'my $port="";'.
'} else {'.
'my $port=":$ENV{SERVER_PORT}";'.
'}'.
'my $self=$ENV{SCRIPT_NAME};'.
'my $absolute_self="$protocol://$ENV{SERVER_NAME}$port$ENV{SCRIPT_NAME}";'.
'my ($path)=$ENV{SCRIPT_NAME}=~m!^(.*/)[^/]+$!;'.
'my $absolute_path="$protocol://$ENV{SERVER_NAME}$port$path";'.
'my %__v=@_;my %__ov;for(keys %__v){$__ov{$_}=$$_;$$_=$__v{$_};}'.
'my $res;'.
$code.
'$$_=$__ov{$_} for(keys %__ov);'.
'return $res; }';
die "Template format error" unless $sub;
return $sub;
}
sub template_for($$$)
{
my ($var,$start,$end)=@_;
return [map +{$var=>$_},($start..$end)];
}
sub include($)
{
my ($filename)=@_;
open FILE,"<:encoding(UTF-8)",$filename or return '';
my $file=do { local $/; <FILE> };
$file=~s/^\s+//;
$file=~s/\s+$//;
$file=~s/\n\s*/ /sg;
return $file;
}
sub forbidden_unicode($;$)
{
my ($dec,$hex)=@_;
return 1 if length($dec)>7 or length($hex)>7; # too long numbers
my $ord=($dec or hex $hex);
return 1 if $ord>MAX_UNICODE; # outside unicode range
return 1 if $ord<32; # control chars
return 1 if $ord>=0x7f and $ord<=0x84; # control chars
return 1 if $ord>=0xd800 and $ord<=0xdfff; # surrogate code points
return 1 if $ord>=0x202a and $ord<=0x202e; # text direction
return 1 if $ord>=0xfdd0 and $ord<=0xfdef; # non-characters
return 1 if $ord % 0x10000 >= 0xfffe; # non-characters
return 0;
}
sub clean_string($;$)
{
my ($str,$cleanentities)=@_;
if($cleanentities) { $str=~s/&/&/g } # clean up &
else
{
$str=~s/&(#([0-9]+);|#x([0-9a-fA-F]+);|)/
if($1 eq "") { '&' } # change simple ampersands
elsif(forbidden_unicode($2,$3)) { "" } # strip forbidden unicode chars
else { "&$1" } # and leave the rest as-is.
/ge # clean up &, excluding numerical entities
}
$str=~s/\</</g; # clean up brackets for HTML tags
$str=~s/\>/>/g;
$str=~s/"/"/g; # clean up quotes for HTML attributes
$str=~s/'/'/g;
$str=~s/,/,/g; # clean up commas for some reason I forgot
$str=~s/[\x00-\x08\x0b\x0c\x0e-\x1f]//g; # remove control chars
$str=~s/[\x{fdd0}-\x{fdef}\x{fffe}\x{ffff}\x{1fffe}\x{1ffff}\x{2fffe}\x{2ffff}\x{3fffe}\x{3ffff}\x{4fffe}\x{4ffff}\x{5fffe}\x{5ffff}\x{6fffe}\x{6ffff}\x{7fffe}\x{7ffff}\x{8fffe}\x{8ffff}\x{9fffe}\x{9ffff}\x{afffe}\x{affff}\x{bfffe}\x{bffff}\x{cfffe}\x{cffff}\x{dfffe}\x{dffff}\x{efffe}\x{effff}\x{ffffe}\x{fffff}\x{10fffe}\x{10ffff}]//g; # remove non-characters
return $str;
}
sub decode_string($;$$)
{
my ($str,$charset,$noentities)=@_;
my $use_unicode=$has_encode && $charset;
#$str=decode($charset,$str) if $use_unicode;
$str=~s{(&#([0-9]*)([;&])|&#([x&])([0-9a-f]*)([;&]))}{
my $ord=($2 or hex $5);
if($3 eq '&' or $4 eq '&' or $5 eq '&') { $1 } # nested entities, leave as-is.
elsif(forbidden_unicode($2,$5)) { "" } # strip forbidden unicode chars
elsif($ord==35 or $ord==38) { $1 } # don't convert & or #
elsif($use_unicode) { chr $ord } # if we have unicode support, convert all entities
elsif($ord<128) { chr $ord } # otherwise just convert ASCII-range entities
else { $1 } # and leave the rest as-is.
}gei unless $noentities;
$str=~s{(&#([0-9]+);|&#x([0-9a-f]+);)}{
if(forbidden_unicode($2,$3)) { "" }
else { $1 };
}gei unless $noentities;
$str=~s/[\x00-\x08\x0b\x0c\x0e-\x1f]//g; # remove control chars
return $str;
}
sub escamp($)
{
my ($str)=@_;
$str=~s/&/&/g;
return $str;
}
sub urlenc($)
{
my ($str)=@_;
$str=~s/([^\w ])/"%".sprintf("%02x",ord $1)/sge;
$str=~s/ /+/sg;
return $str;
}
sub clean_path($)
{
my ($str)=@_;
$str=~s!([^\w/._\-])!"%".sprintf("%02x",ord $1)!sge;
return $str;
}
#
# Javascript utilities
#
sub clean_to_js($)
{
my $str=shift;
$str=~s/&/\\x26/g;
$str=~s/</\\x3c/g;
$str=~s/>/\\x3e/g;
$str=~s/"/\\x22/g; #"
$str=~s/('|')/\\x27/g;
$str=~s/,/,/g;
$str=~s/&#[0-9]+;/sprintf "\\u%04x",$1/ge;
$str=~s/&#x[0-9a-f]+;/sprintf "\\u%04x",hex($1)/gie;
$str=~s/(\r\n|\r|\n)/\\n/g;
return "'$str'";
}
sub js_string($)
{
my $str=shift;
$str=~s/\\/\\\\/g;
$str=~s/'/\\'/g;
$str=~s/([\x00-\x1f\x80-\xff<>&])/sprintf "\\x%02x",ord($1)/ge;
eval '$str=~s/([\x{100}-\x{ffff}])/sprintf "\\u%04x",ord($1)/ge';
$str=~s/(\r\n|\r|\n)/\\n/g;
return "'$str'";
}
sub js_array(@)
{
return "[".(join ",",@_)."]";
}
sub js_hash(%)
{
my %hash=@_;
return "{".(join ",",map "'$_':$hash{$_}",keys %hash)."}";
}
#
# HTTP utilities
#
# LIGHTWEIGHT HTTP/1.1 CLIENT
# by fatalM4/coda, modified by WAHa.06x36
use constant CACHEFILE_PREFIX => 'cache-'; # you can make this a directory (e.g. 'cachedir/cache-' ) if you'd like
use constant FORCETIME => '0.04'; # If the cache is less than (FORCETIME) days old, don't even attempt to refresh.
# Saves everyone some bandwidth. 0.04 days is ~ 1 hour. 0.0007 days is ~ 1 min.
eval 'use IO::Socket::INET'; # Will fail on old Perl versions!
sub get_http($;$$$)
{
my ($url,$maxsize,$referer,$cacheprefix)=@_;
my ($host,$port,$doc)=$url=~m!^(?:https?://|)([^/]+)(:[0-9]+|)(.*)$!;
$port=80 unless($port);
my $hash=encode_base64(rc4(null_string(6),"$host:$port$doc",0),"");
$hash=~tr!/+!_-!; # remove / and +
my $cachefile=($cacheprefix or CACHEFILE_PREFIX).($doc=~m!([^/]{0,15})$!)[0]."-$hash"; # up to 15 chars of filename
my ($modified,$cache);
if(open CACHE,"<",$cachefile) # get modified date and cache contents
{
$modified=<CACHE>;
$cache=join "",<CACHE>;
chomp $modified;
close CACHE;
return $cache if((-M $cachefile)<FORCETIME);
}
my $sock=IO::Socket::INET->new("$host:$port") or return $cache;
print $sock "GET $doc HTTP/1.1\r\nHost: $host\r\nConnection: close\r\n";
print $sock "If-Modified-Since: $modified\r\n" if $modified;
print $sock "Referer: $referer\r\n" if $referer;
print $sock "\r\n"; #finished!
# header
my ($line,$statuscode,$lastmod);
do {
$line=<$sock>;
$statuscode=$1 if($line=~/^HTTP\/1\.1 (\d+)/);
$lastmod=$1 if($line=~/^Last-Modified: (.*)/);
} until ($line=~/^\r?\n/);
# body
my ($line,$output);
while($line=<$sock>)
{
$output.=$line;
last if $maxsize and $output>=$maxsize;
}
undef $sock;
if($statuscode=="200")
{
#navbar changed, update cache
if(open CACHE,">$cachefile")
{
print CACHE "$lastmod\n";
print CACHE $output;
close CACHE or die "close cache: $!";
}
return $output;
}
else # touch and return cache, or nothing if no cache
{
utime(time,time,$cachefile);
return $cache;
}
}
sub make_http_forward($;$)
{
my ($location,$alternate_method)=@_;
if($alternate_method)
{
print "Content-Type: text/html\n";
print "\n";
print "<html><head>";
print '<meta http-equiv="refresh" content="0; url='.$location.'" />';
print '<script type="text/javascript">document.location="'.$location.'";</script>';
print '</head><body><a href="'.$location.'">'.$location.'</a></body></html>';
}
else
{
print "Status: 303 Go West\n";
print "Location: $location\n";
print "Content-Type: text/html\n";
print "\n";
print '<html><body><a href="'.$location.'">'.$location.'</a></body></html>';
}
}
sub make_cookies(%)
{
my (%cookies)=@_;
my $charset=$cookies{'-charset'};
my $expires=($cookies{'-expires'} or time+14*24*3600);
my $autopath=$cookies{'-autopath'};
my $path=$cookies{'-path'};
my $date=make_date($expires,"cookie");
unless($path)
{
if($autopath eq 'current') { ($path)=$ENV{SCRIPT_NAME}=~m!^(.*/)[^/]+$! }
elsif($autopath eq 'parent') { ($path)=$ENV{SCRIPT_NAME}=~m!^(.*?/)(?:[^/]+/)?[^/]+$! }
else { $path='/'; }
}
foreach my $name (keys %cookies)
{
next if($name=~/^-/); # skip entries that start with a dash
my $value=$cookies{$name};
$value="" unless(defined $value);
$value=cookie_encode($value,$charset);
print "Set-Cookie: $name=$value; path=$path; expires=$date;\n";
}
}
sub cookie_encode($;$)
{
my ($str,$charset)=@_;
if($]>5.007) # new perl, use Encode.pm
{
if($charset)
{
#require Encode;
#$str=Encode::decode($charset,$str);
$str=~s/&\#([0-9]+);/chr $1/ge;
$str=~s/&\#x([0-9a-f]+);/chr hex $1/gei;
}
$str=~s/([^0-9a-zA-Z])/
my $c=ord $1;
sprintf($c>255?'%%u%04x':'%%%02x',$c);
/sge;
}
else # do the hard work ourselves
{
if($charset=~/\butf-?8$/i)
{
$str=~s{([\xe0-\xef][\x80-\xBF][\x80-\xBF]|[\xc0-\xdf][\x80-\xBF]|&#([0-9]+);|&#[xX]([0-9a-fA-F]+);|[^0-9a-zA-Z])}{ # convert UTF-8 to URL encoding - only handles up to U-FFFF
my $c;
if($2) { $c=$2 }
elsif($3) { $c=hex $3 }
elsif(length $1==1) { $c=ord $1 }
elsif(length $1==2)
{
my @b=map { ord $_ } split //,$1;
$c=(($b[0]-0xc0)<<6)+($b[1]-0x80);
}
elsif(length $1==3)
{
my @b=map { ord $_ } split //,$1;
$c=(($b[0]-0xe0)<<12)+(($b[1]-0x80)<<6)+($b[2]-0x80);
}
sprintf($c>255?'%%u%04x':'%%%02x',$c);
}sge;
}
elsif($charset=~/\b(?:shift.*jis|sjis)$/i) # old perl, using shift_jis
{
require 'sjis.pl';
my $sjis_table=get_sjis_table();
$str=~s{([\x80-\x9f\xe0-\xfc].|&#([0-9]+);|&#[xX]([0-9a-fA-F]+);|[^0-9a-zA-Z])}{ # convert Shift_JIS to URL encoding
my $c=($2 or ($3 and hex $3) or $$sjis_table{$1});
sprintf($c>255?'%%u%04x':'%%%02x',$c);
}sge;
}
else
{
$str=~s/([^0-9a-zA-Z])/sprintf('%%%02x',ord $1)/sge;
}
}
return $str;
}
sub get_xhtml_content_type(;$$)
{
my ($charset,$usexhtml)=@_;
my $type;
if($usexhtml and $ENV{HTTP_ACCEPT}=~/application\/xhtml\+xml/) { $type="application/xhtml+xml"; }
else { $type="text/html"; }
$type.="; charset=$charset" if($charset);
return $type;
}
sub expand_filename($)
{
my ($filename)=@_;
return $filename if($filename=~m!^/!);
return $filename if($filename=~m!^\w+:!);
my ($self_path)=$ENV{SCRIPT_NAME}=~m!^(.*/)[^/]+$!;
return $self_path.$filename;
}
#
# Network utilities
#
sub resolve_host($)
{
my $ip=shift;
return (gethostbyaddr inet_aton($ip),AF_INET or $ip);
}
#
# Data utilities
#
sub process_tripcode($;$$$$$)
{
my ($name,$tripkey,$secret,$charset,$nonamedecoding,$variant)=@_;
$tripkey="!" unless($tripkey);
if($name=~/^(.*?)((?<!&)#|\Q$tripkey\E)(.*)$/)
{
my ($namepart,$marker,$trippart)=($1,$2,$3);
my $trip;
$namepart=decode_string($namepart,$charset) unless $nonamedecoding;
$namepart=clean_string($namepart);
if($trippart && $variant){
return($namepart, $tripkey . trip_0ch($trippart)) if $variant == '0ch';
return($namepart, $tripkey . trip_futaba($trippart)) if $variant == 'futaba';
return($namepart, $tripkey . trip_futaba_utf8($trippart)) if $variant == 'futaba-utf8';
}
if($secret and $trippart=~s/(?:\Q$marker\E)(?<!&#)(?:\Q$marker\E)*(.*)$//) # do we want secure trips, and is there one?
{
my $str=$1;
my $maxlen=255-length($secret);
$str=substr $str,0,$maxlen if(length($str)>$maxlen);
# $trip=$tripkey.$tripkey.encode_base64(rc4(null_string(6),"t".$str.$secret),"");
$trip=$tripkey.$tripkey.hide_data($1,6,"trip",$secret,1);
return ($namepart,$trip) unless($trippart); # return directly if there's no normal tripcode
}
# 2ch trips are processed as Shift_JIS whenever possible
eval 'use Encode qw(decode encode)';
unless($@)
{
$trippart=decode_string($trippart,$charset);
$trippart=encode("Shift_JIS",$trippart,0x0200);
}
$trippart=clean_string($trippart);
my $salt=substr $trippart."H..",1,2;
$salt=~s/[^\.-z]/./g;
$salt=~tr/:;<=>?@[\\]^_`/ABCDEFGabcdef/;
$trip=$tripkey.(substr crypt($trippart,$salt),-10).$trip;
return ($namepart,$trip);
}
return clean_string($name) if $nonamedecoding;
return (clean_string(decode_string($name,$charset)),"");
}
sub trip_0ch($){
my ($cap) = @_;
return '' unless $cap;
$cap = encode("Shift_JIS", $cap);
$cap =~ s/\0//g;
$cap =~ s/"/"/g;
$cap =~ s/</</g;
$cap =~ s/>/>/g;
$cap =~ s/\r\n|\r|\n/<br>/g;
$cap =~ s/\x81\x9a/\x81\x99/g;
$cap =~ s/\x81\x9f/\x81\x9e/g;
$cap =~ s/\x8d\xed\x8f\x9c/\x81\x8d\xed\x8f\x9c\x81/g;
$cap =~ s/\x8a\xc7\x97\x9d/\x81\x8a\xc7\x97\x9d\x81/g;
$cap =~ s/\x8a\xc7\x92\xvc/\x81\x8a\xc7\x92\xbc\x81/g;
my $salt = substr $cap . 'H.', 1, 2;
$salt=~s/[^\.-z]/./g;
$salt=~tr/:;<=>?@[\\]^_`/ABCDEFGabcdef/;
return substr crypt($cap, $salt), -10;
}
sub trip_futaba($){
my ($cap) = @_;
$cap = encode("Shift_JIS", $cap);
$cap =~ s/[ \t\n\r\0\x0b]*$//;
$cap =~ s/"/"/g;
$cap =~ s/</</g;
$cap =~ s/>/>/g;
$cap =~ s/,/,/g;
$cap =~ s/&/,/g;
my $salt = substr $cap . 'H.G', 1, 2;
$salt=~s/[^\.-z]/./g;
$salt=~tr/:;<=>?@[\\]^_`/ABCDEFGabcdef/;
return substr crypt($cap, $salt), -10;
}
sub trip_futaba_utf8($){
my ($cap) = @_;
$cap = encode("UTF-8", $cap);
$cap =~ s/[ \t\n\r\0\x0b]*$//;
$cap =~ s/"/"/g;
$cap =~ s/</</g;
$cap =~ s/>/>/g;
$cap =~ s/,/,/g;
$cap =~ s/&/,/g;
my $salt = substr $cap . 'H.G', 1, 2;
$salt=~s/[^\.-z]/./g;
$salt=~tr/:;<=>?@[\\]^_`/ABCDEFGabcdef/;
return substr crypt($cap, $salt), -10;
}
sub make_date($$;@)
{
my ($time,$style,@locdays)=@_;
my @days=qw(Sun Mon Tue Wed Thu Fri Sat);
my @months=qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
@locdays=@days unless(@locdays);
if($style eq "2ch")
{
my @ltime=localtime($time);
return sprintf("%04d-%02d-%02d %02d:%02d",
$ltime[5]+1900,$ltime[4]+1,$ltime[3],$ltime[2],$ltime[1]);
}
elsif($style eq "futaba" or $style eq "0")
{
my @ltime=localtime($time);
return sprintf("%02d/%02d/%02d(%s)%02d:%02d",
$ltime[5]-100,$ltime[4]+1,$ltime[3],$locdays[$ltime[6]],$ltime[2],$ltime[1]);
}
elsif($style eq "localtime")
{
return scalar(localtime($time));
}
elsif($style eq "tiny")
{
my @ltime=localtime($time);
return sprintf("%02d/%02d %02d:%02d",
$ltime[4]+1,$ltime[3],$ltime[2],$ltime[1]);
}
elsif($style eq "http")
{
my ($sec,$min,$hour,$mday,$mon,$year,$wday)=gmtime($time);
return sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT",
$days[$wday],$mday,$months[$mon],$year+1900,$hour,$min,$sec);
}
elsif($style eq "cookie")
{
my ($sec,$min,$hour,$mday,$mon,$year,$wday)=gmtime($time);
return sprintf("%s, %02d-%s-%04d %02d:%02d:%02d GMT",
$days[$wday],$mday,$months[$mon],$year+1900,$hour,$min,$sec);
}
elsif($style eq "month")
{
my ($sec,$min,$hour,$mday,$mon,$year,$wday)=gmtime($time);
return sprintf("%s %d",
$months[$mon],$year+1900);
}
elsif($style eq "atomnow")
{
my ($sec,$min,$hour,$mday,$mon,$year,$wday)=gmtime();
return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ",
$year+1900,$mon+1,$mday,$hour,$min,$sec);
}
elsif($style eq "atom")
{
my ($sec,$min,$hour,$mday,$mon,$year,$wday)=gmtime($time);
return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ",
$year+1900,$mon+1,$mday,$hour,$min,$sec);
}
elsif($style eq "swatch")
{
my $current_time = gmtime();
my $cet_time = $current_time + ONE_HOUR; # Adding 1 hour to get CET offset
my $date_string = $cet_time->strftime("d%d.%m.%y");
my $beats = int($cet_time->second + $cet_time->minute * 60 + $cet_time->hour * 3600) / 86.4;
my $fraction = sprintf("%02d", int(($beats - int($beats)) * 100));
$beats = int($beats);
my $time_string = sprintf("@%03d.%s", $beats, $fraction);
return "$date_string $time_string .beats";
}
elsif($style eq "2ch-sep93")
{
my $sep93=timelocal(0,0,0,1,8,93);
return make_date($time,"2ch") if($time<$sep93);
my @ltime=localtime($time);
return sprintf("%04d-%02d-%02d %02d:%02d",
1993,9,int ($time-$sep93)/86400+1,$ltime[2],$ltime[1]);
}
}
sub parse_http_date($)
{
my ($date)=@_;
my %months=(Jan=>0,Feb=>1,Mar=>2,Apr=>3,May=>4,Jun=>5,Jul=>6,Aug=>7,Sep=>8,Oct=>9,Nov=>10,Dec=>11);
if($date=~/^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) (\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$/)
{ return eval { timegm($6,$5,$4,$1,$months{$2},$3-1900) } }
return undef;
}
sub cfg_expand($%)
{
my ($str,%grammar)=@_;
$str=~s/%(\w+)%/
my @expansions=@{$grammar{$1}};
cfg_expand($expansions[rand @expansions],%grammar);
/ge;
return $str;
}
sub encode_base64($;$) # stolen from MIME::Base64::Perl
{
my ($data,$eol)=@_;
$eol="\n" unless(defined $eol);
my $res=pack "u",$data;
$res=~s/^.//mg; # remove length counts
$res=~s/\n//g; # remove newlines
$res=~tr|` -_|AA-Za-z0-9+/|; # translate to base64
my $padding=(3-length($data)%3)%3; # fix padding at the end
$res=~s/.{$padding}$/'='x$padding/e if($padding);
$res=~s/(.{1,76})/$1$eol/g if(length $eol); # break encoded string into lines of no more than 76 characters each
return $res;
}
sub decode_base64($) # stolen from MIME::Base64::Perl
{
my ($str)=@_;
$str=~tr|A-Za-z0-9+=/||cd; # remove non-base64 characters
$str=~s/=+$//; # remove padding
$str=~tr|A-Za-z0-9+/| -_|; # translate to uuencode
return "" unless(length $str);
return unpack "u",join '',map { chr(32+length($_)*3/4).$_ } $str=~/(.{1,60})/gs;
}
sub dot_to_dec($)
{
return unpack('N',pack('C4',split(/\./, $_[0]))); # wow, magic.
}
sub dec_to_dot($)
{
return join('.',unpack('C4',pack('N',$_[0])));
}
sub mask_ip($$;$)
{
my ($ip,$key,$algorithm)=@_;
$ip=dot_to_dec($ip) if $ip=~/\./;
my ($block,$stir)=setup_masking($key,$algorithm);
my $mask=0x80000000;
for(1..32)
{
my $bit=$ip&$mask?"1":"0";
$block=$stir->($block);
$ip^=$mask if(ord($block)&0x80);
$block=$bit.$block;
$mask>>=1;
}
return sprintf "%08x",$ip;
}
sub unmask_ip($$;$)
{
my ($id,$key,$algorithm)=@_;
$id=hex($id);
my ($block,$stir)=setup_masking($key,$algorithm);
my $mask=0x80000000;
for(1..32)
{
$block=$stir->($block);
$id^=$mask if(ord($block)&0x80);