Debian Codegraph @

src/.svn/text-base/utils.pl.svn-base

raw
1 #BSD Copyright (c) 2009, Jeff Forristal (wiretrip.net)
2 #BSD All rights reserved.
3 #BSD
4 #BSD Redistribution and use in source and binary forms, with or without
5 #BSD modification, are permitted provided that the following conditions
6 #BSD are met:
7 #BSD
8 #BSD - Redistributions of source code must retain the above copyright
9 #BSD notice, this list of conditions and the following disclaimer.
10 #BSD
11 #BSD - Redistributions in binary form must reproduce the above copyright
12 #BSD notice, this list of conditions and the following disclaimer in the
13 #BSD documentation and/or other materials provided with the distribution.
14 #BSD
15 #BSD THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 #BSD "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 #BSD LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 #BSD FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 #BSD COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 #BSD INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 #BSD BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 #BSD LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 #BSD CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 #BSD LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
25 #BSD ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 #BSD POSSIBILITY OF SUCH DAMAGE.
27
28 ########################################################################
29
30 =item B<utils_recperm>
31
32 Params: $uri, $depth, \@dir_parts, \@valid, \&func, \%track, \%arrays, \&cfunc
33
34 Return: nothing
35
36 This is a special function which is used to recursively-permutate through
37 a given directory listing. This is really only used by whisker, in order
38 to traverse down directories, testing them as it goes. See whisker 2.0 for
39 exact usage examples.
40
41 =cut
42
43 # '/', 0, \@dir.split, \@valid, \&func, \%track, \%arrays, \&cfunc
44 sub utils_recperm {
45 my ( $d, $p, $pp, $pn, $r, $fr, $dr, $ar, $cr ) = ( '', shift, shift, @_ );
46 $p =~ s#/+#/#g;
47 if ( $pp >= @$pn ) {
48 push @$r, $p if &$cr( $$dr{$p} );
49 }
50 else {
51 my $c = $$pn[$pp];
52 if ( $c !~ /^\@/ ) {
53 utils_recperm( $p . $c . '/', $pp + 1, @_ )
54 if ( &$fr( $p . $c . '/' ) );
55 }
56 else {
57 $c =~ tr/\@//d;
58 if ( defined $$ar{$c} ) {
59 foreach $d ( @{ $$ar{$c} } ) {
60 if ( &$fr( $p . $d . '/' ) ) {
61 utils_recperm( $p . $d . '/', $pp + 1, @_ );
62 }
63 }
64 }
65 }
66 }
67 }
68
69 #################################################################
70
71 =item B<utils_array_shuffle>
72
73 Params: \@array
74
75 Return: nothing
76
77 This function will randomize the order of the elements in the given array.
78
79 =cut
80
81 sub utils_array_shuffle { # fisher yates shuffle....w00p!
82 my $array = shift;
83 my $i;
84 for ( $i = @$array ; --$i ; ) {
85 my $j = int rand( $i + 1 );
86 next if $i == $j;
87 @$array[ $i, $j ] = @$array[ $j, $i ];
88 }
89 } # end array_shuffle, from Perl Cookbook (rock!)
90
91 #################################################################
92
93 =item B<utils_randstr>
94
95 Params: [ $size, $chars ]
96
97 Return: $random_string
98
99 This function generates a random string between 10 and 20 characters
100 long, or of $size if specified. If $chars is specified, then the
101 random function picks characters from the supplied string. For example,
102 to have a random string of 10 characters, composed of only the characters
103 'abcdef', then you would run:
104
105 utils_randstr(10,'abcdef');
106
107 The default character string is alphanumeric.
108
109 =cut
110
111 sub utils_randstr {
112 my $str;
113 my $drift = shift || ( ( rand() * 10 ) % 10 ) + 10;
114
115 # 'a'..'z' doesn't seem to work on string assignment :(
116 my $CHARS = shift
117 || 'abcdefghijklmnopqrstuvwxyz'
118 . 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
119 . '0123456789';
120
121 my $L = length($CHARS);
122 for ( 1 .. $drift ) {
123 $str .= substr( $CHARS, ( ( rand() * $L ) % $L ), 1 );
124 }
125 return $str;
126 }
127
128 #################################################################
129
130 =item B<utils_port_open>
131
132 Params: $host, $port
133
134 Return: $result
135
136 Quick function to attempt to make a connection to the given host and
137 port. If a connection was successfully made, function will return true
138 (1). Otherwise it returns false (0).
139
140 Note: this uses standard TCP connections, thus is not recommended for use
141 in port-scanning type applications. Extremely slow.
142
143 =cut
144
145 sub utils_port_open { # this should be platform-safe
146 my ( $target, $port ) = @_;
147
148 return 0 if ( !defined $target || !defined $port );
149 return 0 if ( !defined $Socket::VERSION );
150
151 if ( !( socket( S, PF_INET, SOCK_STREAM, 0 ) ) ) { return 0; }
152 if ( connect( S, sockaddr_in( $port, inet_aton($target) ) ) ) {
153 close(S);
154 return 1;
155 }
156 else { return 0; }
157 }
158
159 #################################################################
160
161 =item B<utils_lowercase_keys>
162
163 Params: \%hash
164
165 Return: $number_changed
166
167 Will lowercase all the header names (but not values) of the given hash.
168
169 =cut
170
171 sub utils_lowercase_keys {
172 my $href = shift;
173
174 return if ( !( defined $href && ref($href) ) );
175
176 my $count = 0;
177 while ( my ( $key, $val ) = each %$href ) {
178 if ( $key =~ tr/A-Z// ) {
179 $count++;
180 delete $$href{$key};
181 $$href{ lc($key) } = $val;
182 }
183 }
184 return $count;
185 }
186
187 #################################################################
188
189 =item B<utils_find_lowercase_key>
190
191 Params: \%hash, $key
192
193 Return: $value, undef on error or not exist
194
195 Searches the given hash for the $key (regardless of case), and
196 returns the value. If the return value is placed into an array, the
197 will dereference any multi-value references and return an array of
198 all values.
199
200 WARNING! In scalar context, $value can either be a single-value
201 scalar or an array reference for multiple scalar values. That means
202 you either need to check the return value and act appropriately, or
203 use an array context (even if you only want a single value). This is
204 very important, even if you know there are no multi-value hash keys.
205 This function may still return an array of multiple values even if
206 all hash keys are single value, since lowercasing the keys could result
207 in multiple keys matching. For example, a hash with the values
208 { 'Foo'=>'a', 'fOo'=>'b' } technically has two keys with the lowercase
209 name 'foo', and so this function will either return an array or array
210 reference with both 'a' and 'b'.
211
212 =cut
213
214 sub utils_find_lowercase_key {
215 return utils_find_key( $_[0], $_[1], 1 );
216 }
217
218 #################################################################
219
220 =item B<utils_find_key>
221
222 Params: \%hash, $key
223
224 Return: $value, undef on error or not exist
225
226 Searches the given hash for the $key (case-sensitive), and
227 returns the value. If the return value is placed into an array, the
228 will dereference any multi-value references and return an array of
229 all values.
230
231 =cut
232
233 sub utils_find_key {
234 my ( $href, $key, $dolower ) = ( shift, shift, shift || 0 );
235
236 return undef if ( !( defined $href && ref($href) ) );
237 return undef if ( !defined $key );
238
239 if ($dolower) {
240 $key = lc($key);
241 my ( $k, $v );
242 my @match;
243 while ( ( $k, $v ) = each %$href ) {
244 if ( lc($k) eq $key ) {
245 if( ref($v) ) {
246 push @match, @$v;
247 } else {
248 push @match, $v;
249 }
250 }
251 }
252 return @match if wantarray();
253 return \@match if( ~~@match > 1 );
254 return $match[0];
255 }
256 else {
257 return @{ $href->{$key} } if ( ref( $href->{$key} ) && wantarray() );
258 return $href->{$key};
259 }
260 return undef;
261 }
262
263 #################################################################
264
265 =item B<utils_delete_lowercase_key>
266
267 Params: \%hash, $key
268
269 Return: $number_found
270
271 Searches the given hash for the $key (regardless of case), and
272 deletes the key out of the hash if found. The function returns
273 the number of keys found and deleted (since multiple keys can
274 exist under the names 'Key', 'key', 'keY', 'KEY', etc.).
275
276 =cut
277
278 sub utils_delete_lowercase_key {
279 my ( $href, $key ) = ( shift, lc(shift) );
280
281 return undef if ( !( defined $href && ref($href) ) );
282 return undef if ( !defined $key );
283
284 my $deleted = 0;
285 foreach ( keys %$href ) {
286 if ( lc($_) eq $key ) {
287 delete $href->{$_};
288 $deleted++;
289 }
290 }
291 return $deleted;
292 }
293
294 #################################################################
295
296 =item B<utils_getline>
297
298 Params: \$data [, $resetpos ]
299
300 Return: $line (undef if no more data)
301
302 Fetches the next \n terminated line from the given data. Use
303 the optional $resetpos to reset the internal position pointer.
304 Does *NOT* return trialing \n.
305
306 =cut
307
308 {
309 my $POS = 0;
310
311 sub utils_getline {
312 my ( $dr, $rp ) = @_;
313
314 return undef if ( !( defined $dr && ref($dr) ) );
315 $POS = $rp if ( defined $rp );
316
317 my $where = index( $$dr, "\x0a", $POS );
318 return undef if ( $where == -1 );
319
320 my $str = substr( $$dr, $POS, $where - $POS );
321 $POS = $where + 1;
322
323 return $str;
324 }
325 }
326
327 #################################################################
328
329 =item B<utils_getline_crlf>
330
331 Params: \$data [, $resetpos ]
332
333 Return: $line (undef if no more data)
334
335 Fetches the next \r\n terminated line from the given data. Use
336 the optional $resetpos to reset the internal position pointer.
337 Does *NOT* return trialing \r\n.
338
339 =cut
340
341 {
342 my $POS = 0;
343
344 sub utils_getline_crlf {
345 my ( $dr, $rp ) = @_;
346
347 return undef if ( !( defined $dr && ref($dr) ) );
348 $POS = $rp if ( defined $rp );
349
350 my $tpos = $POS;
351 while (1) {
352 my $where = index( $$dr, "\x0a", $tpos );
353 return undef if ( $where == -1 );
354
355 if ( substr( $$dr, $where - 1, 1 ) eq "\x0d" ) {
356 my $str = substr( $$dr, $POS, $where - $POS - 1 );
357 $POS = $where + 1;
358 return $str;
359 }
360 else {
361 $tpos = $where + 1;
362 }
363 }
364 }
365 }
366
367 #################################################################
368
369 =item B<utils_save_page>
370
371 Params: $file, \%response
372
373 Return: 0 on success, 1 on error
374
375 Saves the data portion of the given whisker %response hash to the
376 indicated file. Can technically save the data portion of a
377 %request hash too. A file is not written if there is no data.
378
379 Note: LW does not do any special file checking; files are opened
380 in overwrite mode.
381
382 =cut
383
384 sub utils_save_page {
385 my ( $file, $hr ) = @_;
386 return 1 if ( !ref($hr) || ref($file) );
387 return 0
388 if ( !defined $$hr{'whisker'}
389 || !defined $$hr{'whisker'}->{'data'} );
390 open( OUT, ">$file" ) || return 1;
391 binmode(OUT); # Stupid Windows
392 print OUT $$hr{'whisker'}->{'data'};
393 close(OUT);
394 return 0;
395 }
396
397 #################################################################
398
399 =item B<utils_getopts>
400
401 Params: $opt_str, \%opt_results
402
403 Return: 0 on success, 1 on error
404
405 This function is a general implementation of GetOpts::Std. It will
406 parse @ARGV, looking for the options specified in $opt_str, and will
407 put the results in %opt_results. Behavior/parameter values are
408 similar to GetOpts::Std's getopts().
409
410 Note: this function does *not* support long options (--option),
411 option grouping (-opq), or options with immediate values (-ovalue).
412 If an option is indicated as having a value, it will take the next
413 argument regardless.
414
415 =cut
416
417 sub utils_getopts {
418 my ( $str, $ref ) = @_;
419 my ( %O, $l );
420 my @left;
421
422 return 1 if ( $str =~ tr/-:a-zA-Z0-9//c );
423
424 while ( $str =~ m/([a-z0-9]:{0,1})/ig ) {
425 $l = $1;
426 if ( $l =~ tr/://d ) {
427 $O{$l} = 1;
428 }
429 else { $O{$l} = 0; }
430 }
431
432 while ( $l = shift(@ARGV) ) {
433 push( @left, $l ) && next if ( substr( $l, 0, 1 ) ne '-' );
434 push( @left, $l ) && next if ( $l eq '-' );
435 substr( $l, 0, 1 ) = '';
436 if ( length($l) != 1 ) {
437 %$ref = ();
438 return 1;
439 }
440 if ( $O{$l} == 1 ) {
441 my $x = shift(@ARGV);
442 $$ref{$l} = $x;
443 }
444 else { $$ref{$l} = 1; }
445 }
446
447 @ARGV = @left;
448 return 0;
449 }
450
451 #################################################################
452
453 =item B<utils_text_wrapper>
454
455 Params: $long_text_string [, $crlf, $width ]
456
457 Return: $formatted_test_string
458
459 This is a simple function used to format a long line of text for
460 display on a typical limited-character screen, such as a unix
461 shell console.
462
463 $crlf defaults to "\n", and $width defaults to 76.
464
465 =cut
466
467 sub utils_text_wrapper {
468 my ( $out, $w, $str, $crlf, $width ) = ( '', 0, @_ );
469 $crlf ||= "\n";
470 $width ||= 76;
471 $str .= $crlf if ( $str !~ /$crlf$/ );
472 return $str if ( length($str) <= $width );
473 while ( length($str) > $width ) {
474 my $w1 = rindex( $str, ' ', $width );
475 my $w2 = rindex( $str, "\t", $width );
476 if ( $w1 > $w2 ) { $w = $w1; }
477 else { $w = $w2; }
478 if ( $w == -1 ) {
479 $w = $width;
480 }
481 else { substr( $str, $w, 1 ) = ''; }
482 $out .= substr( $str, 0, $w, '' );
483 $out .= $crlf;
484 }
485 return $out . $str;
486 }
487
488 #################################################################
489
490 =item B<utils_bruteurl>
491
492 Params: \%req, $pre, $post, \@values_in, \@values_out
493
494 Return: Nothing (adds to @out)
495
496 Bruteurl will perform a brute force against the host/server specified in
497 %req. However, it will make one request per entry in @in, taking the
498 value and setting $hin{'whisker'}->{'uri'}= $pre.value.$post. Any URI
499 responding with an HTTP 200 or 403 response is pushed into @out. An
500 example of this would be to brute force usernames, putting a list of
501 common usernames in @in, setting $pre='/~' and $post='/'.
502
503 =cut
504
505 sub utils_bruteurl {
506 my ( $hin, $upre, $upost, $arin, $arout ) = @_;
507 my ( $U, %hout );
508
509 return if ( !( defined $hin && ref($hin) ) );
510 return if ( !( defined $arin && ref($arin) ) );
511 return if ( !( defined $arout && ref($arout) ) );
512 return if ( !defined $upre || length($upre) == 0 );
513 return if ( !defined $upost || length($upost) == 0 );
514
515 http_fixup_request($hin);
516
517 map {
518 ( $U = $_ ) =~ tr/\r\n//d;
519 next if ( $U eq '' );
520 if (
521 !http_do_request( $hin, \%hout, { 'uri' => $upre . $U . $upost } ) )
522 {
523 if ( $hout{'whisker'}->{'code'} == 200
524 || $hout{'whisker'}->{'code'} == 403 )
525 {
526 push( @{$arout}, $U );
527 }
528 }
529 } @$arin;
530 }
531
532 #################################################################
533
534 =item B<utils_join_tag>
535
536 Params: $tag_name, \%attributes
537
538 Return: $tag_string [undef on error]
539
540 This function takes the $tag_name (like 'A') and a hash full of
541 attributes (like {href=>'http://foo/'}) and returns the
542 constructed HTML tag string (<A href="http://foo">).
543
544 =cut
545
546 sub utils_join_tag {
547 my ( $name, $href ) = @_;
548 return undef if ( !defined $name || $name eq '' );
549 return undef if ( !defined $href || !ref($href) );
550 my ( $out, $k, $v ) = ( "<$name", '', '' );
551 while ( ( $k, $v ) = each %$href ) {
552 next if ( $k eq '' );
553 $out .= " $k";
554 $out .= "=\"$v\"" if ( defined $v );
555 }
556 $out .= '>';
557 return $out;
558 }
559
560 #################################################################
561
562 =item B<utils_request_clone>
563
564 Params: \%from_request, \%to_request
565
566 Return: 1 on success, 0 on error
567
568 This function takes the connection/request-specific values from the
569 given from_request hash, and copies them to the to_request hash.
570
571 =cut
572
573 sub utils_request_clone {
574 my ( $from, $to ) = @_;
575 return 0 if ( !defined $from || !ref($from) );
576 return 0 if ( !defined $to || !ref($to) );
577 return 0 if ( !defined $from->{whisker}->{MAGIC} );
578
579 %$to = ();
580
581 # copy headers
582 my ( $k, $v );
583 while ( ( $k, $v ) = each(%$from) ) {
584 next if ( $k eq 'whisker' );
585 if ( ref($v) ) {
586 @{ $to->{$k} } = @$v;
587 }
588 else {
589 $to->{$k} = $v;
590 }
591 }
592
593 # copy whisker control values
594 $to->{whisker} = {};
595 while ( ( $k, $v ) = each( %{ $from->{whisker} } ) ) {
596 if ( ref($v) ) {
597 @{ $to->{whisker}->{$k} } = @$v;
598 }
599 else {
600 $to->{whisker}->{$k} = $v;
601 }
602 }
603
604 return 1;
605 }
606
607 #################################################################
608
609 =item B<utils_request_fingerprint>
610
611 Params: \%request [, $hash ]
612
613 Return: $fingerprint [undef on error]
614
615 This function constructs a 'fingerprint' of the given request by
616 using a cryptographic hashing function on the constructed original
617 HTTP request.
618
619 Note: $hash can be 'md5' (default) or 'md4'.
620
621 =cut
622
623 sub utils_request_fingerprint {
624 my ( $href, $hash ) = @_;
625 $hash ||= 'md5';
626 return undef if ( !defined $href || !ref($href) );
627 return undef if ( !defined $href->{whisker}->{MAGIC} );
628
629 my $data = '';
630 if ( $href->{whisker}->{MAGIC} == 31339 ) { # LW2 request
631 $data = http_req2line($href);
632 if ( $href->{whisker}->{version} ne '0.9' ) {
633 $data .= http_construct_headers($href);
634 $data .= $href->{whisker}->{raw_header_data}
635 if ( defined $href->{whisker}->{raw_header_data} );
636 $data .= $href->{whisker}->{http_eol};
637 $data .= $href->{whisker}->{data}
638 if ( defined $href->{whisker}->{data} );
639 } # http 0.9 support
640
641 return 'md5:' . md5($data) if ( $hash eq 'md5' );
642 return 'md4:' . md4($data) if ( $hash eq 'md4' );
643 }
644
645 return undef;
646 }
647
648 #################################################################
649
650 =item B<utils_flatten_lwhash>
651
652 Params: \%lwhash
653
654 Return: $flat_version [undef on error]
655
656 This function takes a %request or %response libwhisker hash, and
657 creates an approximate flat data string of the original request/
658 response (i.e. before it was parsed into components and placed
659 into the libwhisker hash).
660
661 =cut
662
663 sub utils_flatten_lwhash {
664 my $hr = shift;
665 return undef if ( !defined $hr || !ref($hr) );
666 my $out;
667
668 if ( $hr->{whisker}->{MAGIC} == 31339 ) {
669 $out = http_req2line($hr);
670 }
671 elsif ( $hr->{whisker}->{MAGIC} == 31340 ) {
672 $out = http_resp2line($hr);
673 }
674 else {
675 return undef;
676 }
677
678 $out .= http_construct_headers($hr);
679 $out .= $hr->{whisker}->{http_eol} || "\x0d\x0a";
680 if ( defined $hr->{whisker}->{data}
681 && length( $hr->{whisker}->{data} ) > 0 )
682 {
683 $out .= $hr->{whisker}->{data};
684 }
685
686 return $out;
687 }
688
689 #################################################################
690
691 sub _utils_carp_common {
692 my ($x,$pack,$m) = (0, shift || '',join('',@_) || '(Unknown error)');
693 my @s = caller($x++);
694 @s=caller($x++) while(defined $s[0] && ($s[0] eq 'LW2' || $s[0] eq $pack));
695 return $m if !defined $s[0];
696 return "$m at $s[1] line $s[2]\n";
697 }
698
699 =item B<utils_carp>
700
701 Params: [ $package_name ]
702
703 Return: nothing
704
705 This function acts like Carp's carp function. It warn's with the file and
706 line number of user's code which causes a problem. It traces up the call
707 stack and reports the first function that is not in the LW2 or optional
708 $package_name package package.
709
710 =cut
711
712 sub utils_carp {
713 warn _utils_carp_common(@_);
714 }
715
716 =item B<utils_croak>
717
718 Params: [ $package_name ]
719
720 Return: nothing
721
722 This function acts like Carp's croak function. It die's with the file and
723 line number of user's code which causes a problem. It traces up the call
724 stack and reports the first function that is not in the LW2 or optional
725 $package_name package package.
726
727 =cut
728
729 sub utils_croak {
730 die _utils_carp_common(@_);
731 }