This file is indexed.

/usr/share/perl5/Paranoid/Input.pm is in libparanoid-perl 0.34-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
# Paranoid::Input -- Paranoid input functions
#
# (c) 2005, Arthur Corliss <corliss@digitalmages.com>
#
# $Id: Input.pm,v 0.20 2011/04/13 22:01:43 acorliss Exp $
#
#    This software is licensed under the same terms as Perl, itself.
#    Please see http://dev.perl.org/licenses/ for more information.
#
#####################################################################

#####################################################################
#
# Environment definitions
#
#####################################################################

package Paranoid::Input;

use 5.006;

use strict;
use warnings;
use vars qw($VERSION @EXPORT @EXPORT_OK %EXPORT_TAGS);
use base qw(Exporter);
use Fcntl qw(:flock :seek O_RDONLY);
use Paranoid;
use Paranoid::Debug qw(:all);
use Carp;

($VERSION) = ( q$Revision: 0.20 $ =~ /(\d+(?:\.(\d+))+)/sm );

@EXPORT = qw(FSZLIMIT LNSZLIMIT slurp sip tail closeFile
    detaint stringMatch);
@EXPORT_OK = qw(FSZLIMIT LNSZLIMIT slurp sip tail closeFile
    detaint stringMatch addTaintRegex);
%EXPORT_TAGS = (
    all => [
        qw(FSZLIMIT LNSZLIMIT slurp sip tail closeFile
            detaint stringMatch addTaintRegex)
        ],
        );

use constant STAT_INO  => 1;
use constant STAT_SIZE => 7;
use constant DEF_FSIZE => 16 * 1024;
use constant DEF_LSIZE => 2 * 1024;
use constant RV_LSZERR => -1;

#####################################################################
#
# Module code follows
#
#####################################################################

{
    my $fszlimit = DEF_FSIZE;

    sub FSZLIMIT : lvalue {

        # Purpose:  Gets/sets $fszlimit
        # Returns:  $fszlimit
        # Usage:    $limit = FSZLIMIT;
        # Usage:    FSZLIMIT = 100;

        $fszlimit;
    }

    my $lnszlimit = DEF_LSIZE;

    sub LNSZLIMIT : lvalue {

        # Purpose:  Gets/sets $lnszlimit
        # Returns:  $lnszlimit
        # Usage:    $limit = LNSZLIMIT;
        # Usage:    LNSZLIMIT = 100;

        $lnszlimit;
    }
}

