blib/lib/LightTCP/Server.pm

filter: Statementstmt 28.6% 254 / 887 Branchbran 20.0% 93 / 464 Conditioncond 22.8% 55 / 241 MC/DCmcdc 14.0% 20 / 142 Subroutinesub 36.6% 33 / 90 Podpod 97.5% 40 / 41 totaltotal 26.5% 495 / 1865 CC 322 SCAR 51.1
CC
322
Cov
25%
_httpparse
992.0
start
552.0
_httprequest
462.0
CRAP 166.0
↑ Summary
1 #!/usr/bin/env perl
2 package LightTCP::Server;
3  
4 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 5 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use IO::Socket::INET;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use IPC::Open3;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use File::Temp;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # Make threads support optional
13 5 ▶our $HAS_THREADS = eval {
Condition50%1/2
eval { do { require threads; require threads::shared; 1 } } || 0
l!l
05
MC/DC0%0/1
eval { do { require threads; require threads::shared; 1 } } || 0
eval { do { require threads; require threads::shared; 1 } }
Truth table50%1/2
A
A= eval { do { require threads; require threads::shared; 1 } }
Aresult
11
00
14 5 require threads;
15 0 require threads::shared;
16 0 1;
17 } || 0;
18  
19 5 our $VERSION = '2.05';
20  
21 5 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
22 5 DEFAULT_ADDR => '0.0.0.0:8881',
23 DEFAULT_NAME => 'tcpsrv',
24 DEFAULT_TYPE => 'single',
25 DEFAULT_THREADS => 10,
26 DEFAULT_TIMEOUT => -1,
27 DEFAULT_DIR => '/var/www',
28 DEFAULT_ETC => '.',
29 DEFAULT_FNEXT => 'html css js ico gif jpg png',
30 DEFAULT_CGIEXT => 'cgi php',
31 DEFAULT_UPLOAD_DIR => '/var/www/uploads',
32 UPLOAD_MAX_SIZE => 10 * 1024 * 1024,
33 RATE_LIMIT_REQUESTS => 100,
34 RATE_LIMIT_WINDOW => 60,
35 RATE_LIMIT_BLOCK => 300,
36 5 };
37  
38 23 ▶sub new {
Subroutine new: called CC=5 SCAR=16.1
Pod documented
39 23 my ($class, @args) = @_;
40 23 my $self = bless {}, $class;
41  
42 23 ▶ if (@args == 1 && ref $args[0] eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (@args == 1 and ref $args[0] eq "HASH") 0 23 23
Condition33%1/3
@args == 1 and ref $args[0] eq "HASH"
!ll&&!rl&&r
2300
MC/DC0%0/2
@args == 1 and ref $args[0] eq "HASH"
@args == 1 ref $args[0] eq "HASH"
Truth table33%1/3
A and B
A= @args == 1B= ref $args[0] eq "HASH"
ABresult
0X0
100
111
43 0 @args = %{$args[0]};
44 }
45 23 $self->{server_addr} = DEFAULT_ADDR;
46 23 $self->{server_name} = DEFAULT_NAME;
47 23 $self->{server_type} = DEFAULT_TYPE;
48 23 $self->{max_threads} = DEFAULT_THREADS;
49 23 $self->{server_timeout} = DEFAULT_TIMEOUT;
50 23 $self->{server_dir} = DEFAULT_DIR;
51 23 $self->{server_etc} = DEFAULT_ETC;
52 23 $self->{server_autostop} = 0;
53 23 $self->{server_deny} = 0;
54 23 $self->{server_secure} = 0;
55 23 $self->{server_auth} = 0;
56 23 $self->{server_keys} = [];
57 23 $self->{runas_user} = '';
58 23 $self->{runas_group} = '';
59 23 $self->{server_http} = 1;
60 23 $self->{server_perlonly} = 1;
61 23 $self->{server_fnext} = DEFAULT_FNEXT;
62 23 $self->{server_cgi} = 0;
63 23 $self->{server_cgiext} = DEFAULT_CGIEXT;
64 23 $self->{http_postlimit} = 0;
65 23 $self->{func_timeout} = undef;
66 23 $self->{func_perl} = undef;
67 23 $self->{func_done} = undef;
68 23 $self->{func_log} = undef;
69 23 $self->{func_upload} = undef;
70 23 $self->{logfn} = '';
71 23 $self->{verbose} = 0;
72 23 $self->{_server} = undef;
73 23 $self->{_serverloop} = 1;
74 23 $self->{_threads} = [];
75 23 $self->{_log_lock} = do { my $lock :shared; \$lock; };
76 23 $self->{upload_dir} = DEFAULT_UPLOAD_DIR;
77 23 $self->{upload_max_size} = UPLOAD_MAX_SIZE;
78 23 $self->{upload_allowed_types} = [qw(
79 image/jpeg image/png image/gif image/webp
80 application/pdf text/plain text/csv text/html
81 application/zip application/x-zip-compressed
82 application/msword
83 application/vnd.openxmlformats-officedocument.wordprocessingml.document
84 application/vnd.ms-excel
85 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
86 )];
87 23 $self->{rate_limit_enabled} = 0;
88 23 $self->{rate_limit_requests} = RATE_LIMIT_REQUESTS;
89 23 $self->{rate_limit_window} = RATE_LIMIT_WINDOW;
90 23 $self->{rate_limit_block_duration} = RATE_LIMIT_BLOCK;
91 23 $self->{rate_limit_whitelist} = [qw(127.0.0.1 ::1 localhost)];
92 23 $self->{_rate_limit_lock} = do { my $lock :shared; \$lock; };
93 23 $self->{_rate_limit_data} = {};
94 23 $self->{_upload_lock} = do { my $lock :shared; \$lock; };
95  
96 23 ▶ while (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 174 19 193
97 174 my ($attr, $value) = splice(@args, 0, 2);
98 174 ▶ $self->$attr($value) if $self->can($attr);
Branch: 1 branch
BranchTrueFalseTotal
if $self->can($attr) 174 0 174
99 }
100  
101 19 $self->_init_config();
102 19 return $self;
103 }
104  
105 22 ▶sub server_addr {
Subroutine server_addr: called CC=4 SCAR=15.2
Pod documented
106 22 my ($self, $value) = @_;
107 22 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 22 0 22
108 22 ▶ croak "server_addr is required" unless defined $value && $value ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value ne "" 0 22 22
Condition33%1/3
defined $value and $value ne ""
!ll&&!rl&&r
0022
MC/DC0%0/2
defined $value and $value ne ""
defined $value $value ne ""
Truth table33%1/3
A and B
A= defined $valueB= $value ne ""
ABresult
0X0
100
111
109 22 $self->{server_addr} = $value;
110 }
111 22 return $self->{server_addr};
112 }
113  
114 0 ▶sub server_name {
Subroutine server_name: not called CC=4 SCAR=30.0
Pod documented
115 0 my ($self, $value) = @_;
116 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
117 0 ▶ croak "server_name must be a string" if defined $value && ref $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and ref $value 0 0 0
Condition0%0/3
defined $value and ref $value
!ll&&!rl&&r
000
MC/DC0%0/2
defined $value and ref $value
defined $value ref $value
Truth table0%0/3
A and B
A= defined $valueB= ref $value
ABresult
0X0
100
111
118 0 $self->{server_name} = $value;
119 }
120 0 return $self->{server_name};
121 }
122  
123 0 ▶sub server_type {
Subroutine server_type: not called CC=3 SCAR=24.8
Pod documented
124 0 my ($self, $value) = @_;
125 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
126 0 ▶ croak "server_type must be single, fork, or thread" unless $value =~ /^(?:single|fork|thread)$/x;
Branch: 1 branch
BranchTrueFalseTotal
unless $value =~ /^(?:single|fork|thread)$/x 0 0 0
127 0 $self->{server_type} = $value;
128 }
129 0 return $self->{server_type};
130 }
131  
132 0 ▶sub max_threads {
Subroutine max_threads: not called CC=4 SCAR=30.0
Pod documented
133 0 my ($self, $value) = @_;
134 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
135 0 ▶ croak "max_threads must be a positive integer" if defined $value && $value !~ /^\d+$/x;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and not $value =~ /^\d+$/x 0 0 0
Condition0%0/3
defined $value and not $value =~ /^\d+$/x
!ll&&!rl&&r
000
MC/DC0%0/2
defined $value and not $value =~ /^\d+$/x
defined $value not $value =~ /^\d+$/x
Truth table0%0/3
A and not(B)
A= defined $valueB= not $value =~ /^\d+$/x
ABresult
0X0
100
111
136 0 $self->{max_threads} = $value;
137 }
138 0 return $self->{max_threads};
139 }
140  
141 0 ▶sub server_timeout {
Subroutine server_timeout: not called CC=4 SCAR=30.0
Pod documented
142 0 my ($self, $value) = @_;
143 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
144 0 ▶ croak "server_timeout must be >= -1" if defined $value && $value < -1;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and $value < -1 0 0 0
Condition0%0/3
defined $value and $value < -1
!ll&&!rl&&r
000
MC/DC0%0/2
defined $value and $value < -1
defined $value $value < -1
Truth table0%0/3
A and B
A= defined $valueB= $value < -1
ABresult
0X0
100
111
145 0 $self->{server_timeout} = $value;
146 }
147 0 return $self->{server_timeout};
148 }
149  
150 0 ▶sub server_dir {
Subroutine server_dir: not called CC=2 SCAR=17.9
Pod documented
151 0 my ($self, $value) = @_;
152 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
153 0 $self->{server_dir} = $value;
154 }
155 0 return $self->{server_dir};
156 }
157  
158 0 ▶sub server_etc {
Subroutine server_etc: not called CC=2 SCAR=17.9
Pod documented
159 0 my ($self, $value) = @_;
160 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
161 0 $self->{server_etc} = $value;
162 }
163 0 return $self->{server_etc};
164 }
165  
166 0 ▶sub server_autostop {
Subroutine server_autostop: not called CC=2 SCAR=17.9
Pod documented
167 0 my ($self, $value) = @_;
168 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
169 0 $self->{server_autostop} = $value;
170 }
171 0 return $self->{server_autostop};
172 }
173  
174 0 ▶sub server_deny {
Subroutine server_deny: not called CC=2 SCAR=17.9
Pod documented
175 0 my ($self, $value) = @_;
176 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
177 0 $self->{server_deny} = $value;
178 }
179 0 return $self->{server_deny};
180 }
181  
182 0 ▶sub server_secure {
Subroutine server_secure: not called CC=2 SCAR=17.9
Pod documented
183 0 my ($self, $value) = @_;
184 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
185 0 $self->{server_secure} = $value;
186 }
187 0 return $self->{server_secure};
188 }
189  
190 0 ▶sub server_auth {
Subroutine server_auth: not called CC=2 SCAR=17.9
Pod documented
191 0 my ($self, $value) = @_;
192 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
193 0 $self->{server_auth} = $value;
194 }
195 0 return $self->{server_auth};
196 }
197  
198 0 ▶sub server_keys {
Subroutine server_keys: not called CC=4 SCAR=30.0
Pod documented
199 0 my ($self, $value) = @_;
200 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
201 0 ▶ croak "server_keys must be an arrayref" if defined $value && ref $value ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and ref $value ne "ARRAY" 0 0 0
Condition0%0/3
defined $value and ref $value ne "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $value and ref $value ne "ARRAY"
defined $value ref $value ne "ARRAY"
Truth table0%0/3
A and B
A= defined $valueB= ref $value ne "ARRAY"
ABresult
0X0
100
111
202 0 $self->{server_keys} = $value;
203 }
204 0 return $self->{server_keys};
205 }
206  
207 0 ▶sub runas_user {
Subroutine runas_user: not called CC=2 SCAR=17.9
Pod documented
208 0 my ($self, $value) = @_;
209 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
210 0 $self->{runas_user} = $value;
211 }
212 0 return $self->{runas_user};
213 }
214  
215 0 ▶sub runas_group {
Subroutine runas_group: not called CC=2 SCAR=17.9
Pod documented
216 0 my ($self, $value) = @_;
217 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
218 0 $self->{runas_group} = $value;
219 }
220 0 return $self->{runas_group};
221 }
222  
223 0 ▶sub server_http {
Subroutine server_http: not called CC=2 SCAR=17.9
Pod undocumented
224 0 my ($self, $value) = @_;
225 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
226 0 $self->{server_http} = $value;
227 }
228 0 return $self->{server_http};
229 }
230  
231 0 ▶sub server_perlonly {
Subroutine server_perlonly: not called CC=2 SCAR=17.9
Pod documented
232 0 my ($self, $value) = @_;
233 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
234 0 $self->{server_perlonly} = $value;
235 }
236 0 return $self->{server_perlonly};
237 }
238  
239 0 ▶sub server_fnext {
Subroutine server_fnext: not called CC=2 SCAR=17.9
Pod documented
240 0 my ($self, $value) = @_;
241 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
242 0 $self->{server_fnext} = $value;
243 }
244 0 return $self->{server_fnext};
245 }
246  
247 0 ▶sub server_cgi {
Subroutine server_cgi: not called CC=2 SCAR=17.9
Pod documented
248 0 my ($self, $value) = @_;
249 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
250 0 $self->{server_cgi} = $value;
251 }
252 0 return $self->{server_cgi};
253 }
254  
255 0 ▶sub server_cgiext {
Subroutine server_cgiext: not called CC=2 SCAR=17.9
Pod documented
256 0 my ($self, $value) = @_;
257 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
258 0 $self->{server_cgiext} = $value;
259 }
260 0 return $self->{server_cgiext};
261 }
262  
263 0 ▶sub http_postlimit {
Subroutine http_postlimit: not called CC=2 SCAR=17.9
Pod documented
264 0 my ($self, $value) = @_;
265 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
266 0 $self->{http_postlimit} = $value;
267 }
268 0 return $self->{http_postlimit};
269 }
270  
271 0 ▶sub func_timeout {
Subroutine func_timeout: not called CC=2 SCAR=17.9
Pod documented
272 0 my ($self, $value) = @_;
273 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
274 0 $self->{func_timeout} = $value;
275 }
276 0 return $self->{func_timeout};
277 }
278  
279 0 ▶sub func_perl {
Subroutine func_perl: not called CC=2 SCAR=17.9
Pod documented
280 0 my ($self, $value) = @_;
281 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
282 0 $self->{func_perl} = $value;
283 }
284 0 return $self->{func_perl};
285 }
286  
287 0 ▶sub func_done {
Subroutine func_done: not called CC=2 SCAR=17.9
Pod documented
288 0 my ($self, $value) = @_;
289 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
290 0 $self->{func_done} = $value;
291 }
292 0 return $self->{func_done};
293 }
294  
295 0 ▶sub func_log {
Subroutine func_log: not called CC=2 SCAR=17.9
Pod documented
296 0 my ($self, $value) = @_;
297 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
298 0 $self->{func_log} = $value;
299 }
300 0 return $self->{func_log};
301 }
302  
303 0 ▶sub logfn {
Subroutine logfn: not called CC=2 SCAR=17.9
Pod documented
304 0 my ($self, $value) = @_;
305 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
306 0 $self->{logfn} = $value;
307 }
308 0 return $self->{logfn};
309 }
310  
311 55 ▶sub verbose {
Subroutine verbose: called CC=5 SCAR=17.8
Pod documented
312 55 my ($self, $value) = @_;
313 55 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 21 34 55
314 21 ▶ croak "verbose must be 0-3" if defined $value && ($value < 0 || $value > 3);
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and $value < 0 || $value > 3 0 21 21
Condition33%2/6
defined $value and $value < 0 || $value > 3
!ll&&!rl&&r
0210
$value < 0 or $value > 3
l!l&&r!l&&!r
0021
MC/DC0%0/3
defined $value and $value < 0 || $value > 3
defined $value $value < 0 $value > 3
Truth table25%1/4
A and B or C
A= defined $valueB= $value < 0C= $value > 3
ABCresult
0XX0
1000
11X1
1011
315 21 $self->{verbose} = $value;
316 }
317 55 return $self->{verbose};
318 }
319  
320 0 ▶sub _server {
Subroutine _server: not called CC=2 SCAR=17.9
321 0 my ($self, $value) = @_;
322 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
323 0 $self->{_server} = $value;
324 }
325 0 return $self->{_server};
326 }
327  
328 0 ▶sub _serverloop {
Subroutine _serverloop: not called CC=2 SCAR=17.9
329 0 my ($self, $value) = @_;
330 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
331 0 $self->{_serverloop} = $value;
332 }
333 0 return $self->{_serverloop};
334 }
335  
336 0 ▶sub _threads {
Subroutine _threads: not called CC=2 SCAR=17.9
337 0 my ($self, $value) = @_;
338 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
339 0 $self->{_threads} = $value;
340 }
341 0 return $self->{_threads};
342 }
343  
344 0 ▶sub _log_lock {
Subroutine _log_lock: not called CC=2 SCAR=17.9
345 0 my ($self, $value) = @_;
346 0 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 0 0
347 0 $self->{_log_lock} = $value;
348 }
349 0 return $self->{_log_lock};
350 }
351  
352 25 ▶sub upload_dir {
Subroutine upload_dir: called CC=5 SCAR=16.2
Pod documented
353 25 my ($self, $value) = @_;
354 25 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 20 5 25
355 20 ▶ croak "upload_dir must be a non-empty string" unless defined $value && $value ne '' && !ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value ne "" and not ref $value 1 19 20
Condition66%4/6
defined $value and $value ne "" and not ref $value
!ll&&!rl&&r
1019
defined $value and $value ne ""
!ll&&!rl&&r
0119
MC/DC33%1/3
defined $value and $value ne "" and not ref $value
defined $value $value ne "" not ref $value
Truth table50%2/4
A and B and not(C)
A= defined $valueB= $value ne ""C= not ref $value
ABCresult
0XX0
10X0
1100
1111
356 19 $self->{upload_dir} = $value;
357 }
358 24 return $self->{upload_dir};
359 }
360  
361 27 ▶sub upload_max_size {
Subroutine upload_max_size: called CC=4 SCAR=13.9
Pod documented
362 27 my ($self, $value) = @_;
363 27 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 22 5 27
364 22 ▶ croak "upload_max_size must be positive" if defined $value && $value <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and $value <= 0 1 21 22
Condition66%2/3
defined $value and $value <= 0
!ll&&!rl&&r
0211
MC/DC50%1/2
defined $value and $value <= 0
defined $value $value <= 0
Truth table66%2/3
A and B
A= defined $valueB= $value <= 0
ABresult
0X0
100
111
365 21 $self->{upload_max_size} = $value;
366 }
367 26 return $self->{upload_max_size};
368 }
369  
370 9 ▶sub upload_allowed_types {
Subroutine upload_allowed_types: called CC=4 SCAR=14.5
Pod documented
371 9 my ($self, $value) = @_;
372 9 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 2 7 9
373 2 ▶ croak "upload_allowed_types must be an arrayref" if defined $value && ref $value ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and ref $value ne "ARRAY" 0 2 2
Condition33%1/3
defined $value and ref $value ne "ARRAY"
!ll&&!rl&&r
020
MC/DC0%0/2
defined $value and ref $value ne "ARRAY"
defined $value ref $value ne "ARRAY"
Truth table33%1/3
A and B
A= defined $valueB= ref $value ne "ARRAY"
ABresult
0X0
100
111
374 2 $self->{upload_allowed_types} = $value;
375 }
376 9 return $self->{upload_allowed_types};
377 }
378  
379 3 ▶sub func_upload {
Subroutine func_upload: called CC=2 SCAR=6.9
Pod documented
380 3 my ($self, $value) = @_;
381 3 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 1 2 3
382 1 $self->{func_upload} = $value;
383 }
384 3 return $self->{func_upload};
385 }
386  
387 23 ▶sub rate_limit_enabled {
Subroutine rate_limit_enabled: called CC=2 SCAR=6.9
Pod documented
388 23 my ($self, $value) = @_;
389 23 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 22 1 23
390 22 $self->{rate_limit_enabled} = $value;
391 }
392 23 return $self->{rate_limit_enabled};
393 }
394  
395 33 ▶sub rate_limit_requests {
Subroutine rate_limit_requests: called CC=4 SCAR=13.9
Pod documented
396 33 my ($self, $value) = @_;
397 33 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 22 11 33
398 22 ▶ croak "rate_limit_requests must be positive" if defined $value && $value <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and $value <= 0 1 21 22
Condition66%2/3
defined $value and $value <= 0
!ll&&!rl&&r
0211
MC/DC50%1/2
defined $value and $value <= 0
defined $value $value <= 0
Truth table66%2/3
A and B
A= defined $valueB= $value <= 0
ABresult
0X0
100
111
399 21 $self->{rate_limit_requests} = $value;
400 }
401 32 return $self->{rate_limit_requests};
402 }
403  
404 33 ▶sub rate_limit_window {
Subroutine rate_limit_window: called CC=4 SCAR=13.9
Pod documented
405 33 my ($self, $value) = @_;
406 33 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 23 10 33
407 23 ▶ croak "rate_limit_window must be positive" if defined $value && $value <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and $value <= 0 1 22 23
Condition66%2/3
defined $value and $value <= 0
!ll&&!rl&&r
0221
MC/DC50%1/2
defined $value and $value <= 0
defined $value $value <= 0
Truth table66%2/3
A and B
A= defined $valueB= $value <= 0
ABresult
0X0
100
111
408 22 $self->{rate_limit_window} = $value;
409 }
410 32 return $self->{rate_limit_window};
411 }
412  
413 22 ▶sub rate_limit_block_duration {
Subroutine rate_limit_block_duration: called CC=4 SCAR=14.5
Pod documented
414 22 my ($self, $value) = @_;
415 22 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 21 1 22
416 21 ▶ croak "rate_limit_block_duration must be non-negative" if defined $value && $value < 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and $value < 0 0 21 21
Condition33%1/3
defined $value and $value < 0
!ll&&!rl&&r
0210
MC/DC0%0/2
defined $value and $value < 0
defined $value $value < 0
Truth table33%1/3
A and B
A= defined $valueB= $value < 0
ABresult
0X0
100
111
417 21 $self->{rate_limit_block_duration} = $value;
418 }
419 22 return $self->{rate_limit_block_duration};
420 }
421  
422 10 ▶sub rate_limit_whitelist {
Subroutine rate_limit_whitelist: called CC=4 SCAR=21.7
Pod documented
423 10 my ($self, $value) = @_;
424 10 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 10 10
425 0 ▶ croak "rate_limit_whitelist must be an arrayref" if defined $value && ref $value ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and ref $value ne "ARRAY" 0 0 0
Condition0%0/3
defined $value and ref $value ne "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $value and ref $value ne "ARRAY"
defined $value ref $value ne "ARRAY"
Truth table0%0/3
A and B
A= defined $valueB= ref $value ne "ARRAY"
ABresult
0X0
100
111
426 0 $self->{rate_limit_whitelist} = $value;
427 }
428 10 return $self->{rate_limit_whitelist};
429 }
430  
431 14 ▶sub _rate_limit_lock {
Subroutine _rate_limit_lock: called CC=2 SCAR=7.6
432 14 my ($self, $value) = @_;
433 14 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 14 14
434 0 $self->{_rate_limit_lock} = $value;
435 }
436 14 return $self->{_rate_limit_lock};
437 }
438  
439 15 ▶sub _rate_limit_data {
Subroutine _rate_limit_data: called CC=2 SCAR=7.6
440 15 my ($self, $value) = @_;
441 15 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 15 15
442 0 $self->{_rate_limit_data} = $value;
443 }
444 15 return $self->{_rate_limit_data};
445 }
446  
447 3 ▶sub _upload_lock {
Subroutine _upload_lock: called CC=2 SCAR=7.6
448 3 my ($self, $value) = @_;
449 3 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 0 3 3
450 0 $self->{_upload_lock} = $value;
451 }
452 3 return $self->{_upload_lock};
453 }
454  
455 19 ▶sub _init_config {
Subroutine _init_config: called CC=3 SCAR=14.2
456 19 my ($self) = @_;
457  
458 19 ▶ if ($self->verbose) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->verbose) 0 19 19
459 0 for my $attr (qw(server_addr server_name server_type max_threads server_timeout
460 server_dir server_etc server_deny server_secure server_auth
461 runas_user runas_group server_http server_perlonly server_fnext
462 server_cgi server_cgiext http_postlimit logfn verbose)) {
463 0 $self->logit(sprintf("- %-16s = %s", $attr, $self->$attr), 2);
464 }
465 }
466 }
467  
468 0 ▶sub _create_server {
Subroutine _create_server: not called CC=2 SCAR=17.9
469 0 my ($self) = @_;
470  
471 0 my $server = IO::Socket::INET->new(
472 LocalAddr => $self->server_addr,
473 Proto => 'tcp',
474 Listen => SOMAXCONN,
475 ReuseAddr => SO_REUSEADDR
476 );
477  
478 0 ▶ if (!$server) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($server) 0 0 0
479 0 $self->logit("# Error: Failed to bind to " . $self->server_addr . " - $!", 0);
480 0 return undef;
481 }
482  
483 0 $self->_server($server);
484 0 $self->logit("# " . $self->server_name . " Listening for requests on " . $self->server_addr, 0);
485 0 return $server;
486 }
487  
488 0 ▶sub _set_runas {
Subroutine _set_runas: not called CC=10 SCAR=47.0
489 0 my ($self) = @_;
490  
491 0 my $user = $self->runas_user;
492 0 my $group = $self->runas_group;
493  
494 0 ▶ if ($user ne '' || $group ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($user ne "" or $group ne "") 0 0 0
Condition0%0/3
$user ne "" or $group ne ""
l!l&&r!l&&!r
000
MC/DC0%0/2
$user ne "" or $group ne ""
$user ne "" $group ne ""
Truth table0%0/3
A or B
A= $user ne ""B= $group ne ""
ABresult
1X1
011
000
495 0 ▶ if ($group ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($group ne "") 0 0 0
496 0 my $gid = getgrnam($group);
497 0 ▶ $) = "$gid $gid" or $self->logit("# Error setting group $group: $!", 0) if $gid;
Branch: 1 branch
BranchTrueFalseTotal
if $gid 0 0 0
Condition0%0/6
$gid && (($) = "$gid $gid") || $self->logit("# Error setting group ${group}: $!", 0))
!ll&&!rl&&r
000
$) = "$gid $gid" or $self->logit("# Error setting group ${group}: $!", 0)
l!l&&r!l&&!r
000
MC/DC0%0/3
$gid && (($) = "$gid $gid") || $self->logit("# Error setting group ${group}: $!", 0))
$gid $) = "$gid $gid" $self->logit("# Error setting group ${group}: $!", 0)
Truth table0%0/4
A && B or C
A= $gidB= $) = "$gid $gid"C= $self->logit("# Error setting group ${group}: $!", 0)
ABCresult
0XX0
1000
11X1
1011
498 }
499 0 ▶ if ($user ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($user ne "") 0 0 0
500 0 my $uid = getpwnam($user);
501 0 ▶ chown($uid, -1, $self->logfn) if $self->logfn ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $self->logfn ne "" 0 0 0
502 0 ▶ $> = $uid or $self->logit("# Error setting user $user: $!", 0) if $uid;
Branch: 1 branch
BranchTrueFalseTotal
if $uid 0 0 0
Condition0%0/6
$uid && (($> = $uid) || $self->logit("# Error setting user ${user}: $!", 0))
!ll&&!rl&&r
000
$> = $uid or $self->logit("# Error setting user ${user}: $!", 0)
l!l&&r!l&&!r
000
MC/DC0%0/3
$uid && (($> = $uid) || $self->logit("# Error setting user ${user}: $!", 0))
$uid $> = $uid $self->logit("# Error setting user ${user}: $!", 0)
Truth table0%0/4
A && B or C
A= $uidB= $> = $uidC= $self->logit("# Error setting user ${user}: $!", 0)
ABCresult
0XX0
1000
11X1
1011
503 }
504 0 $self->logit("# Running as user $user and group $group", 0);
505 }
506 }
507  
508 0 ▶sub start {
Subroutine start: not called CC=23 SCAR=63.1
Pod documented
509 0 my ($self) = @_;
510  
511 0 my $server = $self->_create_server();
512 0 ▶ return 0 unless defined $server;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $server 0 0 0
513 0 ▶ if ($self->{server_type} eq 'thread' && !$HAS_THREADS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server_type"} eq "thread" and not $LightTCP::Server::HAS_THREADS) 0 0 0
Condition0%0/3
$self->{"server_type"} eq "thread" and not $LightTCP::Server::HAS_THREADS
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"server_type"} eq "thread" and not $LightTCP::Server::HAS_THREADS
$self->{"server_type"} eq "thread" not $LightTCP::Server::HAS_THREADS
Truth table0%0/3
A and not(B)
A= $self->{"server_type"} eq "thread"B= not $LightTCP::Server::HAS_THREADS
ABresult
0X0
100
111
514 warn "Threads not available in this Perl. Falling back to fork mode.\n"
515 0 ▶ if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
516 0 $self->{server_type} = 'fork'; # or 'single'
517 }
518 0 $self->_set_runas();
519  
520 0 $self->_serverloop(1);
521 0 $| = 1;
522  
523 0 ▶ local $SIG{INT} = sub { $self->_signal_handler() };
Subroutine __ANON__: not called CC=1 SCAR=6.9
524 0 ▶ local $SIG{TERM} = sub { $self->_signal_handler() };
Subroutine __ANON__: not called CC=1 SCAR=6.9
525  
526 #$self->logit("# " . $self->server_name . " Listening for requests on " . $self->server_addr, 0);
527  
528 0 my $threads = $self->_threads;
529  
530 0 ▶ while ($self->_serverloop) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_serverloop) 0 0 0
531 0 ▶ if ($self->server_timeout == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->server_timeout == 0) { } 0 0 0
elsif ($self->server_timeout > 0) { } 0 0 0
532 0 my $remain = 86400 - (time() % 86400);
533 0 $server->timeout($remain);
534 } elsif ($self->server_timeout > 0) {
535 0 $server->timeout($self->server_timeout);
536 }
537  
538 0 my $client = $server->accept();
539 0 ▶ if ($self->_serverloop) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_serverloop) { } 0 0 0
elsif (defined $client) { } 0 0 0
540 0 ▶ if (!defined $client) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $client) { } 0 0 0
elsif ($self->server_type eq 'fork') { } 0 0 0
elsif ($self->server_type eq 'thread') { } 0 0 0
541 0 ▶ if ($! =~ /timed out/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($! =~ /timed out/i) { } 0 0 0
542 0 $self->logit("# Timeout waiting for client connection (timeout: " . $self->server_timeout . "s)");
543 0 ▶ if ($self->server_timeout == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->server_timeout == 0) { } 0 0 0
544 0 $self->_serverloop(0);
545 } else {
546 0 my $func = $self->func_timeout;
547 0 ▶ $func->($self) if $func;
Branch: 1 branch
BranchTrueFalseTotal
if $func 0 0 0
548 }
549 } else {
550 0 $self->logit("# Error accepting client connection: $!", 0);
551 }
552 } elsif ($self->server_type eq 'fork') {
553 0 my $pid = fork;
554 0 ▶ die "fork: $!" unless defined $pid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 0 0
555 0 ▶ if ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid) { } 0 0 0
556 0 close $client;
557 } else {
558 0 close $server;
559 0 $self->_handle_client($client);
560 0 exit 0;
561 }
562 } elsif ($self->server_type eq 'thread') {
563 0 ▶ while (scalar(@$threads) >= $self->max_threads) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @$threads >= $self->max_threads) 0 0 0
564 0 $threads = [ grep { $_->is_running() } @$threads ];
565 0 ▶ sleep 1 if scalar(@$threads) >= $self->max_threads;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @$threads >= $self->max_threads 0 0 0
566 }
567 0 ▶ my $thr = threads->create(sub { $self->_handle_client($client); threads->detach(); });
Subroutine __ANON__: not called CC=1 SCAR=6.9
568 0 push @$threads, $thr;
569 0 $threads = [ grep { $_->is_running() } @$threads ];
570 } else {
571 0 $self->_handle_client($client);
572 }
573 } elsif (defined $client) {
574 0 close($client);
575 }
576 }
577  
578 0 ▶ if ($self->server_type eq 'thread') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->server_type eq "thread") 0 0 0
579 0 $self->logit("# Shutting down threads...", 0);
580 0 for my $thr (@$threads) {
581 0 ▶ $thr->join() if $thr->is_running();
Branch: 1 branch
BranchTrueFalseTotal
if $thr->is_running 0 0 0
582 }
583 }
584  
585 0 close($server);
586 0 $self->_server(0);
587 0 return 1;
588 }
589  
590 0 ▶sub _signal_handler {
Subroutine _signal_handler: not called CC=4 SCAR=30.0
591 0 my ($self) = @_;
592 0 ▶ return unless defined $self->_serverloop;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->_serverloop 0 0 0
593 0 $self->_serverloop(0);
594 0 print STDERR "\n";
595 0 $self->logit("# Closing server loop and setting timeout to 0", 0);
596 0 ▶ if (defined $self->_server && $self->_server->can('timeout')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->_server and $self->_server->can("timeout")) 0 0 0
Condition0%0/3
defined $self->_server and $self->_server->can("timeout")
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->_server and $self->_server->can("timeout")
defined $self->_server $self->_server->can("timeout")
Truth table0%0/3
A and B
A= defined $self->_serverB= $self->_server->can("timeout")
ABresult
0X0
100
111
597 0 $self->_server->timeout(0);
598 }
599 }
600  
601 0 ▶sub _handle_client {
Subroutine _handle_client: not called CC=9 SCAR=45.0
602 0 my ($self, $client) = @_;
603  
604 0 my $clip = $client->peerhost();
605 0 my $clport = $client->peerport();
606  
607 0 ▶ if ($self->rate_limit_enabled) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->rate_limit_enabled) 0 0 0
608 0 my $block_info = $self->_is_blocked($clip);
609 0 ▶ if ($block_info) {
Branch: 1 branch
BranchTrueFalseTotal
if ($block_info) 0 0 0
610 0 $self->_send_rate_limit_response($client, $clip, $block_info);
611 0 return;
612 }
613  
614 0 ▶ unless ($self->_check_rate_limit($clip)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_check_rate_limit($clip)) 0 0 0
615 0 $self->_block_ip($clip, $self->rate_limit_block_duration);
616 0 $self->_send_rate_limit_response($client, $clip, {blocked => 1});
617 0 return;
618 }
619 }
620  
621 0 my %req = (clip => $clip, clport => $clport);
622 0 my $allow = $self->_checkhost(\%req);
623  
624 0 ▶ if ($allow eq 'deny') {
Branch: 1 branch
BranchTrueFalseTotal
if ($allow eq "deny") 0 0 0
625 0 close($client);
626 0 return;
627 }
628  
629 0 ▶ if (!($allow eq 'allow')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($allow eq "allow") 0 0 0
630 0 ▶ if (!$self->_checkauth(\%req)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_checkauth(\%req)) 0 0 0
631 0 $self->_send_unauthorized($client, $req{clip});
632 0 return;
633 }
634 }
635  
636 0 ▶ if ($self->server_http) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->server_http) { } 0 0 0
637 0 $self->_httpparse($client, \%req);
638 } else {
639 0 my $func = $self->func_perl;
640 0 ▶ $func->($self, $client, \%req) if $func;
Branch: 1 branch
BranchTrueFalseTotal
if $func 0 0 0
641 }
642  
643 0 close($client);
644 }
645  
646 0 ▶sub _checkhost {
Subroutine _checkhost: not called CC=8 SCAR=42.8
647 0 my ($self, $preq) = @_;
648  
649 0 ▶ return 'allow' if $self->server_deny == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $self->server_deny == 0 0 0 0
650  
651 0 my $bfn = $self->server_etc . '/' . $self->server_name . '_' . $preq->{clip};
652 0 ▶ return 'allow' if -f "$bfn.allow" || $preq->{clip} eq '127.0.0.1';
Branch: 1 branch
BranchTrueFalseTotal
if -f "$bfn.allow" or $preq->{"clip"} eq "127.0.0.1" 0 0 0
Condition0%0/3
-f "$bfn.allow" or $preq->{"clip"} eq "127.0.0.1"
l!l&&r!l&&!r
000
MC/DC0%0/2
-f "$bfn.allow" or $preq->{"clip"} eq "127.0.0.1"
-f "$bfn.allow" $preq->{"clip"} eq "127.0.0.1"
Truth table0%0/3
A or B
A= -f "$bfn.allow"B= $preq->{"clip"} eq "127.0.0.1"
ABresult
1X1
011
000
653 0 ▶ return 'deny' if -f "$bfn.deny";
Branch: 1 branch
BranchTrueFalseTotal
if -f "$bfn.deny" 0 0 0
654  
655 0 ▶ my $ext = $self->server_secure ? 'deny' : 'access';
Branch: 1 branch
BranchTrueFalseTotal
$self->server_secure ? : 0 0 0
656 0 my $fn = $bfn . '.' . $ext;
657  
658 0 ▶ if (!-f $fn) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $fn) 0 0 0
659 0 $self->logit(" TCP checkallow $fn");
660 0 ▶ if (open(my $tfp, '>', $fn)) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $tfp, '>', $fn) { } 0 0 0
661 0 my ($now_str, $now) = $self->_gettime();
662 0 print $tfp "$now access\n";
663 0 close($tfp);
664 0 chmod(0660, $fn);
665 } else {
666 0 $self->logit("# Error creating $fn: $!");
667 }
668 }
669 0 return $ext;
670 }
671  
672 0 ▶sub _checkauth {
Subroutine _checkauth: not called CC=7 SCAR=40.3
673 0 my ($self, $preq) = @_;
674  
675 0 ▶ return 1 unless $self->server_auth;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->server_auth 0 0 0
676  
677 0 my $client_key = '';
678 0 ▶ $client_key = $preq->{'X-API-KEY'} if exists $preq->{'X-API-KEY'};
Branch: 1 branch
BranchTrueFalseTotal
if exists $preq->{"X-API-KEY"} 0 0 0
679 (undef, $client_key) = split(/\s+/, $preq->{'AUTHORIZATION'}, 2)
680 0 ▶ if exists $preq->{'AUTHORIZATION'} && $preq->{'AUTHORIZATION'} =~ /^Basic /i;
Branch: 1 branch
BranchTrueFalseTotal
if exists $preq->{"AUTHORIZATION"} and $preq->{"AUTHORIZATION"} =~ /^Basic /i 0 0 0
Condition0%0/3
exists $preq->{"AUTHORIZATION"} and $preq->{"AUTHORIZATION"} =~ /^Basic /i
!ll&&!rl&&r
000
MC/DC0%0/2
exists $preq->{"AUTHORIZATION"} and $preq->{"AUTHORIZATION"} =~ /^Basic /i
exists $preq->{"AUTHORIZATION"} $preq->{"AUTHORIZATION"} =~ /^Basic /i
Truth table0%0/3
A and B
A= exists $preq->{"AUTHORIZATION"}B= $preq->{"AUTHORIZATION"} =~ /^Basic /i
ABresult
0X0
100
111
681  
682 0 ▶ if ($client_key ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($client_key ne "") 0 0 0
683 0 $client_key = lc($client_key);
684 0 my %valid_keys = map { $_ => 1 } @{$self->server_keys};
685 0 ▶ if (exists $valid_keys{$client_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $valid_keys{$client_key}) 0 0 0
686 0 $self->logit("# Authenticated: using $client_key");
687 0 return 1;
688 }
689 }
690  
691 0 $self->logit("# Authentication failed: No valid X-API-Key or Basic Auth", 1);
692 0 return 0;
693 }
694  
695 0 ▶sub _send_unauthorized {
Subroutine _send_unauthorized: not called CC=1 SCAR=6.9
696 0 my ($self, $client, $clip) = @_;
697  
698 0 my $response = "HTTP/1.1 401 Unauthorized\r\n";
699 0 $response .= "WWW-Authenticate: Basic realm=\"Restricted Area\"\r\n";
700 0 $response .= "Content-Type: text/plain\r\n";
701 0 $response .= "Content-Length: 33\r\n";
702 0 $response .= "Connection: close\r\n";
703 0 $response .= "\r\n";
704 0 $response .= "Error 401: Authentication required";
705  
706 0 print $client $response;
707 }
708  
709 0 ▶sub _httpparse {
Subroutine _httpparse: not called CC=31 SCAR=69.0
710 0 my ($self, $client, $preq) = @_;
711  
712 0 my $clip = $client->peerhost();
713 0 my $clport = $client->peerport();
714 0 my $request = $self->_httprequest($client);
715  
716 0 ▶ return if !defined $request;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $request 0 0 0
717  
718 0 ▶ $self->logit("invalid request uri_fn=$request->{URI_FN}") if $self->server_perlonly == 0 && $request->{URI_VALID} == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $self->server_perlonly == 0 and $request->{"URI_VALID"} == 0 0 0 0
Condition0%0/3
$self->server_perlonly == 0 and $request->{"URI_VALID"} == 0
!ll&&!rl&&r
000
MC/DC0%0/2
$self->server_perlonly == 0 and $request->{"URI_VALID"} == 0
$self->server_perlonly == 0 $request->{"URI_VALID"} == 0
Truth table0%0/3
A and B
A= $self->server_perlonly == 0B= $request->{"URI_VALID"} == 0
ABresult
0X0
100
111
719  
720 0 ▶ if ($self->verbose >= 3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->verbose >= 3) 0 0 0
721 0 for my $key (sort keys %$request) {
722 0 $self->logit("- RECV HDR $key : $request->{$key}");
723 }
724 }
725  
726 0 ▶ $clip = $request->{'X-REAL-IP'} if exists $request->{'X-REAL-IP'};
Branch: 1 branch
BranchTrueFalseTotal
if exists $request->{"X-REAL-IP"} 0 0 0
727 0 ▶ $clip = $request->{'X-FORWARDED-FOR'} if exists $request->{'X-FORWARDED-FOR'};
Branch: 1 branch
BranchTrueFalseTotal
if exists $request->{"X-FORWARDED-FOR"} 0 0 0
728 0 $request->{clip} = $clip;
729 0 $request->{clport} = $clport;
730  
731 0 my $allowed = $self->_checkhost($request);
732  
733 0 ▶ if ($allowed eq 'deny') {
Branch: 1 branch
BranchTrueFalseTotal
if ($allowed eq "deny") 0 0 0
734 0 $request->{sStatus} = "403 Forbidden";
735 0 $request->{sReturn} = "Error 403: Access denied for $clip";
736 0 $self->logit("# Access denied: Denied by host check for $clip", 1);
737 0 $self->_httperror($client, $request);
738 0 return;
739 }
740  
741 0 ▶ if ($request->{METHOD} eq '' || !defined $request->{URI_FN}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request->{"METHOD"} eq "" or not defined $request->{"URI_FN"}) 0 0 0
Condition0%0/3
$request->{"METHOD"} eq "" or not defined $request->{"URI_FN"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$request->{"METHOD"} eq "" or not defined $request->{"URI_FN"}
$request->{"METHOD"} eq "" not defined $request->{"URI_FN"}
Truth table0%0/3
A or not(B)
A= $request->{"METHOD"} eq ""B= not defined $request->{"URI_FN"}
ABresult
1X1
011
000
742 0 $request->{sStatus} = "403 Forbidden";
743 0 $request->{sReturn} = "Error 403: Access denied for $clip";
744 0 $self->logit("# Access denied: Denied by host check for $clip", 1);
745 0 return $self->_httperror($client, $request);
746 }
747  
748 0 $self->logit("- FROM IP : $clip:$clport", 3);
749  
750 0 ▶ if ($self->verbose == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->verbose == 2) 0 0 0
751 0 $self->logit("- --------- RAW HEADER DATA:\n$request->{RAW_DATA}");
752 }
753  
754 0 my ($stat, $len);
755 0 my $fn = $self->server_dir . $request->{URI_FN};
756 0 my $func = $self->func_perl;
757  
758 0 ▶ my $uri_fn = $request->{URI_FN} || '';
Condition0%0/2
$request->{'URI_FN'} || ''
l!l
00
MC/DC0%0/1
$request->{'URI_FN'} || ''
$request->{'URI_FN'}
Truth table0%0/2
A
A= $request->{'URI_FN'}
Aresult
11
00
759  
760 0 ▶ if ($uri_fn eq '/upload' || $uri_fn eq '/upload/' || $uri_fn eq '/api/upload') {
Branch: 4 branches
BranchTrueFalseTotal
if ($uri_fn eq '/upload' or $uri_fn eq '/upload/' or $uri_fn eq '/api/upload') { } 0 0 0
elsif ($self->server_cgi and $request->{'URI_VALID'} and index($self->server_cgiext, $request->{'URI_EXT'}) != -1) { } 0 0 0
elsif ($request->{'URI_VALID'} and -f $fn and $self->server_perlonly == 0 and $self->server_fnext eq '' || index($self->server_fnext, $request->{'URI_EXT'}) != -1) { } 0 0 0
elsif ($func) { } 0 0 0
Condition0%0/6
$uri_fn eq "/upload" or $uri_fn eq "/upload/" or $uri_fn eq "/api/upload"
l!l&&r!l&&!r
000
$uri_fn eq "/upload" or $uri_fn eq "/upload/"
l!l&&r!l&&!r
000
MC/DC0%0/3
$uri_fn eq "/upload" or $uri_fn eq "/upload/" or $uri_fn eq "/api/upload"
$uri_fn eq "/upload" $uri_fn eq "/upload/" $uri_fn eq "/api/upload"
Truth table0%0/4
A or B or C
A= $uri_fn eq "/upload"B= $uri_fn eq "/upload/"C= $uri_fn eq "/api/upload"
ABCresult
1XX1
01X1
0011
0000
761 0 ▶ if ($request->{METHOD} eq 'POST' && $request->{UPLOADS}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($request->{'METHOD'} eq 'POST' and $request->{'UPLOADS'}) { } 0 0 0
elsif ($request->{'METHOD'} eq 'GET') { } 0 0 0
Condition0%0/3
$request->{"METHOD"} eq "POST" and $request->{"UPLOADS"}
!ll&&!rl&&r
000
MC/DC0%0/2
$request->{"METHOD"} eq "POST" and $request->{"UPLOADS"}
$request->{"METHOD"} eq "POST" $request->{"UPLOADS"}
Truth table0%0/3
A and B
A= $request->{"METHOD"} eq "POST"B= $request->{"UPLOADS"}
ABresult
0X0
100
111
762 0 ($stat, $len) = $self->_handle_upload($client, $request);
763 0 return;
764 } elsif ($request->{METHOD} eq 'GET') {
765 0 ($stat, $len) = $self->_send_upload_form($client);
766 } else {
767 0 ($stat, $len) = $self->_send_upload_response($client, 405, 'Method Not Allowed. Use GET to see form, POST to upload.');
768 }
769 ▶ } elsif ($self->server_cgi && $request->{URI_VALID} && index($self->server_cgiext, $request->{URI_EXT}) >= 0) {
Condition0%0/6
$self->server_cgi and $request->{"URI_VALID"} and index($self->server_cgiext, $request->{"URI_EXT"}) != -1
!ll&&!rl&&r
000
$self->server_cgi and $request->{"URI_VALID"}
!ll&&!rl&&r
000
MC/DC0%0/3
$self->server_cgi and $request->{"URI_VALID"} and index($self->server_cgiext, $request->{"URI_EXT"}) != -1
$self->server_cgi $request->{"URI_VALID"} index($self->server_cgiext, $request->{"URI_EXT"}) != -1
Truth table0%0/4
A and B and C
A= $self->server_cgiB= $request->{"URI_VALID"}C= index($self->server_cgiext, $request->{"URI_EXT"}) != -1
ABCresult
0XX0
10X0
1100
1111
770 0 ($stat, $len) = $self->_cgiexec($client, $request);
771 ▶ } elsif ($request->{URI_VALID} && -f $fn && $self->server_perlonly == 0 &&
Condition0%0/12
$request->{"URI_VALID"} and -f $fn and $self->server_perlonly == 0 and $self->server_fnext eq "" || index($self->server_fnext, $request->{"URI_EXT"}) != -1
!ll&&!rl&&r
000
$request->{"URI_VALID"} and -f $fn and $self->server_perlonly == 0
!ll&&!rl&&r
000
$request->{"URI_VALID"} and -f $fn
!ll&&!rl&&r
000
$self->server_fnext eq "" or index($self->server_fnext, $request->{"URI_EXT"}) != -1
l!l&&r!l&&!r
000
MC/DC0%0/5
$request->{"URI_VALID"} and -f $fn and $self->server_perlonly == 0 and $self->server_fnext eq "" || index($self->server_fnext, $request->{"URI_EXT"}) != -1
$request->{"URI_VALID"} -f $fn $self->server_perlonly == 0 $self->server_fnext eq "" index($self->server_fnext, $request->{"URI_EXT"}) != -1
Truth table0%0/6
A and B and C and D or E
A= $request->{"URI_VALID"}B= -f $fnC= $self->server_perlonly == 0D= $self->server_fnext eq ""E= index($self->server_fnext, $request->{"URI_EXT"}) != -1
ABCDEresult
0XXXX0
10XXX0
110XX0
111000
1111X1
111011
772 ($self->server_fnext eq '' || index($self->server_fnext, $request->{URI_EXT}) >= 0)) {
773 0 ($stat, $len) = $self->_httpfn($client, $request);
774 } elsif ($func) {
775 0 ($stat, $len) = $func->($self, $client, $request);
776 } else {
777 0 ($stat, $len) = $self->_httperror($client, $request);
778 }
779  
780 0 ▶ if ($self->logfn ne '' || $self->verbose) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->logfn ne "" or $self->verbose) 0 0 0
Condition0%0/3
$self->logfn ne "" or $self->verbose
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->logfn ne "" or $self->verbose
$self->logfn ne "" $self->verbose
Truth table0%0/3
A or B
A= $self->logfn ne ""B= $self->verbose
ABresult
1X1
011
000
781 0 $self->logit("$clip - $request->{METHOD} \"$request->{URI}\" $stat $len", 1);
782 }
783  
784 0 $func = $self->func_done;
785 0 ▶ $func->($self, $request) if $func;
Branch: 1 branch
BranchTrueFalseTotal
if $func 0 0 0
786 }
787  
788 0 ▶sub _httprequest {
Subroutine _httprequest: not called CC=21 SCAR=61.4
789 0 my ($self, $client) = @_;
790  
791 0 my %request = (
792 QUERY_STRING => '',
793 METHOD => '',
794 CONTENT_LENGTH => 0,
795 CONTENT_DATA => '',
796 RAW_DATA => ''
797 );
798 0 $ENV{QUERY_STRING} = '';
799 0 $ENV{REQUEST_METHOD} = '';
800  
801 0 $client->timeout(30);
802  
803 0 eval {
804 0 ▶ local $SIG{ALRM} = sub { die "timeout\n" };
Subroutine __ANON__: not called CC=1 SCAR=6.9
805 0 alarm(30);
806 0 ▶ while (<$client>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $client)) 0 0 0
807 0 ▶ if (!defined($_)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $_) 0 0 0
808 0 $self->logit("# Error: Client $client->peerhost() disconnected or read failed: $!", 1);
809 0 last;
810 }
811 0 $request{RAW_DATA} .= $_;
812 0 s/[\r\n\s]+$//;
813 0 ▶ print STDERR " $_\n" if $self->verbose > 2 && $_ ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose > 2 and $_ ne "" 0 0 0
Condition0%0/3
$self->verbose > 2 and $_ ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
$self->verbose > 2 and $_ ne ""
$self->verbose > 2 $_ ne ""
Truth table0%0/3
A and B
A= $self->verbose > 2B= $_ ne ""
ABresult
0X0
100
111
814 0 ▶ if (/\s*(\w+)\s*([^\s]+)\s*HTTP\/(\d.\d)/) {
Branch: 3 branches
BranchTrueFalseTotal
if (m[\s*(\w+)\s*([^\s]+)\s*HTTP/(\d.\d)]) { } 0 0 0
elsif (/:/) { } 0 0 0
elsif (/^$/) { } 0 0 0
815 0 $ENV{REQUEST_METHOD} = uc($1);
816 0 ▶ $request{METHOD} = $ENV{REQUEST_METHOD} || 'GET';
Condition0%0/2
$ENV{'REQUEST_METHOD'} || 'GET'
l!l
00
MC/DC0%0/1
$ENV{'REQUEST_METHOD'} || 'GET'
$ENV{'REQUEST_METHOD'}
Truth table0%0/2
A
A= $ENV{'REQUEST_METHOD'}
Aresult
11
00
817 0 $self->_httpuri(\%request, $2);
818 0 ▶ $request{HTTP_VERSION} = $3 || '1.0';
Condition0%0/2
$3 || '1.0'
l!l
00
MC/DC0%0/1
$3 || '1.0'
$3
Truth table0%0/2
A
A= $3
Aresult
11
00
819 } elsif (/:/) {
820 0 my ($nm, $val) = split /\s*:\s*/, $_, 2;
821 0 $nm =~ s/^\s+//;
822 0 ▶ $request{uc($nm)} = $val if $val ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $val ne "" 0 0 0
823 } elsif (/^$/) {
824 0 ▶ my $len = $request{'CONTENT-LENGTH'} || 0;
Condition0%0/2
$request{'CONTENT-LENGTH'} || 0
l!l
00
MC/DC0%0/1
$request{'CONTENT-LENGTH'} || 0
$request{'CONTENT-LENGTH'}
Truth table0%0/2
A
A= $request{'CONTENT-LENGTH'}
Aresult
11
00
825 0 ▶ $len = $self->http_postlimit if $self->http_postlimit && $len > $self->http_postlimit;
Branch: 1 branch
BranchTrueFalseTotal
if $self->http_postlimit and $len > $self->http_postlimit 0 0 0
Condition0%0/3
$self->http_postlimit and $len > $self->http_postlimit
!ll&&!rl&&r
000
MC/DC0%0/2
$self->http_postlimit and $len > $self->http_postlimit
$self->http_postlimit $len > $self->http_postlimit
Truth table0%0/3
A and B
A= $self->http_postlimitB= $len > $self->http_postlimit
ABresult
0X0
100
111
826 0 $ENV{CONTENT_LENGTH} = $len;
827 0 $request{CONTENT_LENGTH} = $len;
828 0 ▶ if ($len > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len > 0) 0 0 0
829 0 ▶ my $content_type = $request{'CONTENT-TYPE'} || '';
Condition0%0/2
$request{'CONTENT-TYPE'} || ''
l!l
00
MC/DC0%0/1
$request{'CONTENT-TYPE'} || ''
$request{'CONTENT-TYPE'}
Truth table0%0/2
A
A= $request{'CONTENT-TYPE'}
Aresult
11
00
830 0 ▶ if ($content_type =~ /multipart\/form-data/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content_type =~ m[multipart/form-data]i) { } 0 0 0
831 0 read($client, $request{CONTENT_DATA}, $len);
832 0 ▶ if (my $boundary = $self->_extract_boundary($content_type)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $boundary = $self->_extract_boundary($content_type)) 0 0 0
833 0 my $uploads = $self->_parse_multipart($boundary, $request{CONTENT_DATA});
834 0 ▶ $request{UPLOADS} = $uploads if @$uploads;
Branch: 1 branch
BranchTrueFalseTotal
if @$uploads 0 0 0
835 0 ▶ $request{CONTENT_DATA} = '' if $request{UPLOADS};
Branch: 1 branch
BranchTrueFalseTotal
if $request{"UPLOADS"} 0 0 0
836 }
837 } else {
838 0 read($client, $request{CONTENT_DATA}, $len);
839 }
840 }
841 0 last;
842 } else {
843 0 last;
844 }
845 }
846 0 alarm(0);
847 };
848  
849 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
850 0 $self->logit("# Error: Client request timed out or failed: $@");
851 0 $request{sStatus} = "408 Request Timeout";
852 0 $request{sReturn} = "Error 408: Request timed out";
853 0 $request{sContentType} = $self->_httpcontent('txt');
854 0 $self->_reply($client, \%request);
855 0 return undef;
856 }
857  
858 0 return \%request;
859 }
860  
861 0 ▶sub _httpuri {
Subroutine _httpuri: not called CC=9 SCAR=45.0
862 0 my ($self, $preq, $uri) = @_;
863  
864 0 ▶ $preq->{URI} = $uri || '';
Condition0%0/2
$uri || ''
l!l
00
MC/DC0%0/1
$uri || ''
$uri
Truth table0%0/2
A
A= $uri
Aresult
11
00
865 0 $preq->{URI_FN} = $uri;
866 0 $preq->{URI_PARAMS} = '';
867 0 ▶ ($preq->{URI_FN}, $preq->{URI_PARAMS}) = split(/[?]/, $uri, 2) if index($uri, '?') > 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($uri, "?") > 0 0 0 0
868 0 ▶ $preq->{URI_FN} .= 'index.html' if substr($preq->{URI_FN}, -1) eq '/';
Branch: 1 branch
BranchTrueFalseTotal
if substr($preq->{"URI_FN"}, -1) eq "/" 0 0 0
869 0 my @flds = split(/\./, $preq->{URI_FN});
870 0 $preq->{URI_EXT} = '';
871 0 ▶ $preq->{URI_EXT} = pop @flds if $#flds > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $#flds > 0 0 0 0
872 0 $preq->{URI_VALID} = 0;
873 0 ▶ $preq->{URI_VALID} = 1 if $#flds == 0 && $preq->{URI_EXT} ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $#flds == 0 and $preq->{"URI_EXT"} ne "" 0 0 0
Condition0%0/3
$#flds == 0 and $preq->{"URI_EXT"} ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
$#flds == 0 and $preq->{"URI_EXT"} ne ""
$#flds == 0 $preq->{"URI_EXT"} ne ""
Truth table0%0/3
A and B
A= $#flds == 0B= $preq->{"URI_EXT"} ne ""
ABresult
0X0
100
111
874 0 ▶ $preq->{URI_VALID} = 0 if $preq->{URI_FN} =~ /[\\\!\$+\%<;:]/ || $preq->{URI_FN} =~ /\.\./;
Branch: 1 branch
BranchTrueFalseTotal
if $preq->{"URI_FN"} =~ /[\\\!\$+\%<;:]/ or $preq->{"URI_FN"} =~ /\.\./ 0 0 0
Condition0%0/3
$preq->{"URI_FN"} =~ /[\\\!\$+\%<;:]/ or $preq->{"URI_FN"} =~ /\.\./
l!l&&r!l&&!r
000
MC/DC0%0/2
$preq->{"URI_FN"} =~ /[\\\!\$+\%<;:]/ or $preq->{"URI_FN"} =~ /\.\./
$preq->{"URI_FN"} =~ /[\\\!\$+\%<;:]/ $preq->{"URI_FN"} =~ /\.\./
Truth table0%0/3
A or B
A= $preq->{"URI_FN"} =~ /[\\\!\$+\%<;:]/B= $preq->{"URI_FN"} =~ /\.\./
ABresult
1X1
011
000
875 0 $ENV{QUERY_STRING} = $preq->{URI_PARAMS};
876 0 $preq->{QUERY_STRING} = $preq->{URI_PARAMS};
877 }
878  
879 0 ▶sub _httpcontent {
Subroutine _httpcontent: not called CC=3 SCAR=24.8
880 0 my ($self, $ext) = @_;
881  
882 0 my %MIMETYPE = (
883 "txt" => "text/plain", "html" => "text/html", "htm" => "text/html", "css" => "text/css",
884 "jpg" => "image/jpeg", "jpeg" => "image/jpeg", "gz" => "application/gzip", "zip" => "application/zip",
885 "gif" => "image/gif", "mp3" => "audio/mpeg", "ico" => "image/x-icon", "xml" => "text/xml",
886 "png" => "image/png", "tar" => "application/tar", "js" => "text/javascript"
887 );
888  
889 0 my $typ = $MIMETYPE{txt};
890 0 ▶ $typ = $MIMETYPE{$ext} if $ext ne 'txt' && exists $MIMETYPE{$ext};
Branch: 1 branch
BranchTrueFalseTotal
if $ext ne "txt" and exists $MIMETYPE{$ext} 0 0 0
Condition0%0/3
$ext ne "txt" and exists $MIMETYPE{$ext}
!ll&&!rl&&r
000
MC/DC0%0/2
$ext ne "txt" and exists $MIMETYPE{$ext}
$ext ne "txt" exists $MIMETYPE{$ext}
Truth table0%0/3
A and B
A= $ext ne "txt"B= exists $MIMETYPE{$ext}
ABresult
0X0
100
111
891 0 return $typ;
892 }
893  
894 0 ▶sub _cgiexec {
Subroutine _cgiexec: not called CC=13 SCAR=52.0
895 0 my ($self, $client, $preq) = @_;
896  
897 0 $preq->{sStatus} = "400 Not Found";
898 0 $preq->{sReturn} = "Error 400: File not found ($preq->{URI_FN})";
899 0 $preq->{sContentType} = 'text/plain';
900 0 $preq->{opthead} = '';
901 0 $preq->{len} = 0;
902  
903 0 my $fn = $self->server_dir . $preq->{URI_FN};
904  
905 0 ▶ if ($preq->{URI_VALID} && -f $fn) {
Branch: 1 branch
BranchTrueFalseTotal
if ($preq->{"URI_VALID"} and -f $fn) 0 0 0
Condition0%0/3
$preq->{"URI_VALID"} and -f $fn
!ll&&!rl&&r
000
MC/DC0%0/2
$preq->{"URI_VALID"} and -f $fn
$preq->{"URI_VALID"} -f $fn
Truth table0%0/3
A and B
A= $preq->{"URI_VALID"}B= -f $fn
ABresult
0X0
100
111
906 0 ▶ if ($fn =~ /\.\./ || index($fn, '..') >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn =~ /\.\./ or index($fn, "..") != -1) 0 0 0
Condition0%0/3
$fn =~ /\.\./ or index($fn, "..") != -1
l!l&&r!l&&!r
000
MC/DC0%0/2
$fn =~ /\.\./ or index($fn, "..") != -1
$fn =~ /\.\./ index($fn, "..") != -1
Truth table0%0/3
A or B
A= $fn =~ /\.\./B= index($fn, "..") != -1
ABresult
1X1
011
000
907 0 $self->logit("# CGI Security: Path traversal attempt detected in $fn", 1);
908 0 $preq->{sStatus} = "403 Forbidden";
909 0 $preq->{sReturn} = "Error 403: Invalid CGI path";
910 0 return $self->_reply($client, $preq);
911 }
912  
913 0 my ($cgi_in, $cgi_out, $cgi_err);
914 0 my $pid;
915  
916 0 eval {
917 0 $pid = open3($cgi_in, $cgi_out, $cgi_err, $fn, "");
918 };
919  
920 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
921 0 $self->logit("# Error executing CGI $fn: $@");
922 0 $preq->{sStatus} = "500 Internal Server Error";
923 0 $preq->{sReturn} = "Error 500: CGI execution failed ($@)";
924 } else {
925 0 ▶ if ($preq->{METHOD} =~ /POST/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($preq->{"METHOD"} =~ /POST/i) 0 0 0
926 0 ▶ print $cgi_in $preq->{CONTENT_DATA} or $self->logit("# Error sending POST data to CGI: $!");
Branch: 1 branch
BranchTrueFalseTotal
print $cgi_in $preq->{"CONTENT_DATA"} or $self->logit("# Error sending POST data to CGI: $!") 0 0 0
927 }
928 0 close $cgi_in;
929 0 my $output = do { local $/; <$cgi_out> };
930 0 my $errors = do { local $/; <$cgi_err> };
931 0 close $cgi_out;
932 0 close $cgi_err;
933 0 waitpid($pid, 0);
934 0 my $exit_status = $? >> 8;
935  
936 0 ▶ if ($exit_status != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($exit_status != 0) { } 0 0 0
937 0 $self->logit("# CGI $fn failed with exit status $exit_status: $errors");
938 0 $preq->{sStatus} = "500 Internal Server Error";
939 0 $preq->{sReturn} = "Error 500: CGI script failed ($errors)";
940 } else {
941 0 my ($header, $body) = split(/\r?\n\r?\n/, $output, 2);
942 0 $preq->{sStatus} = '200 OK';
943 0 ▶ $preq->{sStatus} = '302 Found' if $output =~ /^\r?Status:\s+302/;
Branch: 1 branch
BranchTrueFalseTotal
if $output =~ /^\r?Status:\s+302/ 0 0 0
944 0 ▶ $preq->{sContentType} = '' if $output =~ m#^\r?Content-Type:.*?\r?\n\r?\n#mi || $preq->{sStatus} eq '302 Found';
Branch: 1 branch
BranchTrueFalseTotal
if $output =~ /^\r?Content-Type:.*?\r?\n\r?\n/im or $preq->{"sStatus"} eq "302 Found" 0 0 0
Condition0%0/3
$output =~ /^\r?Content-Type:.*?\r?\n\r?\n/im or $preq->{"sStatus"} eq "302 Found"
l!l&&r!l&&!r
000
MC/DC0%0/2
$output =~ /^\r?Content-Type:.*?\r?\n\r?\n/im or $preq->{"sStatus"} eq "302 Found"
$output =~ /^\r?Content-Type:.*?\r?\n\r?\n/im $preq->{"sStatus"} eq "302 Found"
Truth table0%0/3
A or B
A= $output =~ /^\r?Content-Type:.*?\r?\n\r?\n/imB= $preq->{"sStatus"} eq "302 Found"
ABresult
1X1
011
000
945 0 $preq->{opthead} = $header;
946 0 ▶ $preq->{sReturn} = $body if length($body);
Branch: 1 branch
BranchTrueFalseTotal
if length $body 0 0 0
947 0 return $self->_reply($client, $preq);
948 }
949 }
950 }
951  
952 0 return $self->_reply($client, $preq);
953 }
954  
955 0 ▶sub _httpfn {
Subroutine _httpfn: not called CC=11 SCAR=48.8
956 0 my ($self, $client, $preq) = @_;
957  
958 0 my $sStatus = '';
959 0 my $sReturn = '';
960 0 my $opthead = '';
961 0 my $sContentType = '';
962 0 my $len = 0;
963 0 my $fn = $self->server_dir . $preq->{URI_FN};
964  
965 0 ▶ if ($preq->{URI_VALID} && -f $fn) {
Branch: 1 branch
BranchTrueFalseTotal
if ($preq->{'URI_VALID'} and -f $fn) { } 0 0 0
Condition0%0/3
$preq->{"URI_VALID"} and -f $fn
!ll&&!rl&&r
000
MC/DC0%0/2
$preq->{"URI_VALID"} and -f $fn
$preq->{"URI_VALID"} -f $fn
Truth table0%0/3
A and B
A= $preq->{"URI_VALID"}B= -f $fn
ABresult
0X0
100
111
966 0 ▶ if ($fn =~ /\.\./ || index($fn, '..') >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn =~ /\.\./ or index($fn, "..") != -1) 0 0 0
Condition0%0/3
$fn =~ /\.\./ or index($fn, "..") != -1
l!l&&r!l&&!r
000
MC/DC0%0/2
$fn =~ /\.\./ or index($fn, "..") != -1
$fn =~ /\.\./ index($fn, "..") != -1
Truth table0%0/3
A or B
A= $fn =~ /\.\./B= index($fn, "..") != -1
ABresult
1X1
011
000
967 0 $self->logit("# Security: Path traversal attempt detected in $fn", 1);
968 0 $sStatus = "403 Forbidden";
969 0 $sReturn = "Error 403: Invalid path";
970 0 $preq->{sContentType} = $self->_httpcontent('txt');
971 0 $preq->{sStatus} = $sStatus;
972 0 $preq->{sReturn} = $sReturn;
973 0 $preq->{len} = length($sReturn);
974 0 return $self->_reply($client, $preq);
975 }
976  
977 0 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fn);
978 0 my $mtime_str = gmtime $mtime;
979 0 my ($day, $mon, $dm, $tm, $yr) = ($mtime_str =~ m/(...) (...) (..) (..:..:..) (....)/);
980 0 $opthead = "Last-Modified: $day, $dm $mon $yr $tm GMT";
981  
982 0 ▶ if (-r $fn) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $fn) { } 0 0 0
983 0 ▶ if (open(my $fh, '<', $fn)) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, '<', $fn) { } 0 0 0
984 0 binmode($fh);
985 0 $len = $size;
986 0 my $bytes_read = read($fh, $sReturn, $len);
987 0 ▶ if (!defined $bytes_read) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $bytes_read) { } 0 0 0
elsif ($preq->{'METHOD'} eq 'GET') { } 0 0 0
elsif ($preq->{'METHOD'} eq 'HEAD') { } 0 0 0
988 0 $self->logit("# Error reading file $fn: $!");
989 0 $sStatus = "500 Internal Server Error";
990 0 $sReturn = "Error 500: Failed to read file";
991 } elsif ($preq->{METHOD} eq 'GET') {
992 0 $sStatus = "200 OK";
993 } elsif ($preq->{METHOD} eq 'HEAD') {
994 0 $sReturn = '';
995 0 $sStatus = "200 OK";
996 }
997 0 close($fh);
998 } else {
999 0 $self->logit("# Error opening file $fn: $!");
1000 0 $sStatus = "500 Internal Server Error";
1001 0 $sReturn = "Error 500: Unable to open file";
1002 }
1003 } else {
1004 0 $self->logit("# Error: File $fn is not readable or accessible");
1005 0 $sStatus = "403 Forbidden";
1006 0 $sReturn = "Error 403: File access denied";
1007 }
1008 } else {
1009 0 $sStatus = "404 Not Found";
1010 0 $sReturn = "Error 404: File not found ($fn)";
1011 }
1012  
1013 0 ▶ $sContentType = $self->_httpcontent(lc($preq->{URI_EXT})) if $sContentType eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $sContentType eq "" 0 0 0
1014 0 $preq->{sContentType} = $sContentType;
1015 0 $preq->{sStatus} = $sStatus;
1016 0 $preq->{opthead} = $opthead;
1017 0 $preq->{sReturn} = $sReturn;
1018 0 $preq->{len} = $len;
1019  
1020 0 return $self->_reply($client, $preq);
1021 }
1022  
1023 0 ▶sub _httperror {
Subroutine _httperror: not called CC=6 SCAR=37.4
1024 0 my ($self, $client, $preq) = @_;
1025  
1026 0 ▶ $preq->{sContentType} = $self->_httpcontent('txt') if not exists $preq->{sContentType};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $preq->{"sContentType"} 0 0 0
1027 0 ▶ $preq->{opthead} = '' if not exists $preq->{opthead};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $preq->{"opthead"} 0 0 0
1028  
1029 0 ▶ if ($preq->{sStatus} eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($preq->{"sStatus"} eq "") 0 0 0
1030 0 $preq->{sStatus} = "400 Not Found";
1031 0 $preq->{sReturn} = "Error 400: File not found ($preq->{URI_FN})";
1032 }
1033  
1034 0 ▶ $preq->{len} = length($preq->{sReturn}) if not exists $preq->{len} || $preq->{len} == 0;
Branch: 1 branch
BranchTrueFalseTotal
unless exists $preq->{"len"} or $preq->{"len"} == 0 0 0 0
Condition0%0/3
exists $preq->{"len"} or $preq->{"len"} == 0
l!l&&r!l&&!r
000
MC/DC0%0/2
exists $preq->{"len"} or $preq->{"len"} == 0
exists $preq->{"len"} $preq->{"len"} == 0
Truth table0%0/3
A or B
A= exists $preq->{"len"}B= $preq->{"len"} == 0
ABresult
1X1
011
000
1035  
1036 0 return $self->_reply($client, $preq);
1037 }
1038  
1039 0 ▶sub _reply {
Subroutine _reply: not called CC=10 SCAR=47.0
1040 0 my ($self, $client, $preq) = @_;
1041  
1042 0 ▶ $preq->{sContentType} = 'text/plain' if not exists $preq->{sContentType};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $preq->{"sContentType"} 0 0 0
1043 0 ▶ $preq->{len} = length($preq->{sReturn}) if not exists $preq->{len} || $preq->{len} == 0;
Branch: 1 branch
BranchTrueFalseTotal
unless exists $preq->{"len"} or $preq->{"len"} == 0 0 0 0
Condition0%0/3
exists $preq->{"len"} or $preq->{"len"} == 0
l!l&&r!l&&!r
000
MC/DC0%0/2
exists $preq->{"len"} or $preq->{"len"} == 0
exists $preq->{"len"} $preq->{"len"} == 0
Truth table0%0/3
A or B
A= exists $preq->{"len"}B= $preq->{"len"} == 0
ABresult
1X1
011
000
1044  
1045 0 my @aheaders = ("HTTP/1.1 $preq->{sStatus}");
1046 0 ▶ push(@aheaders, "Server: $self->{server_name}") if $self->server_name ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $self->server_name ne "" 0 0 0
1047 0 push(@aheaders, "Connection: close");
1048 0 ▶ push(@aheaders, "Content-Type: $preq->{sContentType}") if $preq->{sContentType} ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $preq->{"sContentType"} ne "" 0 0 0
1049 0 ▶ push(@aheaders, $preq->{opthead}) if $preq->{opthead} ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $preq->{"opthead"} ne "" 0 0 0
1050 0 push(@aheaders, "Content-Length: $preq->{len}");
1051  
1052 0 eval {
1053 0 ▶ local $SIG{PIPE} = sub { die "Broken pipe\n" };
Subroutine __ANON__: not called CC=1 SCAR=6.9
1054 print $client join("\r\n", @aheaders) . "\r\n\r\n" . $preq->{sReturn}
1055 0 ▶ or die "Write failed: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
print $client join("\r\n", @aheaders) . "\r\n\r\n" . $preq->{"sReturn"} or die "Write failed: $!\n" 0 0 0
1056 };
1057  
1058 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1059 0 $self->logit("# Error sending response to client $preq->{clip}: $@");
1060 }
1061  
1062 0 close($client);
1063  
1064 0 ▶ if ($self->verbose > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->verbose > 2) 0 0 0
1065 0 print STDERR "# reply header:\n";
1066 0 print STDERR " " . join("\n ", @aheaders) . "\n";
1067 }
1068  
1069 0 $self->logit("status=$preq->{sStatus} type=$preq->{sContentType} len=$preq->{len} $preq->{opthead}");
1070  
1071 0 my $stat = substr($preq->{sStatus}, 0, 3);
1072 0 $preq->{stat} = $stat;
1073  
1074 0 return ($stat, $preq->{len});
1075 }
1076  
1077 7 ▶sub logit {
Subroutine logit: called CC=8 SCAR=37.8
Pod documented
1078 7 my ($self, $msg, $lvl) = @_;
1079  
1080 7 ▶ $lvl = 2 if !defined $lvl || $lvl eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $lvl or $lvl eq "" 0 7 7
Condition33%1/3
not defined $lvl or $lvl eq ""
l!l&&r!l&&!r
007
MC/DC0%0/2
not defined $lvl or $lvl eq ""
not defined $lvl $lvl eq ""
Truth table33%1/3
not(A) or B
A= not defined $lvlB= $lvl eq ""
ABresult
1X1
011
000
1081 7 ▶ return if $lvl > $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $lvl > $self->verbose 7 0 7
1082  
1083 0 lock ${ $self->_log_lock };
1084  
1085 0 my $func_log = $self->func_log;
1086 0 ▶ if ($func_log) {
Branch: 1 branch
BranchTrueFalseTotal
if ($func_log) 0 0 0
1087 0 $func_log->($self, $msg, $lvl);
1088 0 return;
1089 }
1090  
1091 0 ▶ if ($self->logfn ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->logfn ne "") 0 0 0
1092 0 my ($timestr) = $self->_gettime();
1093 0 $timestr =~ s/-//g;
1094 0 my $logline = substr($timestr, 2) . " $msg\n";
1095  
1096 0 my $logfn = $self->logfn;
1097 0 my $tmpfn = $logfn . '.tmp.' . $$ . '.' . time() . '.' . int(rand(1000000));
1098  
1099 0 ▶ if (open(my $tmpfp, '>', $tmpfn)) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $tmpfp, ">", $tmpfn) 0 0 0
1100 0 print $tmpfp $logline;
1101 0 close($tmpfp);
1102 0 ▶ rename($tmpfn, $logfn) or unlink($tmpfn);
Branch: 1 branch
BranchTrueFalseTotal
rename $tmpfn, $logfn or unlink $tmpfn 0 0 0
1103 }
1104 }
1105 }
1106  
1107 0 ▶sub _gettime {
Subroutine _gettime: not called CC=1 SCAR=6.9
1108 0 my ($self) = @_;
1109  
1110 0 my $now = time();
1111 0 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($now);
1112 0 my $tstr = sprintf "%04d-%02d-%02d %02d:%02d:%02d", 1900 + $year, $mon + 1, $mday, $hour, $min, $sec;
1113 0 return ($tstr, $now);
1114 }
1115  
1116 0 ▶sub stop {
Subroutine stop: not called CC=1 SCAR=6.9
Pod documented
1117 0 my ($self) = @_;
1118 0 $self->_serverloop(0);
1119 }
1120  
1121 0 ▶sub is_running {
Subroutine is_running: not called CC=2 SCAR=17.9
Pod documented
1122 0 my ($self) = @_;
1123 0 ▶ return $self->_serverloop ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->_serverloop ? : 0 0 0
1124 }
1125  
1126 54 ▶sub validate_config {
Subroutine validate_config: called CC=26 SCAR=36.2
Pod documented
1127 54 my $pCONF = shift;
1128  
1129 # Support both class method and function call styles
1130 # If first arg is a hashref, it's the config; otherwise it's the class name
1131 54 ▶ if (ref($pCONF) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $pCONF ne "HASH") 0 54 54
1132 0 $pCONF = shift;
1133 }
1134  
1135 54 ▶ return 'server_addr is required' unless defined $pCONF && ref($pCONF) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pCONF and ref $pCONF eq "HASH" 0 54 54
Condition33%1/3
defined $pCONF and ref $pCONF eq "HASH"
!ll&&!rl&&r
0054
MC/DC0%0/2
defined $pCONF and ref $pCONF eq "HASH"
defined $pCONF ref $pCONF eq "HASH"
Truth table33%1/3
A and B
A= defined $pCONFB= ref $pCONF eq "HASH"
ABresult
0X0
100
111
1136 54 ▶ return 'server_addr is required' unless defined $pCONF->{server_addr} && $pCONF->{server_addr} ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pCONF->{"server_addr"} and $pCONF->{"server_addr"} ne "" 6 48 54
Condition100%3/3
defined $pCONF->{"server_addr"} and $pCONF->{"server_addr"} ne ""
!ll&&!rl&&r
3348
MC/DC100%2/2
defined $pCONF->{"server_addr"} and $pCONF->{"server_addr"} ne ""
defined $pCONF->{"server_addr"} $pCONF->{"server_addr"} ne ""
Truth table100%3/3
A and B
A= defined $pCONF->{"server_addr"}B= $pCONF->{"server_addr"} ne ""
ABresult
0X0
100
111
1137 48 ▶ if ($pCONF->{server_addr} !~ /^[0-9.]+:\d+$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pCONF->{"server_addr"} =~ /^[0-9.]+:\d+$/) 3 45 48
1138 3 return 'server_addr must be in format IP:port (e.g., 0.0.0.0:8080)';
1139 }
1140  
1141 45 ▶ if (!defined $pCONF->{server_type} || $pCONF->{server_type} eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $pCONF->{"server_type"} or $pCONF->{"server_type"} eq "") 0 45 45
Condition33%1/3
not defined $pCONF->{"server_type"} or $pCONF->{"server_type"} eq ""
l!l&&r!l&&!r
0045
MC/DC0%0/2
not defined $pCONF->{"server_type"} or $pCONF->{"server_type"} eq ""
not defined $pCONF->{"server_type"} $pCONF->{"server_type"} eq ""
Truth table33%1/3
not(A) or B
A= not defined $pCONF->{"server_type"}B= $pCONF->{"server_type"} eq ""
ABresult
1X1
011
000
1142 0 return 'server_type is required';
1143 }
1144 45 ▶ if ($pCONF->{server_type} ne 'single' && $pCONF->{server_type} ne 'fork' && $pCONF->{server_type} ne 'thread') {
Branch: 1 branch
BranchTrueFalseTotal
if ($pCONF->{"server_type"} ne "single" and $pCONF->{"server_type"} ne "fork" and $pCONF->{"server_type"} ne "thread") 3 42 45
Condition83%5/6
$pCONF->{"server_type"} ne "single" and $pCONF->{"server_type"} ne "fork" and $pCONF->{"server_type"} ne "thread"
!ll&&!rl&&r
4203
$pCONF->{"server_type"} ne "single" and $pCONF->{"server_type"} ne "fork"
!ll&&!rl&&r
3663
MC/DC66%2/3
$pCONF->{"server_type"} ne "single" and $pCONF->{"server_type"} ne "fork" and $pCONF->{"server_type"} ne "thread"
$pCONF->{"server_type"} ne "single" $pCONF->{"server_type"} ne "fork" $pCONF->{"server_type"} ne "thread"
Truth table75%3/4
A and B and C
A= $pCONF->{"server_type"} ne "single"B= $pCONF->{"server_type"} ne "fork"C= $pCONF->{"server_type"} ne "thread"
ABCresult
0XX0
10X0
1100
1111
1145 3 return 'server_type must be single, fork, or thread';
1146 }
1147  
1148 42 ▶ if ($pCONF->{server_type} eq 'thread' && (!defined $pCONF->{max_threads} || $pCONF->{max_threads} <= 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pCONF->{"server_type"} eq "thread" and !defined($pCONF->{"max_threads"}) || $pCONF->{"max_threads"} <= 0) 0 42 42
Condition16%1/6
$pCONF->{"server_type"} eq "thread" and !defined($pCONF->{"max_threads"}) || $pCONF->{"max_threads"} <= 0
!ll&&!rl&&r
4200
not defined $pCONF->{"max_threads"} or $pCONF->{"max_threads"} <= 0
l!l&&r!l&&!r
000
MC/DC0%0/3
$pCONF->{"server_type"} eq "thread" and !defined($pCONF->{"max_threads"}) || $pCONF->{"max_threads"} <= 0
$pCONF->{"server_type"} eq "thread" not defined $pCONF->{"max_threads"} $pCONF->{"max_threads"} <= 0
Truth table25%1/4
A and not(B) or C
A= $pCONF->{"server_type"} eq "thread"B= not defined $pCONF->{"max_threads"}C= $pCONF->{"max_threads"} <= 0
ABCresult
0XX0
1000
11X1
1011
1149 0 return 'max_threads must be positive when server_type is thread';
1150 }
1151  
1152 42 ▶ if (defined $pCONF->{verbose} && ($pCONF->{verbose} < 0 || $pCONF->{verbose} > 3)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pCONF->{"verbose"} and $pCONF->{"verbose"} < 0 || $pCONF->{"verbose"} > 3) 6 36 42
Condition100%6/6
defined $pCONF->{"verbose"} and $pCONF->{"verbose"} < 0 || $pCONF->{"verbose"} > 3
!ll&&!rl&&r
22146
$pCONF->{"verbose"} < 0 or $pCONF->{"verbose"} > 3
l!l&&r!l&&!r
3314
MC/DC100%3/3
defined $pCONF->{"verbose"} and $pCONF->{"verbose"} < 0 || $pCONF->{"verbose"} > 3
defined $pCONF->{"verbose"} $pCONF->{"verbose"} < 0 $pCONF->{"verbose"} > 3
Truth table100%4/4
A and B or C
A= defined $pCONF->{"verbose"}B= $pCONF->{"verbose"} < 0C= $pCONF->{"verbose"} > 3
ABCresult
0XX0
1000
11X1
1011
1153 6 return 'verbose must be between 0 and 3';
1154 }
1155  
1156 36 ▶ if (defined $pCONF->{http_postlimit} && $pCONF->{http_postlimit} < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pCONF->{"http_postlimit"} and $pCONF->{"http_postlimit"} < 0) 3 33 36
Condition66%2/3
defined $pCONF->{"http_postlimit"} and $pCONF->{"http_postlimit"} < 0
!ll&&!rl&&r
3303
MC/DC50%1/2
defined $pCONF->{"http_postlimit"} and $pCONF->{"http_postlimit"} < 0
defined $pCONF->{"http_postlimit"} $pCONF->{"http_postlimit"} < 0
Truth table66%2/3
A and B
A= defined $pCONF->{"http_postlimit"}B= $pCONF->{"http_postlimit"} < 0
ABresult
0X0
100
111
1157 3 return 'http_postlimit must be >= 0';
1158 }
1159  
1160 33 ▶ if ($pCONF->{server_deny} && (!defined $pCONF->{server_etc} || $pCONF->{server_etc} eq '')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pCONF->{"server_deny"} and !defined($pCONF->{"server_etc"}) || $pCONF->{"server_etc"} eq "") 3 30 33
Condition50%3/6
$pCONF->{"server_deny"} and !defined($pCONF->{"server_etc"}) || $pCONF->{"server_etc"} eq ""
!ll&&!rl&&r
3003
not defined $pCONF->{"server_etc"} or $pCONF->{"server_etc"} eq ""
l!l&&r!l&&!r
030
MC/DC33%1/3
$pCONF->{"server_deny"} and !defined($pCONF->{"server_etc"}) || $pCONF->{"server_etc"} eq ""
$pCONF->{"server_deny"} not defined $pCONF->{"server_etc"} $pCONF->{"server_etc"} eq ""
Truth table50%2/4
A and not(B) or C
A= $pCONF->{"server_deny"}B= not defined $pCONF->{"server_etc"}C= $pCONF->{"server_etc"} eq ""
ABCresult
0XX0
1000
11X1
1011
1161 3 return 'server_etc is required when server_deny is enabled';
1162 }
1163  
1164 30 ▶ if ($pCONF->{server_auth} && (!defined $pCONF->{server_keys} || ref($pCONF->{server_keys}) ne 'ARRAY')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pCONF->{"server_auth"} and !defined($pCONF->{"server_keys"}) || ref $pCONF->{"server_keys"} ne "ARRAY") 3 27 30
Condition83%5/6
$pCONF->{"server_auth"} and !defined($pCONF->{"server_keys"}) || ref $pCONF->{"server_keys"} ne "ARRAY"
!ll&&!rl&&r
2433
not defined $pCONF->{"server_keys"} or ref $pCONF->{"server_keys"} ne "ARRAY"
l!l&&r!l&&!r
033
MC/DC66%2/3
$pCONF->{"server_auth"} and !defined($pCONF->{"server_keys"}) || ref $pCONF->{"server_keys"} ne "ARRAY"
$pCONF->{"server_auth"} not defined $pCONF->{"server_keys"} ref $pCONF->{"server_keys"} ne "ARRAY"
Truth table75%3/4
A and not(B) or C
A= $pCONF->{"server_auth"}B= not defined $pCONF->{"server_keys"}C= ref $pCONF->{"server_keys"} ne "ARRAY"
ABCresult
0XX0
1000
11X1
1011
1165 3 return 'server_keys must be an arrayref when server_auth is enabled';
1166 }
1167  
1168 27 return undef;
1169 }
1170  
1171 # ============================================================================
1172 # File Upload Methods
1173 # ============================================================================
1174  
1175 0 ▶sub _send_upload_form {
Subroutine _send_upload_form: not called CC=1 SCAR=6.9
1176 0 my ($self, $client) = @_;
1177  
1178 0 my $max_mb = $self->upload_max_size / (1024 * 1024);
1179 0 my $allowed_types = join(', ', @{$self->upload_allowed_types});
1180  
1181 0 my $html = <<"HTML";
1182 <!DOCTYPE html>
1183 <html>
1184 <head>
1185 <title>File Upload</title>
1186 <style>
1187 body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; }
1188 h1 { color: #333; }
1189 .info { background: #f0f0f0; padding: 10px; margin: 10px 0; border-radius: 5px; }
1190 .error { color: red; margin: 10px 0; }
1191 button { background: #4CAF50; color: white; padding: 10px 20px; border: none; cursor: pointer; }
1192 button:hover { background: #45a049; }
1193 </style>
1194 </head>
1195 <body>
1196 <h1>File Upload</h1>
1197 <div class="info">
1198 <strong>Maximum file size:</strong> ${max_mb}MB<br>
1199 <strong>Allowed types:</strong> $allowed_types
1200 </div>
1201 <form action="/upload" method="POST" enctype="multipart/form-data">
1202 <p><input type="file" name="file" required></p>
1203 <p><button type="submit">Upload File</button></p>
1204 </form>
1205 </body>
1206 </html>
1207 HTML
1208  
1209 0 my $len = length($html);
1210  
1211 0 my @headers = (
1212 "HTTP/1.1 200 OK",
1213 "Server: " . $self->server_name,
1214 "Content-Type: text/html; charset=utf-8",
1215 "Content-Length: $len",
1216 "Connection: close",
1217 );
1218  
1219 0 print $client join("\r\n", @headers) . "\r\n\r\n" . $html;
1220 0 close($client);
1221  
1222 0 return (200, $len);
1223 }
1224  
1225 0 ▶sub _handle_upload {
Subroutine _handle_upload: not called CC=12 SCAR=50.5
1226 0 my ($self, $client, $request) = @_;
1227  
1228 0 my @upload_results;
1229 0 ▶ my $clip = $request->{clip} || 'unknown';
Condition0%0/2
$request->{'clip'} || 'unknown'
l!l
00
MC/DC0%0/1
$request->{'clip'} || 'unknown'
$request->{'clip'}
Truth table0%0/2
A
A= $request->{'clip'}
Aresult
11
00
1230  
1231 0 ▶ if (!$request->{UPLOADS} || @{$request->{UPLOADS}} == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $request->{"UPLOADS"} or @{$request->{"UPLOADS"};} == 0) 0 0 0
Condition0%0/3
not $request->{"UPLOADS"} or @{$request->{"UPLOADS"};} == 0
l!l&&r!l&&!r
000
MC/DC0%0/2
not $request->{"UPLOADS"} or @{$request->{"UPLOADS"};} == 0
not $request->{"UPLOADS"} @{$request->{"UPLOADS"};} == 0
Truth table0%0/3
not(A) or B
A= not $request->{"UPLOADS"}B= @{$request->{"UPLOADS"};} == 0
ABresult
1X1
011
000
1232 0 $self->logit("# Upload request from $clip with no files", 1);
1233 0 return $self->_send_upload_response($client, 400, 'No files uploaded');
1234 }
1235  
1236 0 for my $upload (@{$request->{UPLOADS}}) {
1237 0 ▶ my $filename = $upload->{filename} || 'unnamed';
Condition0%0/2
$upload->{'filename'} || 'unnamed'
l!l
00
MC/DC0%0/1
$upload->{'filename'} || 'unnamed'
$upload->{'filename'}
Truth table0%0/2
A
A= $upload->{'filename'}
Aresult
11
00
1238 0 ▶ my $size = $upload->{size} || 0;
Condition0%0/2
$upload->{'size'} || 0
l!l
00
MC/DC0%0/1
$upload->{'size'} || 0
$upload->{'size'}
Truth table0%0/2
A
A= $upload->{'size'}
Aresult
11
00
1239 0 ▶ my $mime_type = $upload->{mime_type} || 'application/octet-stream';
Condition0%0/2
$upload->{'mime_type'} || 'application/octet-stream'
l!l
00
MC/DC0%0/1
$upload->{'mime_type'} || 'application/octet-stream'
$upload->{'mime_type'}
Truth table0%0/2
A
A= $upload->{'mime_type'}
Aresult
11
00
1240  
1241 0 $self->logit("# Processing upload: $filename ($size bytes, $mime_type) from $clip", 2);
1242  
1243 my ($success, $message, $saved_path) = $self->_save_upload_file(
1244 $filename,
1245 $upload->{data},
1246 0 $mime_type,
1247 );
1248  
1249 0 ▶ if ($success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success) { } 0 0 0
1250 0 $self->logit("# Upload success: $filename -> $saved_path", 1);
1251 0 push @upload_results, {
1252 filename => $filename,
1253 size => $size,
1254 mime_type => $mime_type,
1255 saved_path => $saved_path,
1256 success => 1,
1257 };
1258 } else {
1259 0 $self->logit("# Upload failed: $filename - $message", 1);
1260 0 push @upload_results, {
1261 filename => $filename,
1262 size => $size,
1263 mime_type => $mime_type,
1264 success => 0,
1265 error => $message,
1266 };
1267 }
1268 }
1269  
1270 0 my $func = $self->func_upload;
1271 0 ▶ if ($func) {
Branch: 1 branch
BranchTrueFalseTotal
if ($func) 0 0 0
1272 0 my ($status, $body) = $func->($self, \@upload_results);
1273 0 return $self->_send_upload_response($client, $status, $body);
1274 }
1275  
1276 0 my $success_count = scalar grep { $_->{success} } @upload_results;
1277 0 my $total_count = scalar @upload_results;
1278  
1279 0 ▶ if ($success_count == $total_count) {
Branch: 2 branches
BranchTrueFalseTotal
if ($success_count == $total_count) { } 0 0 0
elsif ($success_count > 0) { } 0 0 0
1280 0 return $self->_send_upload_response($client, 201, "All $success_count file(s) uploaded successfully");
1281 } elsif ($success_count > 0) {
1282 0 return $self->_send_upload_response($client, 207, "$success_count of $total_count files uploaded");
1283 } else {
1284 0 return $self->_send_upload_response($client, 400, "No files uploaded successfully");
1285 }
1286 }
1287  
1288 3 ▶sub _extract_boundary {
Subroutine _extract_boundary: called CC=4 SCAR=14.2
1289 3 my ($self, $content_type) = @_;
1290  
1291 3 ▶ return undef unless defined $content_type && $content_type ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content_type and $content_type ne "" 0 3 3
Condition33%1/3
defined $content_type and $content_type ne ""
!ll&&!rl&&r
003
MC/DC0%0/2
defined $content_type and $content_type ne ""
defined $content_type $content_type ne ""
Truth table33%1/3
A and B
A= defined $content_typeB= $content_type ne ""
ABresult
0X0
100
111
1292  
1293 3 ▶ if ($content_type =~ /boundary=(.+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content_type =~ /boundary=(.+)$/i) 2 1 3
1294 2 my $boundary = $1;
1295 2 $boundary =~ s/^["']+|["']+$//g;
1296 2 return $boundary;
1297 }
1298  
1299 1 return undef;
1300 }
1301  
1302 0 ▶sub _parse_multipart {
Subroutine _parse_multipart: not called CC=11 SCAR=48.8
1303 0 my ($self, $content_type, $body) = @_;
1304  
1305 0 my @uploads;
1306  
1307 my $boundary;
1308 0 ▶ if ($content_type =~ /boundary=(.+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content_type =~ /boundary=(.+)$/i) { } 0 0 0
1309 0 $boundary = $1;
1310 0 $boundary =~ s/^["']|["']$//g;
1311 } else {
1312 0 $self->logit("# No boundary found in Content-Type: $content_type", 1);
1313 0 return \@uploads;
1314 }
1315  
1316 0 my $delimiter = "--$boundary";
1317 0 my $end_delimiter = "$boundary--";
1318  
1319 0 my $part_start = 0;
1320 0 my $part_end = index($body, $delimiter, $part_start);
1321  
1322 0 ▶ while ($part_end > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part_end > 0) 0 0 0
1323 0 my $part = substr($body, $part_start, $part_end - $part_start);
1324 0 $part =~ s/^\r?\n//;
1325  
1326 0 ▶ if ($part ne $end_delimiter && $part ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($part ne $end_delimiter and $part ne "") 0 0 0
Condition0%0/3
$part ne $end_delimiter and $part ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
$part ne $end_delimiter and $part ne ""
$part ne $end_delimiter $part ne ""
Truth table0%0/3
A and B
A= $part ne $end_delimiterB= $part ne ""
ABresult
0X0
100
111
1327 0 my ($headers, $data) = $self->_split_part_headers($part);
1328 0 ▶ if ($headers && $data ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($headers and $data ne "") 0 0 0
Condition0%0/3
$headers and $data ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
$headers and $data ne ""
$headers $data ne ""
Truth table0%0/3
A and B
A= $headersB= $data ne ""
ABresult
0X0
100
111
1329 0 ▶ my $disposition = $headers->{'Content-Disposition'} || '';
Condition0%0/2
$headers->{'Content-Disposition'} || ''
l!l
00
MC/DC0%0/1
$headers->{'Content-Disposition'} || ''
$headers->{'Content-Disposition'}
Truth table0%0/2
A
A= $headers->{'Content-Disposition'}
Aresult
11
00
1330 0 ▶ if ($disposition =~ /filename="([^"]+)"/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($disposition =~ /filename="([^"]+)"/) 0 0 0
1331 0 my $filename = $1;
1332 0 my $safe_name = $self->_sanitize_filename($filename);
1333 0 ▶ my $mime_type = $headers->{'Content-Type'} || 'application/octet-stream';
Condition0%0/2
$headers->{'Content-Type'} || 'application/octet-stream'
l!l
00
MC/DC0%0/1
$headers->{'Content-Type'} || 'application/octet-stream'
$headers->{'Content-Type'}
Truth table0%0/2
A
A= $headers->{'Content-Type'}
Aresult
11
00
1334  
1335 0 push @uploads, {
1336 filename => $safe_name,
1337 data => $data,
1338 mime_type => $mime_type,
1339 size => length($data),
1340 };
1341 }
1342 }
1343 }
1344  
1345 0 $part_start = $part_end + length($delimiter) + 2;
1346 0 ▶ last if $part_start >= length($body);
Branch: 1 branch
BranchTrueFalseTotal
if $part_start >= length $body 0 0 0
1347 0 $part_end = index($body, $delimiter, $part_start);
1348 }
1349  
1350 0 return \@uploads;
1351 }
1352  
1353 1 ▶sub _split_part_headers {
Subroutine _split_part_headers: called CC=5 SCAR=17.0
1354 1 my ($self, $part) = @_;
1355  
1356 1 my ($header_section, $body) = $part =~ /^((?:[^\r\n]+\r?\n)*)\r?\n(.*)$/s;
1357  
1358 1 ▶ return (undef, $part) unless defined $header_section && defined $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $header_section and defined $body 0 1 1
Condition33%1/3
defined $header_section and defined $body
!ll&&!rl&&r
001
MC/DC0%0/2
defined $header_section and defined $body
defined $header_section defined $body
Truth table33%1/3
A and B
A= defined $header_sectionB= defined $body
ABresult
0X0
100
111
1359  
1360 1 my %headers;
1361 1 for my $line (split /\r?\n/, $header_section) {
1362 2 ▶ if ($line =~ /^([^:]+):\s*(.+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^([^:]+):\s*(.+)$/) 2 0 2
1363 2 $headers{$1} = $2;
1364 }
1365 }
1366  
1367 1 return (\%headers, $body);
1368 }
1369  
1370 4 ▶sub _save_upload_file {
Subroutine _save_upload_file: called CC=6 SCAR=18.3
1371 4 my ($self, $filename, $data, $mime_type) = @_;
1372  
1373 4 my $max_size = $self->upload_max_size;
1374 4 ▶ if (length($data) > $max_size) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $data > $max_size) 1 3 4
1375 1 return (0, "File exceeds maximum size of " . ($max_size / 1024 / 1024) . "MB");
1376 }
1377  
1378 3 ▶ unless ($self->_validate_upload_type($mime_type)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_validate_upload_type($mime_type)) 0 3 3
1379 0 return (0, "File type not allowed: $mime_type");
1380 }
1381  
1382 3 my $upload_dir = $self->upload_dir;
1383 3 ▶ unless (-d $upload_dir) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $upload_dir) 1 2 3
1384 1 ▶ mkdir($upload_dir, 0755) or return (0, "Cannot create upload directory: $!");
Branch: 1 branch
BranchTrueFalseTotal
mkdir $upload_dir, 493 or return 0, "Cannot create upload directory: $!" 1 0 1
1385 }
1386  
1387 3 my $safe_name = $self->_sanitize_filename($filename);
1388 3 my $target_path = "$upload_dir/$safe_name";
1389  
1390 3 lock ${ $self->_upload_lock };
1391  
1392 3 my $temp_fd = File::Temp->new(
1393 DIR => $upload_dir,
1394 SUFFIX => '.tmp',
1395 UNLINK => 0,
1396 );
1397 3 print $temp_fd $data;
1398 3 close($temp_fd);
1399  
1400 3 ▶ if (rename($temp_fd, $target_path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (rename $temp_fd, $target_path) { } 3 0 3
1401 3 chmod(0644, $target_path);
1402 3 $self->logit("# Saved upload: $target_path (" . length($data) . " bytes)", 2);
1403 3 return (1, $target_path, $target_path);
1404 } else {
1405 0 unlink($temp_fd);
1406 0 return (0, "Failed to save file: $!");
1407 }
1408 }
1409  
1410 11 ▶sub _sanitize_filename {
Subroutine _sanitize_filename: called CC=7 SCAR=19.6
1411 11 my ($self, $filename) = @_;
1412  
1413 11 ▶ return 'unnamed_file' unless defined $filename && $filename ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $filename and $filename ne "" 2 9 11
Condition100%3/3
defined $filename and $filename ne ""
!ll&&!rl&&r
119
MC/DC100%2/2
defined $filename and $filename ne ""
defined $filename $filename ne ""
Truth table100%3/3
A and B
A= defined $filenameB= $filename ne ""
ABresult
0X0
100
111
1414  
1415 9 $filename =~ s/^["']+|["']+$//g;
1416  
1417 9 $filename =~ s/\.\.//g;
1418 9 $filename =~ s/[\\\/]+//g;
1419  
1420 9 $filename =~ s/[^\w\.\-]/_/g;
1421  
1422 9 $filename =~ s/^\s+|\s+$//g;
1423  
1424 9 ▶ $filename = 'unnamed_file' if $filename =~ /^\.+$/;
Branch: 1 branch
BranchTrueFalseTotal
if $filename =~ /^\.+$/ 0 9 9
1425 9 ▶ $filename = 'unnamed_file' if $filename eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $filename eq "" 0 9 9
1426  
1427 9 my ($base, $ext) = $filename =~ /^(.+?)(\.[^.]+)?$/;
1428 9 ▶ $base = 'file' if $base eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $base eq "" 0 9 9
1429 9 ▶ $filename = defined $ext ? "$base$ext" : $base;
Branch: 1 branch
BranchTrueFalseTotal
defined $ext ? : 5 4 9
1430  
1431 9 return $filename;
1432 }
1433  
1434 12 ▶sub _validate_upload_type {
Subroutine _validate_upload_type: called CC=6 SCAR=17.9
1435 12 my ($self, $mime_type) = @_;
1436  
1437 12 ▶ return 1 unless defined $mime_type && $mime_type ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mime_type and $mime_type ne "" 5 7 12
Condition100%3/3
defined $mime_type and $mime_type ne ""
!ll&&!rl&&r
417
MC/DC100%2/2
defined $mime_type and $mime_type ne ""
defined $mime_type $mime_type ne ""
Truth table100%3/3
A and B
A= defined $mime_typeB= $mime_type ne ""
ABresult
0X0
100
111
1438  
1439 7 my $allowed = $self->upload_allowed_types;
1440 7 ▶ return 1 unless @$allowed;
Branch: 1 branch
BranchTrueFalseTotal
unless @$allowed 2 5 7
1441  
1442 5 $mime_type = lc($mime_type);
1443 5 for my $allowed_type (@$allowed) {
1444 12 ▶ return 1 if lc($allowed_type) eq $mime_type;
Branch: 1 branch
BranchTrueFalseTotal
if lc $allowed_type eq $mime_type 3 9 12
1445 }
1446  
1447 2 $self->logit("# Rejected upload type: $mime_type", 1);
1448 2 return 0;
1449 }
1450  
1451 0 ▶sub _send_upload_response {
Subroutine _send_upload_response: not called CC=4 SCAR=30.0
1452 0 my ($self, $client, $status, $body) = @_;
1453  
1454 0 ▶ my $status_text = $status eq '201' ? 'Created' :
Branch: 3 branches
BranchTrueFalseTotal
$status eq '201' ? : 0 0 0
$status eq '400' ? : 0 0 0
$status eq '207' ? : 0 0 0
1455 $status eq '400' ? 'Bad Request' :
1456 $status eq '207' ? 'Multi-Status' : 'Response';
1457  
1458 0 my $len = length($body);
1459  
1460 0 my @headers = (
1461 "HTTP/1.1 $status $status_text",
1462 "Server: " . $self->server_name,
1463 "Content-Type: text/plain",
1464 "Content-Length: $len",
1465 "Connection: close",
1466 );
1467  
1468 0 print $client join("\r\n", @headers) . "\r\n\r\n" . $body;
1469 0 close($client);
1470  
1471 0 return ($status, $len);
1472 }
1473  
1474 # ============================================================================
1475 # Rate Limiting Methods
1476 # ============================================================================
1477  
1478 9 ▶sub _check_rate_limit {
Subroutine _check_rate_limit: called CC=6 SCAR=18.2
1479 9 my ($self, $ip) = @_;
1480  
1481 9 my $whitelist = $self->rate_limit_whitelist;
1482 9 for my $_ip (@$whitelist) {
1483 25 ▶ return 1 if $ip eq $_ip;
Branch: 1 branch
BranchTrueFalseTotal
if $ip eq $_ip 1 24 25
1484 }
1485  
1486 8 my $lock = $self->_rate_limit_lock;
1487 8 lock($$lock);
1488  
1489 8 my $data = $self->_rate_limit_data;
1490  
1491 8 my $now = time();
1492 8 my $window = $self->rate_limit_window;
1493 8 my $max_requests = $self->rate_limit_requests;
1494  
1495 8 ▶ my $ip_data = $data->{$ip} //= { count => 0, first_request => $now };
Condition100%2/2
$data->{$ip} //= {"count", 0, "first_request", $now}
l!l
53
MC/DC100%1/1
$data->{$ip} //= {"count", 0, "first_request", $now}
$data->{$ip}
Truth table100%2/2
A
A= $data->{$ip}
Aresult
11
00
1496  
1497 8 ▶ if ($now - $ip_data->{first_request} > $window) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now - $ip_data->{"first_request"} > $window) 0 8 8
1498 0 $ip_data->{count} = 0;
1499 0 $ip_data->{first_request} = $now;
1500 }
1501  
1502 8 $ip_data->{count}++;
1503 8 ▶ $self->logit("# Rate limit check for $ip: $ip_data->{count}/$max_requests", 3) if $self->verbose >= 3;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose >= 3 0 8 8
1504  
1505 8 return $ip_data->{count} <= $max_requests;
1506 }
1507  
1508 4 ▶sub _is_blocked {
Subroutine _is_blocked: called CC=3 SCAR=11.0
1509 4 my ($self, $ip) = @_;
1510  
1511 4 my $lock = $self->_rate_limit_lock;
1512 4 lock($$lock);
1513  
1514 4 my $data = $self->_rate_limit_data;
1515  
1516 4 ▶ return undef unless exists $data->{"blocked:$ip"};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$data{"blocked:$ip"} 2 2 4
1517  
1518 2 my $block_info = $data->{"blocked:$ip"};
1519 2 my $now = time();
1520  
1521 2 ▶ if ($now > $block_info->{until}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now > $block_info->{"until"}) 1 1 2
1522 1 delete $data->{"blocked:$ip"};
1523 1 $self->logit("# Rate limit expired for $ip", 2);
1524 1 return undef;
1525 }
1526  
1527 1 return $block_info;
1528 }
1529  
1530 1 ▶sub _block_ip {
Subroutine _block_ip: called CC=1 SCAR=0.0
1531 1 my ($self, $ip, $duration) = @_;
1532  
1533 1 my $lock = $self->_rate_limit_lock;
1534 1 lock($$lock);
1535  
1536 1 my $data = $self->_rate_limit_data;
1537  
1538 1 $data->{"blocked:$ip"} = {
1539 until => time() + $duration,
1540 reason => 'rate_limit_exceeded',
1541 requests => $self->rate_limit_requests,
1542 window => $self->rate_limit_window,
1543 };
1544  
1545 1 $self->logit("# Blocked IP $ip for ${duration}s (rate limit exceeded)", 1);
1546 }
1547  
1548 0 ▶sub _send_rate_limit_response {
Subroutine _send_rate_limit_response: not called CC=6 SCAR=37.4
1549 0 my ($self, $client, $ip, $block_info) = @_;
1550  
1551 0 ▶ my $remaining = $block_info ? 0 : $self->rate_limit_requests;
Branch: 1 branch
BranchTrueFalseTotal
$block_info ? : 0 0 0
1552 0 my $limit = $self->rate_limit_requests;
1553 0 ▶ my $reset = $block_info ? $block_info->{until} - time() : $self->rate_limit_window;
Branch: 1 branch
BranchTrueFalseTotal
$block_info ? : 0 0 0
1554 0 ▶ my $retry_after = $block_info ? $block_info->{until} - time() : 1;
Branch: 1 branch
BranchTrueFalseTotal
$block_info ? : 0 0 0
1555  
1556 0 ▶ my $body = $block_info
Branch: 1 branch
BranchTrueFalseTotal
$block_info ? : 0 0 0
1557 ? "Error 429 Too Many Requests\nIP $ip has been temporarily blocked due to rate limit exceeded. Retry after $retry_after seconds.\n"
1558 : "Error 429 Too Many Requests\nRate limit exceeded. Please slow down.\n";
1559  
1560 0 my $len = length($body);
1561  
1562 0 my @headers = (
1563 "HTTP/1.1 429 Too Many Requests",
1564 "Server: " . $self->server_name,
1565 "Content-Type: text/plain",
1566 "Content-Length: $len",
1567 "Connection: close",
1568 "X-RateLimit-Limit: $limit",
1569 "X-RateLimit-Remaining: $remaining",
1570 "X-RateLimit-Reset: $reset",
1571 "Retry-After: $retry_after",
1572 );
1573  
1574 0 print $client join("\r\n", @headers) . "\r\n\r\n" . $body;
1575 0 close($client);
1576  
1577 0 ▶ $self->logit("# Sent rate limit response to $ip (blocked: " . ($block_info ? 'yes' : 'warning') . ")", 1);
Branch: 1 branch
BranchTrueFalseTotal
$block_info ? : 0 0 0
1578 }
1579  
1580 # ============================================================================
1581  
1582 5 1;
1583  
1584 =pod
1585  
1586 =head1 NAME
1587  
1588 LightTCP::Server - A configurable TCP/HTTP server with file uploads, rate limiting, and threading support (Pure Perl OOP)
1589  
1590 =head1 VERSION
1591  
1592 Version 2.05
1593  
1594 =head1 LICENSE
1595  
1596 This module is free software.
1597  
1598 You may redistribute it and/or modify it under the same terms as Perl itself.
1599  
1600 =head1 SYNOPSIS
1601  
1602 use LightTCP::Server;
1603  
1604 # Basic HTTP server
1605 my $server = LightTCP::Server->new(
1606 server_addr => '0.0.0.0:8080',
1607 server_name => 'MyServer',
1608 verbose => 1,
1609 );
1610 $server->start();
1611  
1612 # Threaded server with custom handler
1613 my $server = LightTCP::Server->new(
1614 server_addr => '127.0.0.1:8881',
1615 server_type => 'thread',
1616 max_threads => 5,
1617 func_perl => sub {
1618 my ($self, $client, $preq) = @_;
1619 print $client "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nHello";
1620 return (200, 5);
1621 },
1622 );
1623 $server->start();
1624  
1625 # Server with file uploads and rate limiting
1626 my $server = LightTCP::Server->new(
1627 server_addr => '0.0.0.0:8080',
1628 upload_dir => '/var/www/uploads',
1629 upload_max_size => 10 * 1024 * 1024, # 10MB
1630 upload_allowed_types => [qw(image/jpeg image/png application/pdf)],
1631 rate_limit_enabled => 1,
1632 rate_limit_requests => 100,
1633 rate_limit_window => 60,
1634 rate_limit_block_duration => 300,
1635 func_upload => \&handle_upload,
1636 );
1637 $server->start();
1638  
1639 sub handle_upload {
1640 my ($server, $results) = @_;
1641 # $results is arrayref of upload info
1642 return (201, 'Upload successful');
1643 }
1644  
1645 =head1 DESCRIPTION
1646  
1647 C<LightTCP::Server> is a pure Perl OOP module implementing a flexible TCP/HTTP server.
1648 It handles HTTP requests, serves static files, executes CGI scripts, and supports
1649 custom logic via callbacks. Features include:
1650  
1651 =over 4
1652  
1653 =item * Single-threaded, forked, or threaded operation modes
1654  
1655 =item * File upload handling with size limits and type validation
1656  
1657 =item * Configurable rate limiting with IP blocking
1658  
1659 =item * HTTP authentication (API keys and Basic Auth)
1660  
1661 =item * Host-based access control (allow/deny lists)
1662  
1663 =item * CGI script execution
1664  
1665 =item * Comprehensive logging and verbose output levels
1666  
1667 =back
1668  
1669 =head1 ATTRIBUTES
1670  
1671 =head2 Server Configuration
1672  
1673 =over 4
1674  
1675 =item C<server_addr> (required, default: '0.0.0.0:8881')
1676  
1677 IP address and port to listen on. Must be in format C<IP:port> (e.g., C<'0.0.0.0:8080'>).
1678  
1679 =item C<server_name> (default: 'tcpsname')
1680  
1681 Server name used in HTTP headers and logging.
1682  
1683 =item C<server_type> (default: 'single')
1684  
1685 Execution mode: C<'single'> (single process), C<'fork'> (fork per connection), or C<'thread'> (threaded).
1686  
1687 =item C<max_threads> (default: 10)
1688  
1689 Maximum concurrent threads when C<server_type> is C<'thread'>.
1690  
1691 =item C<server_timeout> (default: -1)
1692  
1693 Connection timeout in seconds. C<-1> means no timeout, C<0> means daily timeout check, C<1+> sets explicit timeout.
1694  
1695 =item C<verbose> (default: 0)
1696  
1697 Verbosity level: C<0> (minimal), C<1> (important), C<2> (info), C<3> (debug).
1698  
1699 =item C<logfn> (default: '')
1700  
1701 Path to log file. If empty, logs go to stderr.
1702  
1703 =item C<server_autostop> (default: 0)
1704  
1705 If set to C<1>, server stops after first request.
1706  
1707 =back
1708  
1709 =head2 Directory and File Handling
1710  
1711 =over 4
1712  
1713 =item C<server_dir> (default: '/var/www')
1714  
1715 Root directory for serving static files.
1716  
1717 =item C<server_etc> (default: '.')
1718  
1719 Directory for configuration files (allow/deny lists).
1720  
1721 =item C<server_fnext> (default: 'html css js ico gif jpg png')
1722  
1723 Space-separated list of file extensions to serve statically.
1724  
1725 =item C<server_perlonly> (default: 1)
1726  
1727 If C<1>, only custom handlers serve content; static files are disabled.
1728  
1729 =item C<server_cgi> (default: 0)
1730  
1731 Enable CGI script execution.
1732  
1733 =item C<server_cgiext> (default: 'cgi php')
1734  
1735 Space-separated list of CGI file extensions.
1736  
1737 =item C<http_postlimit> (default: 0)
1738  
1739 Maximum POST body size in bytes. C<0> means unlimited.
1740  
1741 =back
1742  
1743 =head2 Security and Authentication
1744  
1745 =over 4
1746  
1747 =item C<server_deny> (default: 0)
1748  
1749 Enable host-based access control using allow/deny files.
1750  
1751 =item C<server_secure> (default: 0)
1752  
1753 If C<1>, deny by default and require explicit allow files.
1754  
1755 =item C<server_auth> (default: 0)
1756  
1757 Enable authentication via API key or Basic Auth.
1758  
1759 =item C<server_keys> (default: [])
1760  
1761 Arrayref of valid lowercase API key strings.
1762  
1763 =item C<runas_user> (default: '')
1764  
1765 Run server as this user (after binding to privileged port).
1766  
1767 =item C<runas_group> (default: '')
1768  
1769 Run server as this group.
1770  
1771 =back
1772  
1773 =head2 File Upload Configuration
1774  
1775 =over 4
1776  
1777 =item C<upload_dir> (default: '/var/www/uploads')
1778  
1779 Directory for storing uploaded files. Must be writable.
1780  
1781 =item C<upload_max_size> (default: 10MB)
1782  
1783 Maximum file size in bytes for uploads.
1784  
1785 =item C<upload_allowed_types> (default: see below)
1786  
1787 Arrayref of allowed MIME types. Defaults include: image/jpeg, image/png, image/gif,
1788 image/webp, application/pdf, text/plain, text/csv, text/html, application/zip,
1789 application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document,
1790 application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.
1791  
1792 =item C<func_upload>
1793  
1794 Optional callback coderef invoked after successful uploads.
1795 Signature: C<sub($server, $upload_results)> where C<$upload_results> is an arrayref of:
1796 C<{ filename, size, mime_type, saved_path, success, error }>.
1797 Should return C<($status, $message)>.
1798  
1799 =back
1800  
1801 =head2 Rate Limiting Configuration
1802  
1803 =over 4
1804  
1805 =item C<rate_limit_enabled> (default: 0)
1806  
1807 Enable rate limiting.
1808  
1809 =item C<rate_limit_requests> (default: 100)
1810  
1811 Maximum requests per time window.
1812  
1813 =item C<rate_limit_window> (default: 60)
1814  
1815 Time window in seconds.
1816  
1817 =item C<rate_limit_block_duration> (default: 300)
1818  
1819 Duration in seconds to block IPs that exceed rate limit.
1820  
1821 =item C<rate_limit_whitelist> (default: [127.0.0.1, ::1, localhost])
1822  
1823 Arrayref of IP addresses exempt from rate limiting.
1824  
1825 =back
1826  
1827 =head2 Callback Functions
1828  
1829 =over 4
1830  
1831 =item C<func_perl>
1832  
1833 Custom request handler. Signature: C<sub($self, $client, $preq)>.
1834 C<$preq> contains: METHOD, URI, URI_FN, URI_EXT, URI_VALID, QUERY_STRING,
1835 CONTENT_LENGTH, CONTENT_DATA, clip, clport, and HTTP headers.
1836 Should return C<($status_code, $content_length)>.
1837  
1838 =item C<func_timeout>
1839  
1840 Called on connection timeout. Signature: C<sub($self)>.
1841  
1842 =item C<func_done>
1843  
1844 Called after request processing. Signature: C<sub($self, $preq)>.
1845  
1846 =item C<func_log>
1847  
1848 Custom logging handler. Signature: C<sub($self, $message, $level)>.
1849  
1850 =back
1851  
1852 =head1 METHODS
1853  
1854 =over 4
1855  
1856 =item C<new(%config)>
1857  
1858 Create a new server instance. Accepts either a hash or hashref of configuration.
1859  
1860 =item C<start()>
1861  
1862 Start the server and block until shutdown. Returns C<1> on clean shutdown, C<0> on error.
1863  
1864 =item C<stop()>
1865  
1866 Stop the server gracefully.
1867  
1868 =item C<is_running()>
1869  
1870 Returns true if server is running.
1871  
1872 =item C<logit($message, $level)>
1873  
1874 Log a message at the specified level (0-3). Higher levels are more verbose.
1875  
1876 =item C<validate_config(\%config)>
1877  
1878 Class method to validate configuration. Returns C<undef> on success, error message string on failure.
1879  
1880 =item C<server_addr([$value])>
1881  
1882 Getter/setter for server address.
1883  
1884 =item C<server_name([$value])>
1885  
1886 Getter/setter for server name.
1887  
1888 =item C<server_type([$value])>
1889  
1890 Getter/setter for server type.
1891  
1892 =item C<max_threads([$value])>
1893  
1894 Getter/setter for max threads.
1895  
1896 =item C<verbose([$value])>
1897  
1898 Getter/setter for verbosity level.
1899  
1900 =item C<upload_dir([$value])>
1901  
1902 Getter/setter for upload directory.
1903  
1904 =item C<upload_max_size([$value])>
1905  
1906 Getter/setter for max upload size.
1907  
1908 =item C<rate_limit_enabled([$value])>
1909  
1910 Getter/setter for rate limit enabled flag.
1911  
1912 =item C<rate_limit_requests([$value])>
1913  
1914 Getter/setter for rate limit requests.
1915  
1916 =back
1917  
1918 =head1 UPLOAD ENDPOINTS
1919  
1920 The server provides built-in upload handling at these endpoints:
1921  
1922 =over 4
1923  
1924 =item C<GET /upload> or C<GET /upload/>
1925  
1926 Returns an HTML form for file uploads.
1927  
1928 =item C<POST /upload>
1929  
1930 Handles multipart/form-data file uploads.
1931  
1932 =item C<POST /api/upload>
1933  
1934 Alternative endpoint for API-based uploads.
1935  
1936 =back
1937  
1938 Upon successful upload, the C<func_upload> callback is invoked if defined.
1939 File names are sanitized to prevent path traversal attacks.
1940  
1941 =head1 RATE LIMITING
1942  
1943 When rate limiting is enabled, the server tracks requests per IP address.
1944 Responses include these HTTP headers:
1945  
1946 =over 4
1947  
1948 =item C<X-RateLimit-Limit> - Maximum requests allowed
1949  
1950 =item C<X-RateLimit-Remaining> - Remaining requests in window
1951  
1952 =item C<X-RateLimit-Reset> - Seconds until window resets
1953  
1954 =item C<Retry-After> - Seconds until unblocked (on 429 responses)
1955  
1956 =back
1957  
1958 When rate limit is exceeded, the server returns HTTP 429 Too Many Requests
1959 and closes the connection.
1960  
1961 =head1 SECURITY
1962  
1963 =over 4
1964  
1965 =item Path Traversal Protection
1966  
1967 The server blocks requests containing C<..> or suspicious characters in URIs.
1968  
1969 =item Upload Security
1970  
1971 Uploaded filenames are sanitized: C<..>, C</>, C<\>, and special characters are removed.
1972 Files are written atomically using temp files then renamed.
1973  
1974 =item Access Control
1975  
1976 Host-based access control uses files in C<server_etc> directory:
1977 C<${server_name}_${IP}.allow> and C<${server_name}_${IP}.deny>.
1978  
1979 =item Authentication
1980  
1981 Supports X-API-Key header and Basic Auth. Keys are compared case-insensitively.
1982  
1983 =back
1984  
1985 =head1 CGI SUPPORT
1986  
1987 When C<server_cgi> is enabled, files with extensions in C<server_cgiext> are
1988 executed as CGI scripts. The following environment variables are set:
1989  
1990 C<REQUEST_METHOD>, C<QUERY_STRING>, C<CONTENT_LENGTH>, C<SERVER_PROTOCOL>,
1991 C<SCRIPT_NAME>, C<PATH_INFO>, and HTTP headers are passed as C<HTTP_*> variables.
1992  
1993 CGI scripts should output headers followed by a blank line, then the body.
1994  
1995 =head1 EXAMPLES
1996  
1997 See L<examples/demo.pl> for a complete demonstration server.
1998  
1999 =head1 DEPENDENCIES
2000  
2001 =over 4
2002  
2003 =item * C<IO::Socket::INET>
2004  
2005 =item * C<IPC::Open3>
2006  
2007 =item * C<threads>
2008  
2009 =item * C<threads::shared>
2010  
2011 =item * C<File::Temp>
2012  
2013 =back
2014  
2015 =head1 BUGS AND LIMITATIONS
2016  
2017 =over 4
2018  
2019 =item * No HTTPS/TLS support (plain TCP only)
2020  
2021 =item * No WebSocket support
2022  
2023 =item * CGI scripts must be executable and use shebang lines
2024  
2025 =item * Rate limiting uses in-memory storage (resets on restart)
2026  
2027 =item * Large file uploads are held in memory
2028  
2029 =back
2030  
↑ Summary