| 1 | package psSnake; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use POSIX; | ||
| 7 | use utf8; | ||
| 8 | use Data::Dumper; | ||
| 9 | use File::Path; | ||
| 10 | use IPC::Open3; | ||
| 11 | use IO::Select; | ||
| 12 | use IO::Handle; # autoflush | ||
| 13 | use FileHandle; | ||
| 14 | use Time::HiRes qw/usleep/; | ||
| 15 | use Socket; # socketpair | ||
| 16 | use File::Basename; # basename | ||
| 17 | use File::Path; # mkpath | ||
| 18 | use File::Copy; | ||
| 19 | |||
| 20 | my $have_mime_lite; | ||
| 21 | eval { | ||
| 22 | require MIME::Lite; | ||
| 23 | MIME::Lite->import(); | ||
| 24 | require MIME::Base64; | ||
| 25 | MIME::Base64->import(); | ||
| 26 | require MIME::QuotedPrint; | ||
| 27 | MIME::QuotedPrint->import(); | ||
| 28 | require File::MMagic; | ||
| 29 | File::MMagic->import(); | ||
| 30 | }; | ||
| 31 | $have_mime_lite = 1 unless $@; | ||
| 32 | |||
| 33 | # variables available for programs importing this library | ||
| 34 | our $debug; | ||
| 35 | our $debug2; | ||
| 36 | |||
| 37 | our $cmd; | ||
| 38 | our $cmd_opts; | ||
| 39 | |||
| 40 | # populated with sub references | ||
| 41 | # to the console ready functions | ||
| 42 | our $command = ""; | ||
| 43 | our $commands = {}; | ||
| 44 | our $commands_invisible = {}; | ||
| 45 | our $command_param = {}; | ||
| 46 | our $command_desc = {}; | ||
| 47 | our $program_name = ""; | ||
| 48 | |||
| 49 | our $HOOKS = {}; | ||
| 50 | our $real_uid = $<; | ||
| 51 | |||
| 52 | |||
| 53 | # read file, removing carriage returns | ||
| 54 | sub read_file_option { | ||
| 55 | my ($filename, $opts) = @_; | ||
| 56 | $opts = {} unless $opts; | ||
| 57 | |||
| 58 | my $t = undef; | ||
| 59 | |||
| 60 | if (-e $filename || $opts->{'mandatory'}) { | ||
| 61 | $t = read_file_scalar($filename); | ||
| 62 | $t =~ s/[\r\n]//sgo; | ||
| 63 | } | ||
| 64 | |||
| 65 | return $t; | ||
| 66 | } | ||
| 67 | |||
| 68 | sub write_file_option { | ||
| 69 | my ($filename, $value, $opts) = @_; | ||
| 70 | |||
| 71 | $opts = {} unless $opts; | ||
| 72 | my $fh = psSnake::safe_open($filename, "overwrite", {'timeout' => 2}); | ||
| 73 | return 0 unless $fh; | ||
| 74 | print $fh $value . "\n"; | ||
| 75 | psSnake::safe_close($fh); | ||
| 76 | } | ||
| 77 | |||
| 78 | sub read_file_scalar { | ||
| 79 | my ($filename) = @_; | ||
| 80 | |||
| 81 | my $filecontent; | ||
| 82 | unless (open F, $filename) { | ||
| 83 | psSnake::die("Couldn't open $filename for reading: $!"); | ||
| 84 | } | ||
| 85 | { local $/ = undef; $filecontent = <F>; } | ||
| 86 | close F; | ||
| 87 | |||
| 88 | return $filecontent; | ||
| 89 | } | ||
| 90 | |||
| 91 | # read file, each line is an array element | ||
| 92 | # | ||
| 93 | sub read_file_array { | ||
| 94 | my ($filename, $opts) = @_; | ||
| 95 | $opts = {} unless $opts; | ||
| 96 | |||
| 97 | my $arr = []; | ||
| 98 | my $t = undef; | ||
| 99 | |||
| 100 | if (-e $filename || $opts->{'mandatory'}) { | ||
| 101 | $t = read_file_scalar($filename); | ||
| 102 | @{$arr} = split(/\n/so, $t); | ||
| 103 | } | ||
| 104 | |||
| 105 | return $arr; | ||
| 106 | } | ||
| 107 | |||
| 108 | # generate fileinfo structure | ||
| 109 | # | ||
| 110 | sub fileinfo_struct { | ||
| 111 | my ($opts) = @_; | ||
| 112 | |||
| 113 | $opts = {} unless $opts; | ||
| 114 | |||
| 115 | psSnake::die("fileinfo_struct: absolute_name must be specified") | ||
| 116 | unless $opts->{'absolute_name'}; | ||
| 117 | |||
| 118 | my $entry = {}; | ||
| 119 | |||
| 120 | # return empty struct if file does not exist | ||
| 121 | if (! -e $opts->{'absolute_name'} && ! -l $opts->{'absolute_name'}) { | ||
| 122 | return $entry; | ||
| 123 | } | ||
| 124 | |||
| 125 | foreach my $k(qw/absolute_name relative_name short_name/) { | ||
| 126 | $entry->{$k} = $opts->{$k} if defined($opts->{$k}); | ||
| 127 | } | ||
| 128 | |||
| 129 | if (! $entry->{'relative_name'}) { | ||
| 130 | $entry->{'relative_name'} = $entry->{'absolute_name'}; | ||
| 131 | $entry->{'relative_name'} =~ s/^\///o; | ||
| 132 | } | ||
| 133 | if (! $entry->{'short_name'}) { | ||
| 134 | $entry->{'short_name'} = File::Basename::basename($entry->{'absolute_name'}); | ||
| 135 | } | ||
| 136 | |||
| 137 | if (-l $entry->{'absolute_name'}) { | ||
| 138 | $entry->{'type'} = "symlink"; | ||
| 139 | $entry->{'symlink_target'} = readlink($entry->{'absolute_name'}); | ||
| 140 | |||
| 141 | # calculate absolute path for relative symlinks | ||
| 142 | # | ||
| 143 | if ($entry->{'symlink_target'} !~ /^\//o) { | ||
| 144 | |||
| 145 | my $abs_dir = dirname($entry->{'absolute_name'}); | ||
| 146 | $abs_dir = $abs_dir . ($abs_dir eq "/" ? "" : "/") . $entry->{'symlink_target'}; | ||
| 147 | |||
| 148 | $entry->{'symlink_target_abs'} = $abs_dir; | ||
| 149 | } | ||
| 150 | else { | ||
| 151 | $entry->{'symlink_target_abs'} = $entry->{'symlink_target'}; | ||
| 152 | } | ||
| 153 | } | ||
| 154 | elsif (-d $entry->{'absolute_name'}) { | ||
| 155 | $entry->{'type'} = "dir"; | ||
| 156 | } | ||
| 157 | else { | ||
| 158 | $entry->{'type'} = "file"; | ||
| 159 | } | ||
| 160 | |||
| 161 | my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, | ||
| 162 | $atime,$mtime,$ctime,$blksize,$blocks) = lstat($entry->{'absolute_name'}); | ||
| 163 | |||
| 164 | # extract MASK as specified in http://perldoc.perl.org/functions/stat.html | ||
| 165 | $mode = $mode & 07777; | ||
| 166 | |||
| 167 | # saving entry attributes | ||
| 168 | $entry->{'mode'} = $mode; | ||
| 169 | $entry->{'uid'} = $uid; | ||
| 170 | $entry->{'gid'} = $gid; | ||
| 171 | # $entry->{'atime'} = $atime; | ||
| 172 | $entry->{'mtime'} = $mtime; | ||
| 173 | $entry->{'size'} = $size; | ||
| 174 | # $entry->{'mode_printable'} = sprintf("%3o", $mode); | ||
| 175 | |||
| 176 | return $entry; | ||
| 177 | } | ||
| 178 | |||
| 179 | sub read_dir { | ||
| 180 | my ($dirname, $opts) = @_; | ||
| 181 | |||
| 182 | $opts = {} unless $opts; | ||
| 183 | $opts->{'output_type'} = 'arrayref' | ||
| 184 | unless $opts->{'output_type'}; | ||
| 185 | |||
| 186 | my $dummy; | ||
| 187 | if (!opendir($dummy, $dirname)) { | ||
| 188 | if ($opts->{'non_fatal'}) { | ||
| 189 | return 0; | ||
| 190 | } | ||
| 191 | else { | ||
| 192 | psSnake::die("ERROR: unable to open directory [$dirname]"); | ||
| 193 | } | ||
| 194 | } | ||
| 195 | |||
| 196 | my @all_entries = readdir($dummy); | ||
| 197 | close($dummy); | ||
| 198 | |||
| 199 | my $entries; | ||
| 200 | if ($opts->{'output_type'} eq 'arrayref') { | ||
| 201 | $entries = []; | ||
| 202 | } | ||
| 203 | elsif ($opts->{'output_type'} eq 'hashref') { | ||
| 204 | $entries = {}; | ||
| 205 | } | ||
| 206 | |||
| 207 | foreach my $e (sort @all_entries) { | ||
| 208 | next if $e eq '.' || $e eq '..'; | ||
| 209 | |||
| 210 | my $absolute_name = $dirname . "/" . $e; | ||
| 211 | |||
| 212 | if ($opts->{'output_type'} eq 'arrayref') { | ||
| 213 | # skipping non-directories if requested | ||
| 214 | # effectively means "get only files"; | ||
| 215 | if ($opts->{'only-directories'}) { | ||
| 216 | next if -l $absolute_name || ! -d $absolute_name; | ||
| 217 | } | ||
| 218 | |||
| 219 | # symlinks are also files | ||
| 220 | if ($opts->{'only-files'}) { | ||
| 221 | next if -d $absolute_name && ! -l $absolute_name; | ||
| 222 | } | ||
| 223 | |||
| 224 | # simple output, feasible only | ||
| 225 | # for non-recursive directory reads | ||
| 226 | push(@{$entries}, $e); | ||
| 227 | } | ||
| 228 | elsif ($opts->{'output_type'} eq 'hashref') { | ||
| 229 | # used to generate following type of struct | ||
| 230 | # | ||
| 231 | # "etc" => { | ||
| 232 | # "short_name" => "etc", | ||
| 233 | # "relative_name" => "etc", | ||
| 234 | # "type" => "dir", | ||
| 235 | # } | ||
| 236 | # "etc/passwd" => { | ||
| 237 | # "short_name" => "passwd", | ||
| 238 | # "relative_name" => "etc/passwd", | ||
| 239 | # "type" => "file", | ||
| 240 | # } | ||
| 241 | |||
| 242 | my $relative_entry_name = ""; | ||
| 243 | |||
| 244 | # append entry relative path (if we're recursing) | ||
| 245 | if (defined($opts->{'recursed_dir'})) { | ||
| 246 | $relative_entry_name = $opts->{'recursed_dir'} . "/"; | ||
| 247 | } | ||
| 248 | |||
| 249 | # append entry short name | ||
| 250 | $relative_entry_name .= $e; | ||
| 251 | |||
| 252 | # populate entry struct | ||
| 253 | my $entry = psSnake::fileinfo_struct({ | ||
| 254 | 'absolute_name' => $absolute_name, | ||
| 255 | 'relative_name' => $relative_entry_name, | ||
| 256 | 'short_name' => $e, | ||
| 257 | 'user_map' => $opts->{'user_map'}, | ||
| 258 | 'group_map' => $opts->{'group_map'}, | ||
| 259 | }); | ||
| 260 | |||
| 261 | # append entry | ||
| 262 | $entries->{$relative_entry_name} = $entry; | ||
| 263 | |||
| 264 | # do recursion into directories | ||
| 265 | # (but not into symlinked directories!) | ||
| 266 | if (-d $absolute_name && ! -l $absolute_name) { | ||
| 267 | my $opts_r = Storable::dclone($opts); | ||
| 268 | $opts_r->{'recursed_dir'} = $relative_entry_name; | ||
| 269 | |||
| 270 | my $e = read_dir($absolute_name, $opts_r); | ||
| 271 | foreach my $ee (keys %{$e}) { | ||
| 272 | $entries->{$ee} = $e->{$ee}; | ||
| 273 | } | ||
| 274 | } | ||
| 275 | } | ||
| 276 | } | ||
| 277 | |||
| 278 | return $entries; | ||
| 279 | } | ||
| 280 | |||
| 281 | # incompatible with POSIX::SigAction | ||
| 282 | # | ||
| 283 | sub install_layered_signal { | ||
| 284 | my ($s, $handler_code) = @_; | ||
| 285 | |||
| 286 | my %available_signals = map {$_ => 1} keys %SIG; | ||
| 287 | |||
| 288 | psSnake::die("install_layered_signal got nonexistent signal name [$s]") | ||
| 289 | unless defined($available_signals{$s}); | ||
| 290 | psSnake::die("install_layered_signal expects coderef") | ||
| 291 | if !ref($handler_code) || ref($handler_code) ne 'CODE'; | ||
| 292 | |||
| 293 | my $previous_handler = $SIG{$s}; | ||
| 294 | |||
| 295 | my $sig_handler = sub { | ||
| 296 | my ($called_sig_name, @sig_param) = @_; | ||
| 297 | |||
| 298 | # $s is a closure refering to real signal name | ||
| 299 | # for which this handler is being installed. | ||
| 300 | # it is used to distinguish between | ||
| 301 | # real signal handlers and aliased signal handlers | ||
| 302 | my $signal_name = $s; | ||
| 303 | |||
| 304 | # $called_sig_name is a signal name which | ||
| 305 | # was passed to this signal handler; | ||
| 306 | # it doesn't equal $signal_name in case | ||
| 307 | # some signal handlers in %SIG point | ||
| 308 | # to other signal handler (CHLD and CLD, | ||
| 309 | # ABRT and IOT) | ||
| 310 | # | ||
| 311 | # initial signal handler for aliased signal | ||
| 312 | # calles some other signal handler which | ||
| 313 | # should not execute the same handler_code again | ||
| 314 | if ($called_sig_name eq $signal_name) { | ||
| 315 | $handler_code->($signal_name); | ||
| 316 | } | ||
| 317 | |||
| 318 | # run original signal handler if any (including aliased) | ||
| 319 | # | ||
| 320 | if (ref($previous_handler)) { | ||
| 321 | $previous_handler->($called_sig_name, @sig_param); | ||
| 322 | } | ||
| 323 | }; | ||
| 324 | |||
| 325 | $SIG{$s} = $sig_handler; | ||
| 326 | } | ||
| 327 | |||
| 328 | # give process a chance sending TERM, | ||
| 329 | # waiting for a while (2 seconds) | ||
| 330 | # and killing it with KILL | ||
| 331 | sub kill_gently { | ||
| 332 | my ($pid, $opts) = @_; | ||
| 333 | |||
| 334 | $opts = {} unless $opts; | ||
| 335 | $opts->{'wait_time'} = 2 unless defined($opts->{'wait_time'}); | ||
| 336 | $opts->{'first_kill_type'} = 'just_process' unless $opts->{'first_kill_type'}; | ||
| 337 | $opts->{'final_kill_type'} = 'just_process' unless $opts->{'final_kill_type'}; | ||
| 338 | |||
| 339 | if ($opts->{'first_kill_type'} eq 'just_process') { | ||
| 340 | kill(15, $pid); | ||
| 341 | } | ||
| 342 | elsif ($opts->{'first_kill_type'} eq 'process_group') { | ||
| 343 | kill(-15, $pid); | ||
| 344 | } | ||
| 345 | |||
| 346 | my $child_finished = 0; | ||
| 347 | my $wait_start_time = time(); | ||
| 348 | |||
| 349 | while (!$child_finished && $wait_start_time + $opts->{'wait_time'} > time()) { | ||
| 350 | my $waitpid = waitpid($pid, WNOHANG); | ||
| 351 | if ($waitpid eq -1) { | ||
| 352 | $child_finished = 1; | ||
| 353 | } | ||
| 354 | Time::HiRes::usleep(250000); # quarter of a second | ||
| 355 | } | ||
| 356 | |||
| 357 | if (!$child_finished) { | ||
| 358 | if ($opts->{'final_kill_type'} eq 'just_process') { | ||
| 359 | kill(9, $pid); | ||
| 360 | } | ||
| 361 | elsif ($opts->{'final_kill_type'} eq 'process_group') { | ||
| 362 | kill(-9, $pid); | ||
| 363 | } | ||
| 364 | } | ||
| 365 | } | ||
| 366 | |||
| 367 | sub open3_run { | ||
| 368 | my ($cmd, $opts) = @_; | ||
| 369 | |||
| 370 | $opts = {} unless $opts; | ||
| 371 | |||
| 372 | my $child_in = FileHandle->new; | ||
| 373 | my $child_out = FileHandle->new; | ||
| 374 | my $child_err = FileHandle->new; | ||
| 375 | $child_out->autoflush(1); | ||
| 376 | $child_err->autoflush(1); | ||
| 377 | |||
| 378 | my $pid = open3($child_in, $child_out, $child_err, $cmd); | ||
| 379 | |||
| 380 | # push my child's pid to our parent | ||
| 381 | # so in case i am killed parent | ||
| 382 | # could stop my child (search for | ||
| 383 | # child_child_pid in parent code) | ||
| 384 | if ($opts->{'parent_info'}) { | ||
| 385 | my $ps = $opts->{'parent_info'}; | ||
| 386 | print $ps "spawned $pid\n"; | ||
| 387 | } | ||
| 388 | |||
| 389 | if ($child_in && $child_out->opened && $opts->{'child_stdin'}) { | ||
| 390 | |||
| 391 | # If the child process dies for any reason, | ||
| 392 | # the next write to CHLD_IN is likely to generate | ||
| 393 | # a SIGPIPE in the parent, which is fatal by default. | ||
| 394 | # So you may wish to handle this signal. | ||
| 395 | # | ||
| 396 | # from http://perldoc.perl.org/IPC/Open3.html, | ||
| 397 | # absolutely needed to catch piped commands errors. | ||
| 398 | # | ||
| 399 | local $SIG{'SIG_PIPE'} = sub { 1; }; | ||
| 400 | |||
| 401 | print $child_in $opts->{'child_stdin'}; | ||
| 402 | } | ||
| 403 | close($child_in); | ||
| 404 | |||
| 405 | my $child_output = { | ||
| 406 | 'out' => $child_out->fileno, | ||
| 407 | 'err' => $child_err->fileno, | ||
| 408 | $child_out->fileno => { | ||
| 409 | 'parent_socket' => $opts->{'parent_stdout'}, | ||
| 410 | 'scalar_buffer' => "", | ||
| 411 | 'child_handle' => $child_out, | ||
| 412 | 'block_size' => ($child_out->stat)[11] || 1024, | ||
| 413 | }, | ||
| 414 | $child_err->fileno => { | ||
| 415 | 'parent_socket' => $opts->{'parent_stderr'}, | ||
| 416 | 'scalar_buffer' => "", | ||
| 417 | 'child_handle' => $child_err, | ||
| 418 | 'block_size' => ($child_err->stat)[11] || 1024, | ||
| 419 | }, | ||
| 420 | }; | ||
| 421 | |||
| 422 | my $select = IO::Select->new(); | ||
| 423 | $select->add($child_out, $child_err); | ||
| 424 | |||
| 425 | # pass any signal to the child | ||
| 426 | # effectively creating process | ||
| 427 | # strongly attached to the child: | ||
| 428 | # it will terminate only after child | ||
| 429 | # has terminated (except for SIGKILL, | ||
| 430 | # which is specially handled) | ||
| 431 | foreach my $s (keys %SIG) { | ||
| 432 | my $sig_handler; | ||
| 433 | $sig_handler = sub { | ||
| 434 | kill("$s", $pid); | ||
| 435 | $SIG{$s} = $sig_handler; | ||
| 436 | }; | ||
| 437 | $SIG{$s} = $sig_handler; | ||
| 438 | } | ||
| 439 | |||
| 440 | my $child_finished = 0; | ||
| 441 | |||
| 442 | my $got_sig_child = 0; | ||
| 443 | $SIG{'CHLD'} = sub { $got_sig_child = time(); }; | ||
| 444 | |||
| 445 | while(!$child_finished && ($child_out->opened || $child_err->opened)) { | ||
| 446 | |||
| 447 | # parent was killed otherwise we would have got | ||
| 448 | # the same signal as parent and process it same way | ||
| 449 | if (getppid() eq "1") { | ||
| 450 | |||
| 451 | # end my process group with all the children | ||
| 452 | # (i am the process group leader, so my pid | ||
| 453 | # equals to the process group id) | ||
| 454 | # | ||
| 455 | # same thing which is done | ||
| 456 | # with $opts->{'clean_up_children'} | ||
| 457 | # in run_forked | ||
| 458 | # | ||
| 459 | kill(-9, $$); | ||
| 460 | |||
| 461 | # shouldn't reach here | ||
| 462 | exit 1; | ||
| 463 | } | ||
| 464 | |||
| 465 | if ($got_sig_child) { | ||
| 466 | if (time() - $got_sig_child > 1) { | ||
| 467 | # select->can_read doesn't return 0 after SIG_CHLD | ||
| 468 | # | ||
| 469 | # "On POSIX-compliant platforms, SIGCHLD is the signal | ||
| 470 | # sent to a process when a child process terminates." | ||
| 471 | # http://en.wikipedia.org/wiki/SIGCHLD | ||
| 472 | # | ||
| 473 | # nevertheless kill KILL wouldn't break anything here | ||
| 474 | # | ||
| 475 | kill (9, $pid); | ||
| 476 | $child_finished = 1; | ||
| 477 | } | ||
| 478 | } | ||
| 479 | |||
| 480 | Time::HiRes::usleep(1); | ||
| 481 | |||
| 482 | foreach my $fd ($select->can_read(1/100)) { | ||
| 483 | my $str = $child_output->{$fd->fileno}; | ||
| 484 | psSnake::die("child stream not found: $fd") unless $str; | ||
| 485 | |||
| 486 | my $data; | ||
| 487 | my $count = $fd->sysread($data, $str->{'block_size'}); | ||
| 488 | |||
| 489 | if ($count) { | ||
| 490 | if ($str->{'parent_socket'}) { | ||
| 491 | my $ph = $str->{'parent_socket'}; | ||
| 492 | print $ph $data; | ||
| 493 | } | ||
| 494 | else { | ||
| 495 | $str->{'scalar_buffer'} .= $data; | ||
| 496 | } | ||
| 497 | } | ||
| 498 | elsif ($count eq 0) { | ||
| 499 | $select->remove($fd); | ||
| 500 | $fd->close(); | ||
| 501 | } | ||
| 502 | else { | ||
| 503 | psSnake::die("error during sysread: " . $!); | ||
| 504 | } | ||
| 505 | } | ||
| 506 | } | ||
| 507 | |||
| 508 | my $waitpid_ret = waitpid($pid, 0); | ||
| 509 | my $real_exit = $?; | ||
| 510 | my $exit_value = $real_exit >> 8; | ||
| 511 | |||
| 512 | # since we've successfully reaped the child, | ||
| 513 | # let our parent know about this. | ||
| 514 | # | ||
| 515 | if ($opts->{'parent_info'}) { | ||
| 516 | my $ps = $opts->{'parent_info'}; | ||
| 517 | |||
| 518 | # child was killed, inform parent | ||
| 519 | if ($real_exit & 127) { | ||
| 520 | print $ps "$pid killed with " . ($real_exit & 127) . "\n"; | ||
| 521 | |||
| 522 | } | ||
| 523 | |||
| 524 | print $ps "reaped $pid\n"; | ||
| 525 | } | ||
| 526 | |||
| 527 | if ($opts->{'parent_stdout'} || $opts->{'parent_stderr'}) { | ||
| 528 | return $exit_value; | ||
| 529 | } | ||
| 530 | else { | ||
| 531 | return { | ||
| 532 | 'stdout' => $child_output->{$child_output->{'out'}}->{'scalar_buffer'}, | ||
| 533 | 'stderr' => $child_output->{$child_output->{'err'}}->{'scalar_buffer'}, | ||
| 534 | 'exit_code' => $exit_value, | ||
| 535 | }; | ||
| 536 | } | ||
| 537 | } | ||
| 538 | |||
| 539 | sub run_forked { | ||
| 540 | my ($cmd, $opts) = @_; | ||
| 541 | |||
| 542 | $opts = {} unless $opts; | ||
| 543 | $opts->{'timeout'} = 0 unless $opts->{'timeout'}; | ||
| 544 | $opts->{'terminate_wait_time'} = 2 unless defined($opts->{'terminate_wait_time'}); | ||
| 545 | |||
| 546 | # sockets to pass child stdout to parent | ||
| 547 | my $child_stdout_socket; | ||
| 548 | my $parent_stdout_socket; | ||
| 549 | |||
| 550 | # sockets to pass child stderr to parent | ||
| 551 | my $child_stderr_socket; | ||
| 552 | my $parent_stderr_socket; | ||
| 553 | |||
| 554 | # sockets for child -> parent internal communication | ||
| 555 | my $child_info_socket; | ||
| 556 | my $parent_info_socket; | ||
| 557 | |||
| 558 | socketpair($child_stdout_socket, $parent_stdout_socket, AF_UNIX, SOCK_STREAM, PF_UNSPEC) || | ||
| 559 | psSnake::die ("socketpair: $!"); | ||
| 560 | socketpair($child_stderr_socket, $parent_stderr_socket, AF_UNIX, SOCK_STREAM, PF_UNSPEC) || | ||
| 561 | psSnake::die ("socketpair: $!"); | ||
| 562 | socketpair($child_info_socket, $parent_info_socket, AF_UNIX, SOCK_STREAM, PF_UNSPEC) || | ||
| 563 | psSnake::die ("socketpair: $!"); | ||
| 564 | |||
| 565 | $child_stdout_socket->autoflush(1); | ||
| 566 | $parent_stdout_socket->autoflush(1); | ||
| 567 | $child_stderr_socket->autoflush(1); | ||
| 568 | $parent_stderr_socket->autoflush(1); | ||
| 569 | $child_info_socket->autoflush(1); | ||
| 570 | $parent_info_socket->autoflush(1); | ||
| 571 | |||
| 572 | my $start_time = time(); | ||
| 573 | |||
| 574 | my $pid; | ||
| 575 | if ($pid = fork) { | ||
| 576 | |||
| 577 | # we are a parent | ||
| 578 | close($parent_stdout_socket); | ||
| 579 | close($parent_stderr_socket); | ||
| 580 | close($parent_info_socket); | ||
| 581 | |||
| 582 | my $flags; | ||
| 583 | |||
| 584 | # prepare sockets to read from child | ||
| 585 | |||
| 586 | $flags = 0; | ||
| 587 | fcntl($child_stdout_socket, F_GETFL, $flags) || psSnake::die("can't fnctl F_GETFL: $!"); | ||
| 588 | $flags |= O_NONBLOCK; | ||
| 589 | fcntl($child_stdout_socket, F_SETFL, $flags) || psSnake::die("can't fnctl F_SETFL: $!"); | ||
| 590 | |||
| 591 | $flags = 0; | ||
| 592 | fcntl($child_stderr_socket, F_GETFL, $flags) || psSnake::die("can't fnctl F_GETFL: $!"); | ||
| 593 | $flags |= O_NONBLOCK; | ||
| 594 | fcntl($child_stderr_socket, F_SETFL, $flags) || psSnake::die("can't fnctl F_SETFL: $!"); | ||
| 595 | |||
| 596 | $flags = 0; | ||
| 597 | fcntl($child_info_socket, F_GETFL, $flags) || psSnake::die("can't fnctl F_GETFL: $!"); | ||
| 598 | $flags |= O_NONBLOCK; | ||
| 599 | fcntl($child_info_socket, F_SETFL, $flags) || psSnake::die("can't fnctl F_SETFL: $!"); | ||
| 600 | |||
| 601 | # print "child $pid started\n"; | ||
| 602 | |||
| 603 | my $child_timedout = 0; | ||
| 604 | my $child_finished = 0; | ||
| 605 | my $child_stdout = ''; | ||
| 606 | my $child_stderr = ''; | ||
| 607 | my $child_merged = ''; | ||
| 608 | my $child_exit_code = 0; | ||
| 609 | my $child_killed_by_signal = 0; | ||
| 610 | my $parent_died = 0; | ||
| 611 | |||
| 612 | my $got_sig_child = 0; | ||
| 613 | my $got_sig_quit = 0; | ||
| 614 | $SIG{'CHLD'} = sub { $got_sig_child = time(); }; | ||
| 615 | |||
| 616 | if ($opts->{'terminate_on_signal'}) { | ||
| 617 | install_layered_signal($opts->{'terminate_on_signal'}, sub { $got_sig_quit = time(); }); | ||
| 618 | } | ||
| 619 | |||
| 620 | my $child_child_pid; | ||
| 621 | |||
| 622 | while (!$child_finished) { | ||
| 623 | my $now = time(); | ||
| 624 | |||
| 625 | if ($opts->{'terminate_on_parent_sudden_death'}) { | ||
| 626 | $opts->{'runtime'}->{'last_parent_check'} = 0 | ||
| 627 | unless defined($opts->{'runtime'}->{'last_parent_check'}); | ||
| 628 | |||
| 629 | # check for parent once each five seconds | ||
| 630 | if ($now - $opts->{'runtime'}->{'last_parent_check'} > 5) { | ||
| 631 | if (getppid() eq "1") { | ||
| 632 | kill_gently ($pid, { | ||
| 633 | 'first_kill_type' => 'process_group', | ||
| 634 | 'final_kill_type' => 'process_group', | ||
| 635 | 'wait_time' => $opts->{'terminate_wait_time'} | ||
| 636 | }); | ||
| 637 | $parent_died = 1; | ||
| 638 | } | ||
| 639 | |||
| 640 | $opts->{'runtime'}->{'last_parent_check'} = $now; | ||
| 641 | } | ||
| 642 | } | ||
| 643 | |||
| 644 | # user specified timeout | ||
| 645 | if ($opts->{'timeout'}) { | ||
| 646 | if ($now - $start_time > $opts->{'timeout'}) { | ||
| 647 | kill_gently ($pid, { | ||
| 648 | 'first_kill_type' => 'process_group', | ||
| 649 | 'final_kill_type' => 'process_group', | ||
| 650 | 'wait_time' => $opts->{'terminate_wait_time'} | ||
| 651 | }); | ||
| 652 | $child_timedout = 1; | ||
| 653 | } | ||
| 654 | } | ||
| 655 | |||
| 656 | # give OS 10 seconds for correct return of waitpid, | ||
| 657 | # kill process after that and finish wait loop; | ||
| 658 | # shouldn't ever happen -- remove this code? | ||
| 659 | if ($got_sig_child) { | ||
| 660 | if ($now - $got_sig_child > 10) { | ||
| 661 | print STDERR "waitpid did not return -1 for 10 seconds after SIG_CHLD, killing [$pid]\n"; | ||
| 662 | kill (-9, $pid); | ||
| 663 | $child_finished = 1; | ||
| 664 | } | ||
| 665 | } | ||
| 666 | |||
| 667 | if ($got_sig_quit) { | ||
| 668 | # psSnake::do_log("ending process group $pid", {'stderr' => 1}); | ||
| 669 | kill_gently ($pid, { | ||
| 670 | 'first_kill_type' => 'process_group', | ||
| 671 | 'final_kill_type' => 'process_group', | ||
| 672 | 'wait_time' => $opts->{'terminate_wait_time'} | ||
| 673 | }); | ||
| 674 | $child_finished = 1; | ||
| 675 | } | ||
| 676 | |||
| 677 | my $waitpid = waitpid($pid, WNOHANG); | ||
| 678 | |||
| 679 | # child finished, catch it's exit status | ||
| 680 | if ($waitpid ne 0 && $waitpid ne -1) { | ||
| 681 | $child_exit_code = $? >> 8; | ||
| 682 | } | ||
| 683 | |||
| 684 | if ($waitpid eq -1) { | ||
| 685 | $child_finished = 1; | ||
| 686 | next; | ||
| 687 | } | ||
| 688 | |||
| 689 | # child -> parent simple internal communication protocol | ||
| 690 | while (my $l = <$child_info_socket>) { | ||
| 691 | if ($l =~ /^spawned ([0-9]+?)\n(.*?)/so) { | ||
| 692 | $child_child_pid = $1; | ||
| 693 | $l = $2; | ||
| 694 | } | ||
| 695 | if ($l =~ /^reaped ([0-9]+?)\n(.*?)/so) { | ||
| 696 | $child_child_pid = undef; | ||
| 697 | $l = $2; | ||
| 698 | } | ||
| 699 | if ($l =~ /^[\d]+ killed with ([0-9]+?)\n(.*?)/so) { | ||
| 700 | $child_killed_by_signal = $1; | ||
| 701 | $l = $2; | ||
| 702 | } | ||
| 703 | } | ||
| 704 | |||
| 705 | while (my $l = <$child_stdout_socket>) { | ||
| 706 | if (!$opts->{'discard_output'}) { | ||
| 707 | $child_stdout .= $l; | ||
| 708 | $child_merged .= $l; | ||
| 709 | } | ||
| 710 | |||
| 711 | if ($opts->{'stdout_handler'} && ref($opts->{'stdout_handler'}) eq 'CODE') { | ||
| 712 | $opts->{'stdout_handler'}->($l); | ||
| 713 | } | ||
| 714 | } | ||
| 715 | while (my $l = <$child_stderr_socket>) { | ||
| 716 | if (!$opts->{'discard_output'}) { | ||
| 717 | $child_stderr .= $l; | ||
| 718 | $child_merged .= $l; | ||
| 719 | } | ||
| 720 | |||
| 721 | if ($opts->{'stderr_handler'} && ref($opts->{'stderr_handler'}) eq 'CODE') { | ||
| 722 | $opts->{'stderr_handler'}->($l); | ||
| 723 | } | ||
| 724 | } | ||
| 725 | |||
| 726 | Time::HiRes::usleep(1); | ||
| 727 | } | ||
| 728 | |||
| 729 | # $child_pid_pid is not defined in two cases: | ||
| 730 | # * when our child was killed before | ||
| 731 | # it had chance to tell us the pid | ||
| 732 | # of the child it spawned. we can do | ||
| 733 | # nothing in this case :( | ||
| 734 | # * our child successfully reaped its child, | ||
| 735 | # we have nothing left to do in this case | ||
| 736 | # | ||
| 737 | # defined $child_pid_pid means child's child | ||
| 738 | # has not died but nobody is waiting for it, | ||
| 739 | # killing it brutaly. | ||
| 740 | # | ||
| 741 | if ($child_child_pid) { | ||
| 742 | kill_gently($child_child_pid); | ||
| 743 | } | ||
| 744 | |||
| 745 | # in case there are forks in child which | ||
| 746 | # do not forward or process signals (TERM) correctly | ||
| 747 | # kill whole child process group, effectively trying | ||
| 748 | # not to return with some children or their parts still running | ||
| 749 | # | ||
| 750 | # to be more accurate -- we need to be sure | ||
| 751 | # that this is process group created by our child | ||
| 752 | # (and not some other process group with the same pgid, | ||
| 753 | # created just after death of our child) -- fortunately | ||
| 754 | # this might happen only when process group ids | ||
| 755 | # are reused quickly (there are lots of processes | ||
| 756 | # spawning new process groups for example) | ||
| 757 | # | ||
| 758 | if ($opts->{'clean_up_children'}) { | ||
| 759 | kill(-9, $pid); | ||
| 760 | } | ||
| 761 | |||
| 762 | # print "child $pid finished\n"; | ||
| 763 | |||
| 764 | close($child_stdout_socket); | ||
| 765 | close($child_stderr_socket); | ||
| 766 | close($child_info_socket); | ||
| 767 | |||
| 768 | my $o = { | ||
| 769 | 'stdout' => $child_stdout, | ||
| 770 | 'stderr' => $child_stderr, | ||
| 771 | 'merged' => $child_merged, | ||
| 772 | 'timeout' => $child_timedout ? $opts->{'timeout'} : 0, | ||
| 773 | 'exit_code' => $child_exit_code, | ||
| 774 | 'parent_died' => $parent_died, | ||
| 775 | 'killed_by_signal' => $child_killed_by_signal, | ||
| 776 | 'child_pgid' => $pid, | ||
| 777 | }; | ||
| 778 | |||
| 779 | my $err_msg = ""; | ||
| 780 | if ($o->{'exit_code'}) { | ||
| 781 | $err_msg .= "exited with code [$o->{'exit_code'}]\n"; | ||
| 782 | } | ||
| 783 | if ($o->{'timeout'}) { | ||
| 784 | $err_msg .= "ran more than [$o->{'timeout'}] seconds\n"; | ||
| 785 | } | ||
| 786 | if ($o->{'parent_died'}) { | ||
| 787 | $err_msg .= "parent died\n"; | ||
| 788 | } | ||
| 789 | if ($o->{'stdout'}) { | ||
| 790 | $err_msg .= "stdout:\n" . $o->{'stdout'} . "\n"; | ||
| 791 | } | ||
| 792 | if ($o->{'stderr'}) { | ||
| 793 | $err_msg .= "stderr:\n" . $o->{'stderr'} . "\n"; | ||
| 794 | } | ||
| 795 | if ($o->{'killed_by_signal'}) { | ||
| 796 | $err_msg .= "killed by signal [" . $o->{'killed_by_signal'} . "]\n"; | ||
| 797 | } | ||
| 798 | $o->{'err_msg'} = $err_msg; | ||
| 799 | |||
| 800 | return $o; | ||
| 801 | } | ||
| 802 | else { | ||
| 803 | psSnake::die("cannot fork: $!") unless defined($pid); | ||
| 804 | |||
| 805 | # create new process session for open3 call, | ||
| 806 | # so we hopefully can kill all the subprocesses | ||
| 807 | # which might be spawned in it (except for those | ||
| 808 | # which do setsid theirselves -- can't do anything | ||
| 809 | # with those) | ||
| 810 | |||
| 811 | POSIX::setsid() || psSnake::die("Error running setsid: " . $!); | ||
| 812 | |||
| 813 | close($child_stdout_socket); | ||
| 814 | close($child_stderr_socket); | ||
| 815 | close($child_info_socket); | ||
| 816 | |||
| 817 | my $child_exit_code; | ||
| 818 | |||
| 819 | # allow both external programs | ||
| 820 | # and internal perl calls | ||
| 821 | if (!ref($cmd)) { | ||
| 822 | $child_exit_code = open3_run($cmd, { | ||
| 823 | 'parent_info' => $parent_info_socket, | ||
| 824 | 'parent_stdout' => $parent_stdout_socket, | ||
| 825 | 'parent_stderr' => $parent_stderr_socket, | ||
| 826 | 'child_stdin' => $opts->{'child_stdin'}, | ||
| 827 | }); | ||
| 828 | } | ||
| 829 | elsif (ref($cmd) eq 'CODE') { | ||
| 830 | $child_exit_code = $cmd->({ | ||
| 831 | 'opts' => $opts, | ||
| 832 | 'parent_info' => $parent_info_socket, | ||
| 833 | 'parent_stdout' => $parent_stdout_socket, | ||
| 834 | 'parent_stderr' => $parent_stderr_socket, | ||
| 835 | 'child_stdin' => $opts->{'child_stdin'}, | ||
| 836 | }); | ||
| 837 | } | ||
| 838 | else { | ||
| 839 | print $parent_stderr_socket "Invalid command reference: " . ref($cmd) . "\n"; | ||
| 840 | $child_exit_code = 1; | ||
| 841 | } | ||
| 842 | |||
| 843 | close($parent_stdout_socket); | ||
| 844 | close($parent_stderr_socket); | ||
| 845 | close($parent_info_socket); | ||
| 846 | |||
| 847 | exit $child_exit_code; | ||
| 848 | } | ||
| 849 | } | ||
| 850 | |||
| 851 | sub debug2 { | ||
| 852 | my ($text, $opts) = @_; | ||
| 853 | |||
| 854 | if ($psSnake::debug2) { | ||
| 855 | debug($text, $opts); | ||
| 856 | } | ||
| 857 | } | ||
| 858 | |||
| 859 | sub debug { | ||
| 860 | my ($text, $opts) = @_; | ||
| 861 | |||
| 862 | $opts = {} unless $opts; | ||
| 863 | |||
| 864 | if ($psSnake::debug) { | ||
| 865 | my $stamp = localtime() . ": "; | ||
| 866 | |||
| 867 | utf8::encode($text) if utf8::is_utf8($text); | ||
| 868 | |||
| 869 | if ($opts->{'stderr'}) { | ||
| 870 | if (ref($text)) { | ||
| 871 | print STDERR join("", map { "$stamp$_\n" } Dumper($text)); | ||
| 872 | } | ||
| 873 | else { | ||
| 874 | print STDERR $stamp . ($text ? $text : "") . | ||
| 875 | ($text =~ /[\r\n]$/so ? "" : "\n"); | ||
| 876 | } | ||
| 877 | } | ||
| 878 | else { | ||
| 879 | if (ref($text)) { | ||
| 880 | print join("", map { "$stamp$_\n" } Dumper($text)); | ||
| 881 | } | ||
| 882 | else { | ||
| 883 | print $stamp . ($text ? $text : "") . | ||
| 884 | ($text =~ /[\r\n]$/so ? "" : "\n"); | ||
| 885 | } | ||
| 886 | } | ||
| 887 | } | ||
| 888 | } | ||
| 889 | |||
| 890 | # safe_open and safe_close are copied | ||
| 891 | # from ps_farm.pm (should be one library actually) | ||
| 892 | sub safe_open { | ||
| 893 | my ($filename, $mode, $opts) = @_; | ||
| 894 | |||
| 895 | $opts = {} unless $opts; | ||
| 896 | $opts->{'timeout'} = 30 unless defined($opts->{'timeout'}); | ||
| 897 | |||
| 898 | $mode = "open" unless $mode; | ||
| 899 | |||
| 900 | if ($mode eq "overwrite" || $mode eq ">") { | ||
| 901 | $mode = ">"; | ||
| 902 | } | ||
| 903 | elsif ($mode eq "append" || $mode eq ">>") { | ||
| 904 | $mode = ">>"; | ||
| 905 | } | ||
| 906 | else { | ||
| 907 | $mode = ""; | ||
| 908 | } | ||
| 909 | |||
| 910 | my $fh; | ||
| 911 | my $i=0; | ||
| 912 | while (! open($fh, "${mode}${filename}")) { | ||
| 913 | $i = $i + 1; | ||
| 914 | if ($i > $opts->{'timeout'}) { | ||
| 915 | print STDERR "Unable to open $filename\n" if ! $opts->{'silent'}; | ||
| 916 | return 0; | ||
| 917 | } | ||
| 918 | |||
| 919 | print STDERR "still trying to open $filename\n" if ! $opts->{'silent'}; | ||
| 920 | sleep 1; | ||
| 921 | } | ||
| 922 | |||
| 923 | # http://perldoc.perl.org/functions/flock.html | ||
| 924 | # | ||
| 925 | # LOCK_SH, LOCK_EX, LOCK_UN, LOCK_NB <=> 1, 2, 8, 4 | ||
| 926 | # | ||
| 927 | # If LOCK_NB is bitwise-or'ed with LOCK_SH or LOCK_EX | ||
| 928 | # then flock will return immediately | ||
| 929 | |||
| 930 | while (! flock($fh, 2 | 4)) { | ||
| 931 | $i = $i + 1; | ||
| 932 | if ($i > $opts->{'timeout'}) { | ||
| 933 | print STDERR "Unable to lock $filename\n" if ! $opts->{'silent'}; | ||
| 934 | return 0; | ||
| 935 | } | ||
| 936 | |||
| 937 | print STDERR "still trying to lock $filename\n" if ! $opts->{'silent'}; | ||
| 938 | sleep 1; | ||
| 939 | } | ||
| 940 | |||
| 941 | my $fh1; | ||
| 942 | if (!open($fh1, "${mode}${filename}")) { | ||
| 943 | $i = $i + 1; | ||
| 944 | if ($i > $opts->{'timeout'}) { | ||
| 945 | print STDERR "Unable to open and lock $filename\n" if ! $opts->{'silent'}; | ||
| 946 | return 0; | ||
| 947 | } | ||
| 948 | |||
| 949 | print STDERR "Locked $filename, but it's gone. Retrying...\n" if ! $opts->{'silent'}; | ||
| 950 | $opts->{'timeout'} = $opts->{'timeout'} - 1; | ||
| 951 | return safe_open($filename, $mode, $opts); | ||
| 952 | } | ||
| 953 | else { | ||
| 954 | close($fh1); | ||
| 955 | return $fh; | ||
| 956 | } | ||
| 957 | } | ||
| 958 | |||
| 959 | sub safe_close { | ||
| 960 | my ($fh) = @_; | ||
| 961 | return flock($fh, 8) && close($fh); | ||
| 962 | } | ||
| 963 | |||
| 964 | sub do_log { | ||
| 965 | my ($message, $opts) = @_; | ||
| 966 | |||
| 967 | my $module; | ||
| 968 | my $stderr = 0; | ||
| 969 | |||
| 970 | # old style $module population | ||
| 971 | # | ||
| 972 | if (ref($opts) eq 'HASH') { | ||
| 973 | if ($opts->{'module'}) { | ||
| 974 | $module = $opts->{'module'}; | ||
| 975 | } | ||
| 976 | if ($opts->{'stderr'}) { | ||
| 977 | $stderr = $opts->{'stderr'}; | ||
| 978 | } | ||
| 979 | } | ||
| 980 | else { | ||
| 981 | $module = $opts; | ||
| 982 | } | ||
| 983 | |||
| 984 | # current program name (if all previous methods | ||
| 985 | # did not return meaningful module identification) | ||
| 986 | # | ||
| 987 | $module = $0 unless $module; | ||
| 988 | |||
| 989 | # module name formatting | ||
| 990 | # | ||
| 991 | $module = "[" . $module . "] " if $module; | ||
| 992 | |||
| 993 | |||
| 994 | $message = "" unless $message; | ||
| 995 | utf8::encode($message) if utf8::is_utf8($message); | ||
| 996 | $message =~ s/[\r\n]/ /sgo; | ||
| 997 | |||
| 998 | my $message_eol = chop($message); | ||
| 999 | my $message_formatted = | ||
| 1000 | localtime() . " " . $module . | ||
| 1001 | $message . | ||
| 1002 | $message_eol . | ||
| 1003 | ($message_eol eq "\n" ? "" : "\n"); | ||
| 1004 | |||
| 1005 | if ($stderr) { | ||
| 1006 | print STDERR $message_formatted; | ||
| 1007 | } | ||
| 1008 | elsif ($psSnake::debug) { | ||
| 1009 | print $message_formatted; | ||
| 1010 | } | ||
| 1011 | |||
| 1012 | my $log_filename; | ||
| 1013 | my $log_dirname; | ||
| 1014 | |||
| 1015 | if (!defined($psSnake::LOG)) { | ||
| 1016 | print STDERR "psSnake::LOG not configured: $message_formatted\n"; | ||
| 1017 | return; | ||
| 1018 | } | ||
| 1019 | if (ref($psSnake::LOG)) { | ||
| 1020 | $log_filename = $psSnake::LOG->{'filename'}; | ||
| 1021 | if (!$log_filename) { | ||
| 1022 | print STDERR "psSnake::LOG->{'filename'} not configured: $message_formatted\n"; | ||
| 1023 | return; | ||
| 1024 | } | ||
| 1025 | } | ||
| 1026 | else { | ||
| 1027 | $log_filename = $psSnake::LOG; | ||
| 1028 | } | ||
| 1029 | |||
| 1030 | $log_dirname = dirname($log_filename); | ||
| 1031 | if (! -d $log_dirname) { | ||
| 1032 | File::Path::mkpath($log_dirname) || return psSnake::warn("[$log_filename] does not exist and unable to create [$log_dirname]"); | ||
| 1033 | } | ||
| 1034 | |||
| 1035 | if (ref($psSnake::LOG) && $psSnake::LOG->{'rotate_size'}) { | ||
| 1036 | # quick check that we might need to do rotation | ||
| 1037 | my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, | ||
| 1038 | $atime,$mtime,$ctime,$blksize,$blocks) = stat($log_filename); | ||
| 1039 | |||
| 1040 | if ($size && $size > $psSnake::LOG->{'rotate_size'}) { | ||
| 1041 | |||
| 1042 | my $rotated = 0; | ||
| 1043 | |||
| 1044 | # if it seems that rotation is needed -- lock file | ||
| 1045 | # and retry (someone might already done that) | ||
| 1046 | my $rfh = safe_open($log_filename, ""); | ||
| 1047 | psSnake::die ("Unable to open $log_filename; log message: $message_formatted", {'no_log' => 1}) | ||
| 1048 | unless $rfh; | ||
| 1049 | |||
| 1050 | ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, | ||
| 1051 | $atime,$mtime,$ctime,$blksize,$blocks) = stat($log_filename); | ||
| 1052 | if ($size && $size > $psSnake::LOG->{'rotate_size'}) { | ||
| 1053 | link($log_filename, $log_filename . "." . time()) && unlink($log_filename) && ($rotated = 1); | ||
| 1054 | } | ||
| 1055 | else { | ||
| 1056 | # print "already rotated!\n"; | ||
| 1057 | } | ||
| 1058 | safe_close($rfh); | ||
| 1059 | |||
| 1060 | if ($rotated && $psSnake::LOG->{'rotate_keep_copies'}) { | ||
| 1061 | my $dummy; | ||
| 1062 | if (!opendir($dummy, $log_dirname)) { | ||
| 1063 | psSnake::warn("unable to open log directory [$log_dirname] during log rotation"); | ||
| 1064 | } | ||
| 1065 | else { | ||
| 1066 | my @all_entries = readdir($dummy); | ||
| 1067 | close($dummy); | ||
| 1068 | |||
| 1069 | my $log_archive_count = 0; | ||
| 1070 | foreach my $e (sort {$b cmp $a} @all_entries) { | ||
| 1071 | next if "$log_dirname/$e" !~ /$log_filename\.[0-9]+$/; | ||
| 1072 | next if ! -e "$log_dirname/$e"; | ||
| 1073 | |||
| 1074 | $log_archive_count = $log_archive_count + 1; | ||
| 1075 | if ($log_archive_count > $psSnake::LOG->{'rotate_keep_copies'}) { | ||
| 1076 | unlink("$log_dirname/$e") || psSnake::warn("unable to delete expired log archive [$log_dirname/$e]"); | ||
| 1077 | } | ||
| 1078 | } | ||
| 1079 | } | ||
| 1080 | } | ||
| 1081 | } | ||
| 1082 | } | ||
| 1083 | |||
| 1084 | my $fh = safe_open($log_filename, ">>"); | ||
| 1085 | psSnake::die ("Unable to open $log_filename; log message: $message_formatted", {'no_log' => 1}) | ||
| 1086 | unless $fh; | ||
| 1087 | |||
| 1088 | # binmode($fh, ":utf8"); | ||
| 1089 | print $fh $message_formatted; | ||
| 1090 | safe_close($fh); | ||
| 1091 | } | ||
| 1092 | |||
| 1093 | # are we able to write to file | ||
| 1094 | sub can_write { | ||
| 1095 | my ($filename) = @_; | ||
| 1096 | |||
| 1097 | if (! -d dirname($filename)) { | ||
| 1098 | if (!File::Path::mkpath(dirname($filename))) { | ||
| 1099 | return 0; | ||
| 1100 | } | ||
| 1101 | } | ||
| 1102 | |||
| 1103 | if (-e $filename) { | ||
| 1104 | if (-w $filename) { | ||
| 1105 | return 1; | ||
| 1106 | } | ||
| 1107 | else { | ||
| 1108 | return 0; | ||
| 1109 | } | ||
| 1110 | } | ||
| 1111 | else { | ||
| 1112 | my $fh = safe_open($filename, ">", {"timeout" => 0, "silent" => 1}); | ||
| 1113 | if ($fh) { | ||
| 1114 | safe_close($fh); | ||
| 1115 | return 1; | ||
| 1116 | } | ||
| 1117 | else { | ||
| 1118 | return 0; | ||
| 1119 | } | ||
| 1120 | } | ||
| 1121 | } | ||
| 1122 | |||
| 1123 | # are we able to log | ||
| 1124 | sub can_log { | ||
| 1125 | if (defined($psSnake::LOG)) { | ||
| 1126 | my $log_filename; | ||
| 1127 | if (ref($psSnake::LOG)) { | ||
| 1128 | $log_filename = $psSnake::LOG->{'filename'}; | ||
| 1129 | if (!$log_filename) { | ||
| 1130 | $psSnake::LOG = undef; | ||
| 1131 | return 0; | ||
| 1132 | } | ||
| 1133 | } | ||
| 1134 | else { | ||
| 1135 | $log_filename = $psSnake::LOG; | ||
| 1136 | } | ||
| 1137 | |||
| 1138 | if (!can_write($log_filename)) { | ||
| 1139 | $psSnake::LOG = undef; | ||
| 1140 | return 0; | ||
| 1141 | } | ||
| 1142 | } | ||
| 1143 | |||
| 1144 | return 1; | ||
| 1145 | } | ||
| 1146 | |||
| 1147 | sub add_hook { | ||
| 1148 | my ($opts) = @_; | ||
| 1149 | |||
| 1150 | psSnake::die("add_hook: invalid input") | ||
| 1151 | unless $opts->{'type'} && | ||
| 1152 | ref($opts->{'func'}) eq 'CODE' && | ||
| 1153 | ref($opts->{'args'}) eq 'ARRAY'; | ||
| 1154 | |||
| 1155 | push @{$psSnake::HOOKS->{$opts->{'type'}}}, { | ||
| 1156 | 'func' => $opts->{'func'}, | ||
| 1157 | 'args' => $opts->{'args'}, | ||
| 1158 | }; | ||
| 1159 | } | ||
| 1160 | |||
| 1161 | sub run_hook { | ||
| 1162 | my ($type) = @_; | ||
| 1163 | |||
| 1164 | if (scalar(@{$psSnake::HOOKS->{$type}}) gt 0) { | ||
| 1165 | my $h = pop(@{$psSnake::HOOKS->{$type}}); | ||
| 1166 | $h->{'func'}->(@{$h->{'args'}}); | ||
| 1167 | } | ||
| 1168 | } | ||
| 1169 | |||
| 1170 | sub run_hooks { | ||
| 1171 | my ($type) = @_; | ||
| 1172 | |||
| 1173 | while (scalar(@{$psSnake::HOOKS->{$type}}) gt 0) { | ||
| 1174 | psSnake::run_hook($type); | ||
| 1175 | } | ||
| 1176 | } | ||
| 1177 | |||
| 1178 | sub warn { | ||
| 1179 | my ($text) = @_; | ||
| 1180 | print STDERR "WARNING: $text\n"; | ||
| 1181 | psSnake::do_log("[WARN] " . $text); | ||
| 1182 | } | ||
| 1183 | |||
| 1184 | sub die { | ||
| 1185 | my ($message, $opts) = @_; | ||
| 1186 | |||
| 1187 | $opts = {} unless $opts; | ||
| 1188 | |||
| 1189 | # backward compatibility (second parameter used to be scalar) | ||
| 1190 | if (!ref($opts)) { | ||
| 1191 | $opts->{'show_callstack'} = 1; | ||
| 1192 | } | ||
| 1193 | |||
| 1194 | if ($psSnake::HOOKS->{'before_die'} && scalar(@{$psSnake::HOOKS->{'before_die'}})) { | ||
| 1195 | psSnake::run_hooks("before_die"); | ||
| 1196 | } | ||
| 1197 | |||
| 1198 | print STDERR ($message ? $message : ""); | ||
| 1199 | |||
| 1200 | if ($opts->{'show_callstack'}) { | ||
| 1201 | print STDERR get_callstack(); | ||
| 1202 | } | ||
| 1203 | else { | ||
| 1204 | print "\n"; | ||
| 1205 | } | ||
| 1206 | |||
| 1207 | if (!$opts->{'no_log'}) { | ||
| 1208 | psSnake::do_log("[ERR] " . $message); | ||
| 1209 | } | ||
| 1210 | else { | ||
| 1211 | # try logger here? | ||
| 1212 | } | ||
| 1213 | |||
| 1214 | exit 1; | ||
| 1215 | } | ||
| 1216 | |||
| 1217 | sub get_callstack { | ||
| 1218 | my $cstack; | ||
| 1219 | my $i = 0; | ||
| 1220 | while ( 1 ) { | ||
| 1221 | my $tfunc = (caller($i))[3]; | ||
| 1222 | if ($tfunc && $tfunc ne "") { | ||
| 1223 | if ($tfunc !~ /\_\_ANON\_\_/ && | ||
| 1224 | $tfunc !~ /.*::get_callstack/) { | ||
| 1225 | $cstack .= "\t" . $tfunc . "\n"; | ||
| 1226 | } | ||
| 1227 | $i = $i + 1; | ||
| 1228 | } | ||
| 1229 | else { | ||
| 1230 | last; | ||
| 1231 | } | ||
| 1232 | } | ||
| 1233 | return "\nCallstack:\n" . $cstack . "\n"; | ||
| 1234 | } | ||
| 1235 | |||
| 1236 | sub read_cmdline { | ||
| 1237 | my $i = 0; | ||
| 1238 | |||
| 1239 | my $v; | ||
| 1240 | my $first_parameter; | ||
| 1241 | while ($ARGV[$i]) { | ||
| 1242 | if ($ARGV[$i] =~ /--(.+)\b/) { | ||
| 1243 | $v = $1; | ||
| 1244 | if ($v eq "debug") { | ||
| 1245 | $debug = 1; | ||
| 1246 | } | ||
| 1247 | elsif ($v eq "debug2") { | ||
| 1248 | $debug = 1; | ||
| 1249 | $debug2 = 1; | ||
| 1250 | } | ||
| 1251 | else { | ||
| 1252 | $command = $v unless $command; | ||
| 1253 | |||
| 1254 | $cmd_opts->{$v} = ""; | ||
| 1255 | $first_parameter = 1; | ||
| 1256 | } | ||
| 1257 | } | ||
| 1258 | else { | ||
| 1259 | if ($v) { | ||
| 1260 | if ($first_parameter) { | ||
| 1261 | $cmd_opts->{$v} = ""; | ||
| 1262 | $first_parameter = 0; | ||
| 1263 | } | ||
| 1264 | |||
| 1265 | $cmd_opts->{$v} .= ($cmd_opts->{$v} ? " " : "") . $ARGV[$i]; | ||
| 1266 | } | ||
| 1267 | else { | ||
| 1268 | $cmd_opts->{$ARGV[$i]} = 1; | ||
| 1269 | } | ||
| 1270 | } | ||
| 1271 | $i++; | ||
| 1272 | } | ||
| 1273 | } | ||
| 1274 | |||
| 1275 | sub canonize_delimiters { | ||
| 1276 | my ($str, $except) = @_; | ||
| 1277 | |||
| 1278 | my $delimiters = "ts,;&"; | ||
| 1279 | |||
| 1280 | my $delimiters_prepared; | ||
| 1281 | foreach my $d (split(//, $delimiters)) { | ||
| 1282 | next if $except && $except =~ /$d/; | ||
| 1283 | $delimiters_prepared = $delimiters_prepared . "\\$d" | ||
| 1284 | } | ||
| 1285 | |||
| 1286 | my $delim_re = qr/[$delimiters_prepared]+/; | ||
| 1287 | $$str =~ s/$delim_re/\ /g; | ||
| 1288 | } | ||
| 1289 | |||
| 1290 | # - removes duplicates from array | ||
| 1291 | # - leaves first occurence of each duplicate | ||
| 1292 | # - preserves order | ||
| 1293 | # - valid only for arrays of scalars and arrayrefs | ||
| 1294 | # | ||
| 1295 | sub array_clear_dupes { | ||
| 1296 | my @array_in = @_; | ||
| 1297 | |||
| 1298 | my @array_to_process; | ||
| 1299 | foreach my $e (@array_in) { | ||
| 1300 | if (ref($e) eq 'ARRAY') { | ||
| 1301 | push (@array_to_process, @{$e}); | ||
| 1302 | } | ||
| 1303 | else { | ||
| 1304 | push (@array_to_process, $e); | ||
| 1305 | } | ||
| 1306 | } | ||
| 1307 | |||
| 1308 | my @array_out; | ||
| 1309 | my $c = {}; | ||
| 1310 | foreach my $e (@array_to_process) { | ||
| 1311 | unless ($c->{$e}) { | ||
| 1312 | $c->{$e} = 1; | ||
| 1313 | push (@array_out, $e); | ||
| 1314 | } | ||
| 1315 | } | ||
| 1316 | |||
| 1317 | return @array_out; | ||
| 1318 | } | ||
| 1319 | |||
| 1320 | # <LJFUNC> | ||
| 1321 | # name: LJ::is_ascii | ||
| 1322 | # des: checks if text is pure ASCII. | ||
| 1323 | # args: text | ||
| 1324 | # des-text: text to check for being pure 7-bit ASCII text. | ||
| 1325 | # returns: 1 if text is indeed pure 7-bit, 0 otherwise. | ||
| 1326 | # </LJFUNC> | ||
| 1327 | sub is_ascii { | ||
| 1328 | my $text = shift; | ||
| 1329 | return ($text !~ m/[^\x01-\x7f]/o); | ||
| 1330 | } | ||
| 1331 | |||
| 1332 | sub is_digital { | ||
| 1333 | my $text = shift; | ||
| 1334 | return ( $text =~ /^\d+$/o ); | ||
| 1335 | } | ||
| 1336 | |||
| 1337 | sub QP { | ||
| 1338 | my ($text, $encoding) = @_; | ||
| 1339 | |||
| 1340 | $text = "" unless $text; | ||
| 1341 | |||
| 1342 | $encoding = "UTF-8" unless $encoding; | ||
| 1343 | |||
| 1344 | my $encoded_text = $text; | ||
| 1345 | |||
| 1346 | if ($encoding eq "UTF-8") { | ||
| 1347 | $encoded_text = encode("utf8", $encoded_text); | ||
| 1348 | } | ||
| 1349 | |||
| 1350 | $encoded_text = encode_base64($encoded_text, ""); | ||
| 1351 | $encoded_text = "=?${encoding}?B?$encoded_text?="; | ||
| 1352 | |||
| 1353 | # $encoded_text = encode_qp($text); | ||
| 1354 | # $encoded_text = "=?${encoding}?Q?$encoded_text?="; | ||
| 1355 | |||
| 1356 | return $encoded_text; | ||
| 1357 | } | ||
| 1358 | |||
| 1359 | # should be used when you need to concatenate string | ||
| 1360 | # which might be undefined and you want empty string ("") | ||
| 1361 | # instead of perl warnings about uninitialized values | ||
| 1362 | # | ||
| 1363 | sub safe_string { | ||
| 1364 | my ($str) = @_; | ||
| 1365 | |||
| 1366 | if (defined($str)) { | ||
| 1367 | return $str; | ||
| 1368 | } | ||
| 1369 | else { | ||
| 1370 | return ""; | ||
| 1371 | } | ||
| 1372 | } | ||
| 1373 | |||
| 1374 | # | ||
| 1375 | # generic mail sending function | ||
| 1376 | # | ||
| 1377 | # expects one input parameter, hashref, with following keys: | ||
| 1378 | # | ||
| 1379 | # to [mandatory] -- comma-separated list or arrayref of recipients | ||
| 1380 | # from [optional] -- string | ||
| 1381 | # cc [optional] -- comma-separated list or arrayref | ||
| 1382 | # bcc [optional] -- comma-separated list or arrayref | ||
| 1383 | # subject [optional] -- string | ||
| 1384 | # data [optional] -- string, message body | ||
| 1385 | # charset [optional] -- string, utf-8 by default | ||
| 1386 | # attach [optional] -- scalar (might be binary) | ||
| 1387 | # attach_name [optional] -- string, attachment name | ||
| 1388 | # headers [optional] -- hashref { header_name => header_value } | ||
| 1389 | # | ||
| 1390 | sub send_mail { | ||
| 1391 | my ($opts) = @_; | ||
| 1392 | |||
| 1393 | psSnake::die("Programmer error: send_mail expects hashref with at least 'to' set") | ||
| 1394 | unless $opts && $opts->{'to'}; | ||
| 1395 | |||
| 1396 | foreach my $att (qw /subject body cc bcc/) { | ||
| 1397 | $opts->{$att} = "" unless defined($opts->{$att}); | ||
| 1398 | } | ||
| 1399 | $opts->{'charset'} = "utf-8" unless $opts->{'charset'}; | ||
| 1400 | |||
| 1401 | my $process_emails_to_array = sub { | ||
| 1402 | my ($a) = @_; | ||
| 1403 | |||
| 1404 | my @b; | ||
| 1405 | if (ref($a) eq 'ARRAY') { | ||
| 1406 | @b = @{$a}; | ||
| 1407 | } | ||
| 1408 | else { | ||
| 1409 | psSnake::canonize_delimiters(\$a); | ||
| 1410 | @b = split(/\ /, $a); | ||
| 1411 | } | ||
| 1412 | |||
| 1413 | return \@b; | ||
| 1414 | }; | ||
| 1415 | |||
| 1416 | my $process_emails_to_string = sub { | ||
| 1417 | my ($a) = @_; | ||
| 1418 | |||
| 1419 | if (ref($a) eq 'ARRAY') { | ||
| 1420 | return join(",", @{$a}); | ||
| 1421 | } | ||
| 1422 | else { | ||
| 1423 | return $a; | ||
| 1424 | } | ||
| 1425 | }; | ||
| 1426 | |||
| 1427 | foreach my $f (qw/to cc bcc/) { | ||
| 1428 | $opts->{$f} = $process_emails_to_array->($opts->{$f}); | ||
| 1429 | } | ||
| 1430 | |||
| 1431 | push (@{$opts->{'cc'}}, $psSnake::CC_ALL) if $psSnake::CC_ALL && !$opts->{'no_cc_all'}; | ||
| 1432 | push (@{$opts->{'bcc'}}, $psSnake::BCC_ALL) if $psSnake::BCC_ALL && !$opts->{'no_bcc_all'}; | ||
| 1433 | |||
| 1434 | foreach my $f (qw/to cc bcc/) { | ||
| 1435 | my @a = psSnake::array_clear_dupes($opts->{$f}); | ||
| 1436 | $opts->{$f} = $process_emails_to_string->(\@a); | ||
| 1437 | } | ||
| 1438 | |||
| 1439 | $opts->{'from'} = $psSnake::MAIL_FROM | ||
| 1440 | unless $opts->{'from'}; | ||
| 1441 | |||
| 1442 | my @log_to; | ||
| 1443 | my $clean_emails = sub { | ||
| 1444 | my ($in) = @_; | ||
| 1445 | my @out; | ||
| 1446 | |||
| 1447 | foreach my $e (split /,/, $in) { | ||
| 1448 | $e =~ s/^.*<//o; | ||
| 1449 | $e =~ s/>.*$//o; | ||
| 1450 | push(@out, $e); | ||
| 1451 | } | ||
| 1452 | |||
| 1453 | return join(",", @out); | ||
| 1454 | }; | ||
| 1455 | foreach my $f (qw/from to cc bcc/) { | ||
| 1456 | push @log_to, "$f: " . $clean_emails->($opts->{$f}) if $opts->{$f}; | ||
| 1457 | } | ||
| 1458 | |||
| 1459 | if ($have_mime_lite) { | ||
| 1460 | my $msg = new MIME::Lite ( | ||
| 1461 | 'From' => $opts->{'from'}, | ||
| 1462 | 'To' => $opts->{'to'}, | ||
| 1463 | 'Cc' => $opts->{'cc'}, | ||
| 1464 | 'Bcc' => $opts->{'bcc'}, | ||
| 1465 | 'Subject' => QP($opts->{'subject'}, $opts->{'charset'}), | ||
| 1466 | 'Data' => $opts->{'body'}, | ||
| 1467 | ); | ||
| 1468 | |||
| 1469 | # $opts->{'headers'}->{'Reply-To'} = $Golem::SUPPORT_EMAIL | ||
| 1470 | # if $Golem::SUPPORT_EMAIL; | ||
| 1471 | |||
| 1472 | $msg->attr("content-type.charset" => $opts->{'charset'}) | ||
| 1473 | if $opts->{'charset'} && | ||
| 1474 | ! (psSnake::is_ascii($opts->{'body'}) && | ||
| 1475 | psSnake::is_ascii($opts->{'subject'})); | ||
| 1476 | |||
| 1477 | if ($opts->{'attach'}) { | ||
| 1478 | my $mm = new File::MMagic; | ||
| 1479 | my $attach_type = $mm->checktype_contents($opts->{'attach'}); | ||
| 1480 | |||
| 1481 | my $part = MIME::Lite->new( | ||
| 1482 | Type => $attach_type, | ||
| 1483 | Data => $opts->{'attach'}, | ||
| 1484 | Filename => $opts->{'attach_name'} ? $opts->{'attach_name'} : undef, | ||
| 1485 | ); | ||
| 1486 | $msg->attach($part); | ||
| 1487 | } | ||
| 1488 | |||
| 1489 | if ($opts->{'headers'}) { | ||
| 1490 | while (my ($k, $v) = each %{$opts->{'headers'}}) { | ||
| 1491 | $msg->add($k => $v); | ||
| 1492 | } | ||
| 1493 | } | ||
| 1494 | |||
| 1495 | unless ($msg->send()) { | ||
| 1496 | psSnake::do_log("Unable to send mail through MIME::Lite; recipients: [" . join (" ", @log_to) . "]", {"stderr" => 1}); | ||
| 1497 | return 0; | ||
| 1498 | } | ||
| 1499 | } | ||
| 1500 | else { | ||
| 1501 | my $to_scalar; | ||
| 1502 | my $subj = $opts->{'subject'} || ""; | ||
| 1503 | |||
| 1504 | $subj =~ s/"/\\"/go; | ||
| 1505 | |||
| 1506 | foreach my $f (qw/to cc/) { | ||
| 1507 | if ($opts->{$f}) { | ||
| 1508 | $to_scalar = ($to_scalar ? $to_scalar . "," : "") . $clean_emails->($opts->{$f}); | ||
| 1509 | } | ||
| 1510 | } | ||
| 1511 | |||
| 1512 | my $r = psSnake::run_forked("mail -s \"$subj\" $to_scalar", {'child_stdin' => $opts->{'body'}}); | ||
| 1513 | if ($r->{'exit_code'} ne 0) { | ||
| 1514 | psSnake::do_log("Unable to send mail through system mailer, exit_code [$r->{'exit_code'}], stderr [$r->{'stderr'}], " . | ||
| 1515 | "to [$to_scalar], message [" . substr($opts->{'body'}, 0, 200) . "] ", {"stderr" => 1}); | ||
| 1516 | return 0; | ||
| 1517 | } | ||
| 1518 | } | ||
| 1519 | |||
| 1520 | psSnake::do_log("sent mail " . join (" ", @log_to)); | ||
| 1521 | |||
| 1522 | return 1; | ||
| 1523 | } | ||
| 1524 | |||
| 1525 | |||
| 1526 | 1; |