sub slurp ($$;$) {

    # Purpose:  Reads a file into memory provided it doesn't exceed FSZLIMIT
    #           in size.  Automatically splits it into lines, but optionally
    #           chomps them as well.
    # Returns:  True (1) if the file was successfully read,
    #           False (0) if there are any errors
    # Usage:    $rv = slurp($filename, \@lines);
    # Usage:    $rv = slurp($filename, \@lines, 1);

    my $file    = shift;
    my $aref    = shift;
    my $doChomp = shift || 0;
    my $rv      = 0;
    my ( $fd, $b, $line, @lines );

    # Validate arguments
    croak 'Mandatory first argument must be a defined filename'
        unless defined $file;
    croak 'Mandatory second argument must be an array reference'
        unless defined $aref && ref $aref eq 'ARRAY';

    pdebug( "entering w/($file)($aref)($doChomp)", PDLEVEL1 );
    pIn();
    @$aref = ();

    # Validate file and exit early, if need be
    unless ( -e $file && -r _ ) {
        if ( !-e _ ) {
            Paranoid::ERROR =
                pdebug( "file ($file) does not exist", PDLEVEL1 );
        } else {
            Paranoid::ERROR =
                pdebug( "file ($file) is not readable by the effective user",
                PDLEVEL1 );
        }
        pOut();
        pdebug( "leaving w/rv: $rv", PDLEVEL1 );
        return 0;
    }
    unless ( detaint( $file, 'filename', \$b ) ) {
        Paranoid::ERROR =
            pdebug( "failed to detaint filename: $file", PDLEVEL1 );
        pOut();
        pdebug( "leaving w/rv: $rv", PDLEVEL1 );
        return 0;
    }

    # Read the file
    @$aref = ();
    if ( open $fd, '<', $file ) {
        flock $fd, LOCK_SH;
        $b = read $fd, $line, FSZLIMIT() + 1;
        flock $fd, LOCK_UN;
        close $fd;

        # Process what was read
        if ( defined $b ) {
            if ( $b > 0 ) {
                if ( $b > FSZLIMIT ) {
                    Paranoid::ERROR = pdebug(
                        "file '$file' is larger than " . FSZLIMIT . ' bytes',
                        PDLEVEL1
                        );
                } else {
                    $rv = 1;
                }
                while ( length $line > 0 ) {
                    $line       =~ /\n/sm
                        ? $line =~ s/^(.*?\n)//sm
                        : $line =~ s/(.*)//sm;
                    push @lines, $1;
                }
            }
        } else {
            Paranoid::ERROR =
                pdebug( "error reading file ($file): $!", PDLEVEL1 );
        }
        pdebug( "read @{[ scalar @lines ]} lines.", PDLEVEL1 );

        # Chomp lines
        do {
            foreach (@lines) {s/\r?\n$//sm}
        } if $doChomp;

        # Populate $aref with results
        @$aref = @lines;

    } else {
        Paranoid::ERROR =
            pdebug( "error opening file ($file): $!", PDLEVEL1 );
    }

    pOut();
    pdebug( "leaving w/rv: $rv", PDLEVEL1 );

    return $rv;
}

{
    my %fhandles;    # Hash of filenames => filedescriptors
    my %fpids;       # Hash of filenames => opening PIDs
    my %fstat;       # Hash of filenames => [ stat info ]
    my %buffers;     # Hash of strings, keyed by filename

    sub closeFile {

        # Purpose:  closes any opened filehandles and cleans up the internal
        #           data structures
        # Returns:  Result of close(), or True (1) if no such file opened
        # Usage:    $rv = closeFile($filename);

        my $filename = shift;
        my $rv       = 1;

        croak 'Mandatory first argument must be a defined filename'
            unless defined $filename;

        pdebug( "entering w/($filename)", PDLEVEL1 );
        pIn();

        if ( exists $fhandles{$filename} ) {
            $rv = close $fhandles{$filename};
            delete $fhandles{$filename};
            delete $fpids{$filename};
            delete $fstat{$filename};
            delete $buffers{$filename};
        }

        pOut();
        pdebug( "leaving w/rv: $rv", PDLEVEL1 );

        return $rv;
    }

    sub _getHandle {

        # Purpose:  This is a unified function that serves retrieval of file
        #           handles for both sip & tail.  For both, it pays attention
        #           to whether the file was opened before a fork, and if so,
        #           closes the file handle in the child and reopens it, albeit
        #           at the same position.
        #
        #           Invocation differs between sip & tail, however.  For sip
        #           all it needs is the filename.  For tail it expects one or
        #           two more arguments.  The first boolean argument tells the
        #           function that it's being called in tail mode, and should
        #           seek to the end of the file on file opens.  The second
        #           argument is an optional offset to back up from the EOF on
        #           new opens.
        #
        #           Finally, tail mode also keeps track of the file stat
        #           information on each call.  It uses that to detect when
        #           either the file is truncated or moved so that we can
        #           reopen the filehandle and continue tailing.  This is
        #           useful in situations such as in log rotation.
        # Returns:  Filehandle
        # Usage:    $fh = _getHandle($filename);
        # Usage:    $fh = _getHandle($filename, 1, -25);

        my $filename = shift;
        my $seekEOF  = shift;
        my $offset   = shift || 0;
        my ( $f, $fd, $rv, @fstat, $bpos, $buffer );

        # Is there a filehandle cached?
        if ( exists $fhandles{$filename} ) {

            # Yes, so was it opened by us?
            if ( $fpids{$filename} == $$ ) {

                if ($seekEOF) {

                    # In tail mode let's stat the file handle
                    $fstat{$filename} = [ stat $fhandles{$filename} ];
                    $bpos = tell $fhandles{$filename};

                    if ( $bpos < $fstat{$filename}[STAT_SIZE] ) {

                        # shortcut:  if the file size is greater than
                        #            current position we know we still have
                        #            content to read, so continue as normal
                        $rv = $fhandles{$filename};

                    } else {

                        # See what's currently on the filesystem answering to
                        # this filename
                        @fstat = stat $filename;

                        if ( @fstat == 0 ) {

                            # OMG -- they killed Kenny!  You bastards!
                            Paranoid::ERROR =
                                pdebug( "$filename has been deleted",
                                PDLEVEL3 );
                            $rv = undef;

                        } elsif (
                            $fstat[STAT_INO] != $fstat{$filename}[STAT_INO]
                            or
                            ( $fstat[STAT_INO] == $fstat{$filename}[STAT_INO]
                                and $bpos > $fstat{$filename}[STAT_SIZE] )
                            ) {

                            # The file was truncated, moved, or replaced.
                            # Either way, we need to reopen the file
                            # from the beginning
                            pdebug(
                                "$filename has been truncated, moved, "
                                    . 'or replaced -- reopening',
                                PDLEVEL3
                                );
                            closeFile($filename);
                            $rv = _getHandle($filename);

                        } else {

                            # When all else fails, give them the filehandle on
                            # file...
                            $rv = $fhandles{$filename};
                        }
                    }
                } else {

                    # Sip mode
                    $rv = $fhandles{$filename};
                }

            } else {

                pdebug( "reopening $filename", PDLEVEL3 );
                $bpos = tell $fhandles{$filename};
                $buffer = $buffers{$filename} if exists $buffers{$filename};
                closeFile($filename);
                $rv = _getHandle($filename);
                seek $rv, $bpos, SEEK_SET;
                $buffers{$filename} = $buffer if defined $buffer;
            }

        } else {

            # Nope, let's open it up if we can detaint the filename
            if ( detaint( $filename, 'filename', \$f ) ) {

                # Try to open the file
                pdebug( "opening $filename", PDLEVEL3 );
                if ( sysopen $fd, $f, O_RDONLY ) {

                    # Done, now cache and return the filehandle
                    $fhandles{$f} = $fd;
                    $fpids{$f}    = $$;
                    $fstat{$f}    = [ stat $f ];
                    $buffers{$f}  = '';
                    $rv           = $fd;

                    # If seekEOF is set, let's go to the end minus the offset
                    if ($seekEOF) {
                        pdebug( "moving to EOF offset $offset", PDLEVEL3 );
                        seek $fd, $offset, SEEK_END;
                        seek $fd, 0, SEEK_CUR;
                    }

                } else {

                    # Failed to do so, log the error
                    Paranoid::ERROR =
                        pdebug( "failed to open the file ($filename): $!",
                        PDLEVEL1 );
                    $rv = undef;
                }
            } else {
                Paranoid::ERROR =
                    pdebug( "failed to detaint filename: $filename",
                    PDLEVEL1 );
            }
        }

        return $rv;
    }

    sub sip ($$;$) {

        # Purpose:  Reads a block of lines from the specified file
        # Returns:  1 if content was read, 0 if not, -1 if LNSZLIMIT was
        #           exceeded
        # Usage:    $rv = sip($filename, \@lines);
        # Usage:    $rv = sip($filename, \@lines, 1);

        my $filename  = shift;
        my $aref      = shift;
        my $autoChomp = shift || 0;
        my $rv        = 0;
        my ( $fd, $nchar, $input, $i, $line );

        croak 'Mandatory first argument must be a defined filename'
            unless defined $filename;
        croak 'Mandatory second argument must be an array reference'
            unless defined $aref and ref $aref eq 'ARRAY';

        pdebug( "entering w/($filename)($aref)($autoChomp)", PDLEVEL1 );
        pIn();

        @$aref = ();

        # Get the file descriptor
        $fd = _getHandle($filename);
        if ( defined $fd ) {

            # First, use seek to reset EOF flags
            seek $fd, 0, SEEK_CUR;

            # Now, read a chunk
            flock $fd, LOCK_SH;
            $nchar = read $fd, $input, FSZLIMIT;
            flock $fd, LOCK_UN;

            if ($nchar) {

                # Got new content, so let's process it
                $rv = 1;

                # Split buffer + input into lines
                $line = "$buffers{$filename}$input";
                while ( length $line > 0 ) {
                    $line       =~ /\n/sm
                        ? $line =~ s/^(.*?\n)//sm
                        : $line =~ s/(.*)//sm;
                    push @$aref, $1;
                }

                if ( $nchar == FSZLIMIT ) {

                    # We didn't hit EOF so we need to preserve any trailing
                    # characters in the buffer to be concatenated to more
                    # input in a future sip
                    $buffers{$filename} = pop @$aref;

                    # We'll truncate the contents of the buffer if we already
                    # know it'll exceed LNSZLIMIT, but we need to keep enough
                    # of the string around to make it obvious on the next sip
                    # that the upcoming input (on the next sip) needs to
                    # be discard the rest of the line.
                    if ( length $buffers{$filename} > LNSZLIMIT ) {
                        pdebug(
                            'buffered data exceeds '
                                . LNSZLIMIT
                                . ' -- trimming',
                            PDLEVEL2
                            );
                        $buffers{$filename} = substr $buffers{$filename}, 0,
                            LNSZLIMIT +1;
                        $rv = RV_LSZERR;
                    }
                } else {

                    # We must have hit EOF, so we'll empty the buffer
                    $buffers{$filename} = '';
                }

                # Process whatever's left in the array
                $i = 0;
                while ( $i < @$aref ) {
                    if ( length $$aref[$i] > LNSZLIMIT ) {
                        pdebug( 'removing line exceeding ' . LNSZLIMIT,
                            PDLEVEL2 );
                        splice @$aref, $i, 1;
                        $rv = RV_LSZERR;
                    } else {
                        $i++;
                    }
                }

                # Chomp, if necessary
                chomp @$aref if $autoChomp;
            }
        }

        pOut();
        pdebug( "entering w/rv: $rv", PDLEVEL1 );

        return $rv;
    }

    sub tail ($$;$$) {

        # Purpose:  Augments sip's tailing abilities by seeking to
        #           the end (or, optionally, backwards)
        # Returns:  Same as sip
        # Usage:    $rv = tail($filename, \@lines);
        # Usage:    $rv = tail($filename, \@lines, -100);
        # Usage:    $rv = tail($filename, \@lines, -100, 1);

        my $filename  = shift;
        my $aref      = shift;
        my $offset    = shift || 0;
        my $autoChomp = shift || 0;
        my $rv        = 1;
        my ( $fd, $bpos, $ofszlimit );

        croak 'Mandatory first argument must be a defined filename'
            unless defined $filename;
        croak 'Mandatory second argument must be an array reference'
            unless defined $aref and ref $aref eq 'ARRAY';

        pdebug( "entering w/($filename)($aref)($offset)($autoChomp)",
            PDLEVEL1 );
        pIn();

        # Get the file descriptor
        $offset *= LNSZLIMIT +1;
        $fd = _getHandle( $filename, 1, $offset );
        if ( defined $fd ) {

            if ($offset) {

                # We also need to temporarily change FSZLIMIT so we can get
                # all of our back input in one fell swoop
                $ofszlimit = FSZLIMIT;
                FSZLIMIT = abs $offset + $ofszlimit;
            }

            # Now, call sip
            sip( $filename, $aref, $autoChomp );

            # Restore FSZLIMIT if this was the initial call, and prune excess
            # lines found
            if ($offset) {
                FSZLIMIT = $ofszlimit;
                $offset = abs $offset / LNSZLIMIT +1;
                if ( $offset < @$aref ) {
                    splice @$aref, 0, @$aref - $offset;
                }
            }
        } else {
            $rv = 0;
        }

        pOut();
        pdebug( "entering w/rv: $rv", PDLEVEL1 );

        return $rv;
    }
}

{
    my %regexes = (
        alphabetic   => qr/[a-zA-Z]+/sm,
        alphanumeric => qr/[a-zA-Z0-9]+/sm,
        alphawhite   => qr/[a-zA-Z\s]+/sm,
        alnumwhite   => qr/[a-zA-Z0-9\s]+/sm,
        email =>
            qr/[a-zA-Z][\w\.\-]*\@(?:[a-zA-Z0-9][a-zA-Z0-9\-]*\.)*[a-zA-Z0-9]+/sm,
        filename => qr#[/ \w\-\.:,@\+]+\[?#sm,
        fileglob => qr#[/ \w\-\.:,@\+\*\?\{\}\[\]]+\[?#sm,
        hostname => qr/(?:[a-zA-Z0-9][a-zA-Z0-9\-]*\.)*[a-zA-Z0-9]+/sm,
        ipaddr   => qr/(?:\d{1,3}\.){3}\d{1,3}/sm,
        netaddr  => qr#^(?:\d+\.){3}\d+(?:/(?:\d+|(?:\d+\.){3}\d+))?$#sm,
        login    => qr/[a-zA-Z][\w\.\-]*/sm,
        nometa   => qr/[^\%\`\$\!\@]+/sm,
        number   => qr/[+\-]?[0-9]+(?:\.[0-9]+)?/sm,
        );

    sub addTaintRegex ($$) {

        # Purpose:  Adds another regular expression to the internal hash
        # Returns:  True (1) if passed string is defined, False (0) if undef
        # Usage:    $rv = addTaintRegex($name, $regex);

        my $name  = shift;
        my $regex = shift;

        # TODO: Needs to enclose in an eval in case of bad regexes being
        # TODO: passed

        $regexes{$name} = qr/$regex/sm if defined $regex;

        return defined $regex ? 1 : 0;
    }

    sub _getTaintRegex ($) {

        # Purpose:  Retrieves the named regex
        # Returns:  Regex if named regex is defined, undef otherwise
        # Usage:    $regex = _getTaintRegex($name);

        my $name = shift;
        return ( defined $name && exists $regexes{$name} )
            ? $regexes{$name}
            : undef;
    }
}

sub detaint ($$$) {

    # Purpose:  Detaints and validates input in one call
    # Returns:  True (1) if detainting was successful,
    #           False (0) if there are any errors
    # Usage:    $rv = detaint($input, $dataType, \$detainted);

    my $input = shift;
    my $type  = shift;
    my $sref  = shift;
    my $rv    = 0;
    my $regex = _getTaintRegex($type);
    my $istr  = defined $input ? $input : 'undef';
    my $dstr  = defined $type ? $type : 'undef';

    # Validate arguments
    croak 'Mandatory third argument must be a valid scalar reference'
        unless defined $sref && ref $sref eq 'SCALAR';

    pdebug( "entering w/($istr)($dstr)($sref)", PDLEVEL1 );
    pIn();

    # Zero out contents of $sref
    $$sref = undef;

    # Is everything kosher for processing?
    if ( defined $input and length $input and defined $regex ) {

        # It is, so detaint
        ($$sref) = ( $input =~ /^($regex)$/sm );

        # Report the results
        if ( defined $$sref && length $$sref > 0 ) {
            $rv = 1;
            pdebug( "detainted value ($$sref)", PDLEVEL1 );
        } else {
            pdebug( 'failed to detaint input', PDLEVEL1 );
        }

    } else {

        # Bad arguments -- report and return false
        Paranoid::ERROR =
            pdebug( "bad arguments passed ($istr)($dstr)", PDLEVEL1 );
        $rv = 0;
    }

    pOut();
    pdebug( "leaving w/rv: $rv", PDLEVEL1 );

    return $rv;
}

sub stringMatch ($@) {

    # Purpose:  Looks for occurrences of strings and/or regexes in the passed
    #           input
    # Returns:  True (1) any of the strings/regexes match,
    #           False (0), otherwise
    # Usage:    $rv = stringMatch($input, @words);

    my $input = shift;
    my @match = splice @_;
    my $rv    = 0;
    my @regex;

    # Validate arguments
    croak 'Mandatory first argument must be defined input'
        unless defined $input;
    croak 'Mandatory string matches must be passed after input'
        unless @match;

    pdebug( "entering w/($input)(@match)", PDLEVEL1 );
    pIn();

    # Populate @regex w/regexes
    @regex = grep { defined $_ && ref $_ eq 'Regexp' } @match;

    # Convert remaining strings to regexes
    foreach ( grep { defined $_ && ref $_ ne 'Regexp' } @match ) {
        push @regex, m#^/(.+)/$#sm ? qr#$1#smi : qr#\Q$_\E#smi;
    }

    # Start comparisons
    study $input;
    foreach my $r (@regex) {
        if ( $input =~ /$r/smi ) {
            $rv = 1;
            last;
        }
    }

    pOut();
    pdebug( "leaving w/rv: $rv", PDLEVEL1 );

    return $rv;
}

1;

__END__

=head1 NAME

Paranoid::Input - Paranoid input functions

=head1 VERSION

$Id: Input.pm,v 0.20 2011/04/13 22:01:43 acorliss Exp $

=head1 SYNOPSIS

  use Paranoid::Input;

  FSZLIMIT  = 64 * 1024;
  LNSZLIMIT = 2 * 1024;

  $rv = slurp($filename, \@lines);

  $rv = sip($filename, \@lines);
  $rv = sip($filename, \@lines, 1);
  $rv = tail($filename, \@lines);
  $rv = tail($filename, \@lines, -100);
  $rv = tail($filename, \@lines, -100, 1);
  $rv = closeFile($filename);

  addTaintRegex("telephone", qr/\(\d{3}\)\s+\d{3}-\d{4}/);
  $rv = detaint($userInput, "login", \$val);

  $rv = stringMatch($input, @strings);

=head1 DESCRIPTION

The modules provide safer routines to use for input activities such as reading
files and detainting user input.

The B<sip> and B<tail> functions keep open file handles.  Even so, it's
specifically built to be safe for use in B<fork> scenarios.  You can being a
tail or sip in a parent, fork children, and all process can independently
continue sipping with no confusion between processes.  This is possible
because we check to see if the PID matches the PID in effect with the file was
opened.  If not, we reopen the file and seek to the same position so we can
pick up where we left off.

The B<slurp> function isn't affected by this since it reads entire files in a
single call, no filehandles are kept open between calls.

All file-reading functions use and obey B<flock>.

B<addTaintRegex> is only exported if this module is used with the B<:all> target.

=head1 SUBROUTINES/METHODS

=head2 FSZLIMIT

The value returned/set by this lvalue function is the maximum file size that
will be read into memory.  This affects functions like B<slurp> (documented
below).  Unless explicitly set this defaults to 16KB.

=head2 LNSZLIMIT

The valute returned/set by this lvalue function is the maximum line length
supported by functions like B<sip> (documented below).  Unless explicitly set
this defaults to 2KB.

=head2 slurp

  $rv = slurp($filename, \@lines);

This function allows you to read a text file in its entirety into memory, 
the lines of which are placed into the passed array reference.  This function 
will only read files up to B<FSZLIMIT> in size.  Flocking is used (with 
B<LOCK_SH>) and the read is a blocking read.

An optional third argument sets a boolean flag which, if true, determines if
all lines are automatically chomped.  If chomping is enabled this will strip
both UNIX and DOS line separators.

The return value is false if the read was unsuccessful or the file's size
exceeded B<FSZLIMIT>.  In the latter case the array reference will still be
populated with what was read.  The reason for the failure can be retrieved
B<from Paranoid::ERROR>.

=head2 sip

    $rv = sip($filename, \@lines);
    $rv = sip($filename, \@lines, 1);

This function allows you to read a text file into memory in chunks, the 
lines of which are placed into the passed array reference.  The chunks are 
read in at up to B<FSZLIMIT> in size at a time.  Like B<slurp> file locking 
is used and autochomping is also supported.

This function returns true if there was input read, but if any or all of the
input splits into lines greater than B<LNSZLIMIT> it will discard that input
and return -1 (which is still technically boolean true).

The reason why we now care about line lengths is because it's very likely that
line boundaries will not fall neatly along our chunk boundaries, so we need to
take trailing portions of unterminated lines and store them to be joined with
the remainder from the next sip.

When sip comes up to then end of the file it does not close the file, you're
required to close it explicitly with B<closeFile>.  This is done intentionally
to allow the process to continue to effectively B<tail> a growing file.
Unlike the B<tail> function provided here, though, it does perform any
additional checks to see if the file you're reading was truncated or replaced.

An optional third argument tells sip whether or not to chomp all the read
lines before returning.

=head2 tail

    $rv = tail($filename, \@lines);
    $rv = tail($filename, \@lines, -100);
    $rv = tail($filename, \@lines, -100, 1);

The only difference between this function and B<sip> is that tail opens the
file and immediately seeks to the end.  If an optional third argument is
passed it will seek backwards to extract and return that number of lines (if
possible).  Depending on the number passed one must be prepared for enough
memory to be allocated to store B<LNSZLIMIT> * that number.

This function returns true if the file is successfully open, regardless of
whether any new input was there to be read.  It only returns false if there 
was a problem opening or reading the file.

Tail should be called with the third argument for the first tail of a file.
Continuing to use it for subsequent calls will cause the number of lines
returned to be truncated to fit within that limit.

Like B<sip>, one must explicitly close a file with B<closeFile>.

=head2 closeFile

  $rv = closeFile($filename);

This function closes any open file descriptors that may have been opened via
B<sip> or B<tail> for the named file.  This returns the value of the B<close>
function if the file was open, otherwise it returns true.

=head2 addTaintRegex

  addTaintRegex("telephone", qr/\(\d{3}\)\s+\d{3}-\d{4}/);

This adds a regular expression which can used by name to detaint user input
via the B<detaint> function.  This will allow you to overwrite the internally
provided regexes or as well as your own.

=head2 detaint

  $rv = detaint($userInput, "login", \$val);

This function populates the passed reference with the detainted input from the
first argument.  The second argument specifies the type of data in the first
argument, and is used to validate the input before detainting.  The following
data types are currently known:

  alphabetic            ^([a-zA-Z]+)$
  alphanumeric          ^([a-zA-Z0-9])$
  email                 ^([a-zA-Z][\w\.\-]*\@
                        (?:[a-zA-Z0-9][a-zA-Z0-9\-]*\.)*
                        [a-zA-Z0-9]+)$
  filename              ^[/ \w\-\.:,@\+]+\[?$
  fileglob              ^[/ \w\-\.:,@\+\*\?\{\}\[\]]+\[?$
  hostname              ^(?:[a-zA-Z0-9][a-zA-Z0-9\-]*\.)*
                        [a-zA-Z0-9]+)$
  ipaddr                ^(?:\d+\.){3}\d+$
  netaddr               ^(?:\d+\.){3}\d+(?:/(?:\d+|
                        (?:\d+\.){3}\d+))?$
  login                 ^([a-zA-Z][\w\.\-]*)$
  nometa                ^([^\`\$\!\@]+)$
  number                ^([+\-]?[0-9]+(?:\.[0-9]+)?)$

If the first argument fails to match against these regular expressions the
function will return 0.  If the string passed is either undefined or a
zero-length string it will also return 0.  And finally, if you attempt to use
an unknown (or unregistered) data type it will also return 0, and log an error
message in B<Paranoid::ERROR>.

B<NOTE>:  This is a small alteration in previous behavior.  In previous
versions if an undef or zero-length string was passed, or if the data type was
unknown the code would croak.  That was, perhaps, a tad overzealous on my
part.

=head2 stringMatch

  $rv = stringMatch($input, @strings);

This function does a multiline case insensitive regex match against the 
input for every string passed for matching.  This does safe quoted matches 
(\Q$string\E) for all the strings, unless the string is a perl Regexp 
(defined with qr//) or begins and ends with /.

B<NOTE>: this performs a study in hopes that for a large number of regexes
will be performed faster.  This may not always be the case.

=head1 DEPENDENCIES

=over

=item o

L<Fcntl>

=item o

L<Paranoid>

=item o

L<Paranoid::Debug>

=back

=head1 BUGS AND LIMITATIONS

If you fork a process that's already opened a file with B<sip> or B<tail> a
new file descriptor will be opened for the child process.  But what may be
less obvious is that with a newly opened file descriptor you will be starting
back from the beginning (or end, in the case of B<tail>) of the file, rather
than from where ever you were before the fork.

=head1 AUTHOR

Arthur Corliss (corliss@digitalmages.com)

=head1 LICENSE AND COPYRIGHT

This software is licensed under the same terms as Perl, itself. 
Please see http://dev.perl.org/licenses/ for more information.

(c) 2005, Arthur Corliss (corliss@digitalmages.com)