Simple.pm untested

filter: Statementstmt 0.0% 0 / 399 Branchbran 0.0% 0 / 236 Conditioncond 0.0% 0 / 39 MC/DCmcdc 0.0% 0 / 25 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 728 CC 117 SCAR 88.6
CC
117
Cov
0%
import
9900.0
SaveParam
56.0
StopStartService
42.0
CRAP 7057.6
1 package Win32::Daemon::Simple;
2 use POSIX qw(strftime);
3 use Win32;
4 use Hash::Case::Preserve;
5 use Win32::Console qw();
6 use Win32::Daemon;
7 use FindBin qw($Bin $Script);$Bin =~ s{/}{\\}g;
8 use File::Spec;
9 use FileHandle;
10 use Carp;
11 use Exporter;
12 use strict;
13 use vars qw(@ISA @EXPORT $VERSION);
14 @ISA = qw(Exporter);
15 @EXPORT = qw(ReadParam SaveParam Log LogNT OpenLog CloseLog CatchMessages GetMessages ServiceLoop DoEvents CMDLINE SERVICEID SERVICENAME);
16 $VERSION = '0.2.6';
17  
18 sub Now () {
19 strftime( "%Y/%m/%d %H:%M:%S", localtime())
20 }
21  
22 my $compiled = !(-e $INC{'Win32/Daemon/Simple.pm'}); # if the module was not read from disk => the script has been "compiled"
23 if (0) {
24 require 'Win32/Service.pm';
25 }
26  
27 my ($svcid, $origsvcid, $svcname, $svcversion) = ( $Script, $Script);
28 BEGIN {
29 eval {
30 my $title;
31 if ($^C != 1 and $title = Win32::Console::_GetConsoleTitle()) {
32 eval 'sub CMDLINE () {1}';
33 $|=1;
34 if (lc($title) eq lc($^X) or lc($title) eq lc($0)) {
35 eval 'sub FROMCMDLINE () {0}';
36 eval '*MsgBox = \&Win32::MsgBox;';
37 if (! @ARGV) {
38 push @ARGV, '-help_and_settings';
39 }
40 } else {
41 eval 'sub FROMCMDLINE () {1}';
42 eval 'sub MsgBox {}';
43 }
44 } else {
45 eval 'sub CMDLINE () {0}';
46 eval 'sub FROMCMDLINE () {0}';
47 eval 'sub MsgBox {}';
48 }
49 };
50 }
51  
52 my ($info, $params, $param_modify, $run_params);
53  
54 # parameters
55 use Win32::Registry;
56  
57 if ($Win32::Registry::VERSION < 0.08 and !defined($Win32::Registry2::VERSION)) {
58 die "Please update your Win32::Registry to 0.08 or newer or install the patch from http://jenda.krynicky.cz/#Win32::Registry2\n\n";
59 }
60  
61 my $ServiceKey;
62 {
63 my $paramkey;
64 sub ReadParam {
65 my ( $param, $default) = @_;
66 $ServiceKey = $HKLM->Open('SYSTEM\CurrentControlSet\Services\\'.$svcid)
67 unless $ServiceKey;
68 return $default unless $ServiceKey;
69 $paramkey = $ServiceKey->Create('Parameters')
70 unless $paramkey;
71 my $value = $paramkey->GetValue($param);
72 $value = $default unless defined $value;
73 return $value;
74 }
75  
76 sub SaveParam {
77 my ( $param, $value) = @_;
78 $ServiceKey = $HKLM->Open('SYSTEM\CurrentControlSet\Services\\'.$svcid)
79 unless $ServiceKey;
80 return unless $ServiceKey; # do not save anything if the service is not installed
81 $paramkey = $ServiceKey->Create('Parameters')
82 unless $paramkey;
83 die "Can't open/create the Parameters subkey in the service settings!\n" unless $paramkey; # do not save anything if the service is not installed
84 if (!defined $value) {
85 $paramkey->DeleteValue($param);
86 } elsif ($value =~ /^\d+$/) {
87 $paramkey->SetValues($param, REG_DWORD, $value);
88 } else{
89 $value =~ s/\r?\n/\r\n/g;
90 $paramkey->SetValues($param, REG_SZ, $value);
91 }
92 }
93 }
94  
95 sub StopStartService {
96 $|=1;
97 my $cmd = shift;
98 eval "use Win32::Service";
99 my %status;
100 Win32::Service::GetStatus(undef, $svcid, \%status);
101 if (! %status) {
102 print "\t\tThe service $svcid doesn't exist!\n";
103 next;
104 };
105 my ($good_status,$msg);
106 if ($cmd eq 'stop') {
107 $good_status = 1;
108 if( $status{CurrentState} == $good_status) {
109 print "\n The service did not run.\n";
110 MsgBox "The service did not run.\n", MB_ICONINFORMATION, $svcname;
111 return;
112 }
113 $msg = "stopped";
114 Win32::Service::StopService(undef, $svcid);sleep(1);
115 } else {
116 $good_status = 4;
117 if( $status{CurrentState} == $good_status) {
118 print "\n The service was running already.\n";
119 MsgBox "The service was running already.\n", MB_ICONINFORMATION, $svcname;
120 return;
121 }
122 $msg = "started";
123 Win32::Service::StartService(undef, $svcid);sleep(1);
124 }
125  
126 my $count=0;
127 while (++$count < 120 and $status{CurrentState} != $good_status) {
128 sleep(1);
129 print '.';
130 Win32::Service::GetStatus(undef, $svcid, \%status);
131 }
132  
133 if( $status{CurrentState} == $good_status) {
134 print " The service was $msg.\n";
135 MsgBox "The service was $msg.\n", MB_ICONINFORMATION, $svcname;
136 } else {
137 print " The service could not be $msg.\n";
138 MsgBox "The service could not be $msg.\n", MB_ICONERROR, $svcname;
139 }
140 }
141  
142 my ($logging_code,$loop_code);
143 # main processing
144 sub import {
145  
146 #$::dbg->trace('main::','Win32::Daemon::Simple::');
147  
148 shift();
149 my $caller_pack = caller;
150 eval {
151 my ($key, $val);
152 while (defined ($key = shift()) and defined ($val = shift())) {
153 $key = lc $key;
154 if ($key eq 'service') {
155 $svcid = $val;
156 $origsvcid = $val;
157 } elsif ($key eq 'name') {
158 $svcname = $val;
159 } elsif ($key eq 'version') {
160 $svcversion = $val;
161 } elsif ($key eq 'info') {
162 $info = $val;
163 } elsif ($key eq 'logging_code') {
164 $logging_code = $val;
165 } elsif ($key eq 'params') {
166 my %params;
167 tie %params, 'Hash::Case::Preserve', $val;
168 $params = \%params;
169 } elsif ($key eq 'run_params') {
170 $run_params = $val;
171 } elsif ($key eq 'param_modify') {
172 $param_modify = {};
173 foreach my $param (keys %$val) { # hashes are case sensitive, the param should be INsensitive!
174 $param_modify->{lc $param} = $val->{$param};
175 }
176 } else {
177 croak "Unknown option '$key' passed to use Win32::Daemon::Simple!";
178 }
179 }
180 if (! ref $info) {
181 croak "Required parameter 'info' not specified";
182 };
183  
184 if (! ref $params) { $params = {} };
185 if (! ref $run_params) { $run_params = {} };
186 if (! ref $param_modify) { $param_modify = {} };
187 unless (defined $params->{'LogFile'}) {
188 my $logfile = $Bin . '\\' . $Script;
189 $logfile =~ s/\.[^\.]+$/.log/ or $logfile .= '.log';
190 $logfile =~ s{/}{\\}g;
191 $params->{'LogFile'} = $logfile;
192 } elsif ($params->{'LogFile'} !~ m{^\w:[\\/]}) {
193 $params->{'LogFile'} = $Bin . '\\' . $params->{'LogFile'};
194 }
195 $params->{'Interval'} = 1 unless (defined $params->{'Interval'});
196  
197 if (CMDLINE) {
198 Win32::Console::_SetConsoleTitle( "$svcname $svcversion (in commandline mode)");
199 }
200  
201 my $run_with_params = 0;
202 if ($^C != 1 and @ARGV) { # we've got some params !
203 $run_with_params = 1 if (grep {$_ eq '--'} @ARGV);
204 print "$svcname $svcversion\n" unless $run_with_params;
205 my $inst = 0;
206 my $re = join '|', map {quotemeta $_} (keys %$params);
207 my $nore = qr{^[-/]no($re)$}i;
208 my $defre = qr{^[-/]DEFAULT($re)$}i;
209 $re = qr{^[-/]($re)(?:=(.*))?$}si;
210  
211 while (my $opt = shift(@ARGV)){
212 if ($opt =~ m{^[-/]install$}i) {
213 $info->{'name'} = $svcid;
214 $info->{'display'} = $svcname unless defined $info->{'display'};
215 if (! exists $info->{'path'}) {
216 if ($compiled or $0 =~ /\.exe$/i) {
217 $info->{'path'} = "$Bin\\$Script";
218 } else {
219 $info->{'path'} = $^X;
220 if (defined $info->{'parameters'}) {
221 $info->{'parameters'} .= ' --' unless $info->{'parameters'} =~ /--$/;
222 $info->{'parameters'} = "$Bin\\$Script $info->{'parameters'}";
223 } else {
224 $info->{'parameters'} = "$Bin\\$Script";
225 }
226 }
227 }
228 Win32::Daemon::DeleteService($svcid);
229 sleep(2);
230 {
231 my $logdir = $params->{'LogFile'};
232 $logdir =~ s{[\\/][^\\/]+$}{};
233 mkdir $logdir unless -d $logdir;
234 }
235 if( Win32::Daemon::CreateService( $info ) ) {
236 foreach my $param (keys %$params) {
237 SaveParam( $param, $params->{$param});
238 }
239 print " Installed successfully\n $info->{'path'} $info->{'parameters'}\n";
240 MsgBox "Installed successfully\n $info->{'path'} $info->{'parameters'}\n", MB_ICONINFORMATION, $svcname;
241 } else {
242 print " Failed to install: " . Win32::FormatMessage( Win32::Daemon::GetLastError() ) . "\n";
243 MsgBox "Failed to install: " . Win32::FormatMessage( Win32::Daemon::GetLastError() ) . "\n", MB_ICONERROR, $svcname;
244 }
245 $inst = 1;
246 } elsif ($opt =~ m{^[-/]uninstall$}i) {
247 if( Win32::Daemon::DeleteService($svcid) ) {
248 print " Uninstalled successfully\n";
249 MsgBox "Uninstalled successfully\n", MB_ICONINFORMATION, $svcname;
250 } else {
251 print " Failed to uninstall: " . Win32::FormatMessage( Win32::Daemon::GetLastError() ) . "\n";
252 MsgBox "Failed to uninstall: " . Win32::FormatMessage( Win32::Daemon::GetLastError() ) . "\n", MB_ICONERROR, $svcname;
253 }
254 $inst = 1;
255  
256 # service settings
257 } elsif ($opt =~ m{^[-/]service=(.*)$}i) {
258 $svcid = $1;
259 $info->{'name'} = $svcid;
260 if ($info->{'parameters'}) {
261 $info->{'parameters'} =~ s{[/-]service=\S+}{};
262 $info->{'parameters'} = "/service=$svcid $info->{'parameters'}";
263 } else {
264 $info->{'parameters'} = "/service=$svcid --";
265 }
266 } elsif ($opt =~ m{^[-/]service:name=(.*)$}i) {
267 $svcname = $1;
268 $info->{'display'} = $svcname;
269 if ($info->{'parameters'}) {
270 # $info->{'parameters'} =~ s{[/-]service:name=\S+}{}; # what to do with quotes?
271 $info->{'parameters'} = qq{"/service:name=$svcname" $info->{'parameters'}};
272 } else {
273 $info->{'parameters'} = qq{"/service:name=$svcname" --};
274 }
275 if (!$run_with_params) {
276 $ServiceKey = $HKLM->Open('SYSTEM\CurrentControlSet\Services\\'.$svcid)
277 unless $ServiceKey;
278 $ServiceKey->SetValues('DisplayName', REG_SZ, $svcname)
279 if $ServiceKey;
280 }
281 } elsif ($opt =~ m{^[-/]service:user=(.*)$}i) {
282 $info->{'user'} = $1;
283 } elsif ($opt =~ m{^[-/]service:pwd=(.*)$}i) {
284 $info->{'pwd'} = $1;
285 } elsif ($opt =~ m{^[-/]service:interactive=(.*)$}i) {
286 $info->{'interactive'} = (($1 && lc($1) ne 'no') ? 1 : 0);
287  
288 } elsif ($opt =~ m{^[-/]start$}i) {
289 StopStartService('start');
290 $inst = 1;
291 } elsif ($opt =~ m{^[-/]stop$}i) {
292 StopStartService('stop');
293 $inst = 1;
294 } elsif ($opt =~ m{^[-/](?:help(?:_and_settings)?|\?)$}i) {
295 my $dsc = $params->{'Description'};
296 $dsc =~ s/\n/\n /g;
297 print <<"*END*";
298  
299 $Script -install
300 : installs the service
301  
302 $Script -uninstall
303 : uninstalls the service
304  
305 $Script -start
306 : starts the service
307  
308 $Script -stop
309 : stops the service
310  
311 $Script -params
312 : displays the effective settings
313  
314 $Script -PARAM
315 : changes the value of the option to 1
316  
317 $Script -noPARAM
318 : changes the value of the option to 0
319  
320 $Script -PARAM=VALUE
321 : changes the value of an option (you may specify several params at once)
322  
323 The available options:
324 $dsc
325  
326 *END*
327 if (! FROMCMDLINE) {
328 if ($opt =~ m{^[-/]help_and_settings$}i) {
329 print <<'*END*';
330 Type "continue" and press ENTER to start processing files in commandline mode,
331 type "install" and press ENTER to install the service,
332 type "uninstall" and press ENTER to uninstall the service,
333 type "start" and press ENTER to start the service,
334 type "stop" and press ENTER to stop the service,
335 type "ParameterName=Value" and press ENTER to change a service parameter
336 or press ENTER to exit
337 *END*
338 while (my $line = <STDIN>) {
339 chomp($line);
340 last if $line eq '';
341 my ($param, $value) = split /=/, $line, 2;
342 $param = lc $param;
343 if ($param eq 'install') {
344 push @ARGV, '-install';
345 last;
346 } elsif ($param eq 'uninstall') {
347 push @ARGV, '-uninstall';
348 last;
349 } elsif ($param eq 'start') {
350 push @ARGV, '-start';
351 last;
352 } elsif ($param eq 'stop') {
353 push @ARGV, '-stop';
354 last;
355 } elsif ($param eq 'continue') {
356 $run_with_params = 1;
357 last;
358 } elsif (exists $params->{$param}) {
359 $value = 1 unless defined $value;
360 } elsif (substr($param,0,2) eq 'no' and exists $params->{substr($param,2)}) {
361 $param = substr($param,2);
362 $value = 0 unless defined $value;
363 } else {
364 print "Unknown parameter '$param'!\n";
365 next;
366 }
367 if (exists $param_modify->{$param}) {
368 eval {
369 $value = $param_modify->{$param}->($value);
370 SaveParam( $param, $value);
371 $run_params->{$param} = $value;
372 print " $param: $value\n";
373 };
374 if ($@) {
375 print " $param: $run_params->{$param}\n\t$@\n";
376 }
377 } else {
378 SaveParam( $param, $value);
379 $run_params->{$param} = $value;
380 print " $param: $value\n";
381 }
382 }
383 } else {
384 print "(Press ENTER to exit)\n";
385 <STDIN>;
386 }
387 }
388 # exit();
389 } elsif ($opt =~ m{^[-/]params}i) {
390 foreach my $param (keys %$params) {
391 next if lc($param) eq 'description';
392 $val = ReadParam( $param, $params->{$param});
393 if ($val =~ s/\n/\n /g) {
394 print " $param:\n $val\n";
395 } else {
396 print " $param: $val\n";
397 }
398 }
399 print( $origsvcid ne $svcid ? "NOT INSTALLED as $svcid!\n" : "NOT INSTALLED!\n") unless $ServiceKey;
400 if (! FROMCMDLINE) {
401 print "(press ENTER to exit)\n";
402 <STDIN>;
403 }
404 exit();
405 } elsif ($opt =~ $re) {
406 my ( $opt, $val) = ( lc($1), $2);
407 $val = 1 unless defined $val;
408 if (exists $param_modify->{$opt}) {
409 eval {
410 $val = $param_modify->{$opt}->($val);
411 $run_params->{$opt} = $val;
412 unless ($run_with_params) {
413 print " $opt: $val\n";
414 SaveParam( $opt, $val);
415 }
416 };
417 if ($@) {
418 print " $opt: ".ReadParam( $opt, $params->{$opt})."\n\t$@\n";
419 }
420 } else {
421 $run_params->{$opt} = $val;
422 unless ($run_with_params) {
423 print " $opt: $val\n";
424 SaveParam( $opt, $val);
425 }
426 }
427 } elsif ($opt =~ $nore) {
428 my ( $opt) = lc($1);
429 my $val = 0;
430 if (exists $param_modify->{lc $opt}) {
431 eval {
432 $val = $param_modify->{lc $opt}->($val);
433 $run_params->{$opt} = $val;
434 unless ($run_with_params) {
435 print " $opt: $val\n";
436 SaveParam( $opt, $val);
437 }
438 };
439 if ($@) {
440 print " $opt: $@\n";
441 }
442 } else {
443 $run_params->{$opt} = $val;
444 unless ($run_with_params) {
445 print " $opt: $val\n";
446 SaveParam( $opt, $val);
447 }
448 }
449 } elsif ($opt =~ $defre) {
450 my ( $opt) = lc($1);
451 my $val = $params->{$opt};
452 $run_params->{$opt} = $val;
453 unless ($run_with_params) {
454 print " $opt: -DEFAULT-VALUE-\n";
455 SaveParam( $opt, $val);
456 }
457 } elsif ($opt =~ m{^[-/]default$}i) {
458 if ($run_with_params) {
459 foreach my $param (keys %$params) {
460 $run_params->{lc $param} = $params->{$param};
461 }
462 } else {
463 foreach my $param (keys %$params) {
464 SaveParam( $param, $params->{$param});
465 next if lc($param) eq 'description';
466 my $val = $params->{$param};
467 if ($val =~ s/\n/\n /g) {
468 print " $param:\n $val\n";
469 } else {
470 print " $param: $val\n";
471 }
472 }
473 }
474 } elsif ($opt eq '--') {
475 die "\$run_with_params was not set !!!" unless $run_with_params; # this should already be set!
476 last;
477 } else {
478 MsgBox "Unknown option '$opt'", MB_ICONEXCLAMATION, $svcname;
479 $inst = 1;
480 }
481 }
482 MsgBox "Changed the options", MB_ICONINFORMATION, $svcname
483 unless CMDLINE or $inst or $run_with_params;
484 exit if ($inst or !$run_with_params); # if we have params
485 }
486  
487 eval $logging_code; die "$@\n" if $@;
488 $logging_code = '';
489  
490 if (!$^C) {
491 Win32::Daemon::StartService();
492  
493 if (CMDLINE) {
494 no warnings qw(redefine);
495 eval "sub Win32::Daemon::State {&SERVICE_START_PENDING}";
496 }
497  
498 while( SERVICE_START_PENDING != Win32::Daemon::State() ) {
499 sleep( 1 );
500 }
501  
502 if (CMDLINE) {
503 no warnings qw(redefine);
504 eval "sub Win32::Daemon::State {&SERVICE_RUNNING}";
505 }
506  
507 LogStart("\n$svcname ver. $svcversion started");
508  
509 Win32::Daemon::State( SERVICE_RUNNING );
510  
511 OpenLog();
512 LogNT("Read params");
513 {
514 local $^W;
515 no strict 'refs';
516 my $val;
517 foreach my $param (keys %$params) {
518 my $sub = uc $param;
519 if (exists $run_params->{lc $param}) {
520 $val = $run_params->{lc $param};
521 } else {
522 $val = ReadParam( $param, $params->{$param});
523 }
524 LogNT("\t$param: $val") unless lc($param) eq 'description';
525 if (! defined $val) {
526 eval "sub $sub () {undef}";
527 } elsif ($val =~ /^\d+(?:\.\d+)?$/) { # if it looks like a number it IS a number
528 $val += 0;
529 eval "sub $sub () {$val}";
530 } else {
531 $val =~ s{(['\\])}{\\$1}g;
532 eval "sub $sub () {'$val'}";
533 }
534 push @EXPORT, $sub;
535 }
536 eval "sub SERVICEID () {q\\$svcid\\}";
537 eval "sub SERVICENAME () {q\\$svcname\\}";
538 }
539 LogNT('Running');
540 CloseLog();
541 eval $loop_code; die "$@\n" if $@;
542 $loop_code = '';
543 } else {
544 foreach my $param (keys %$params) {
545 my $sub = uc $param;
546 eval "sub $sub () {}";
547 push @EXPORT, $sub;
548 }
549 eval "sub SERVICEID () {q\\$svcid\\}";
550 eval "sub SERVICENAME () {q\\$svcname\\}";
551 }
552 };
553 if ($@) {
554 if (CMDLINE) {
555 die "ERROR in use Win32::Daemon::Simple: $@\n";
556 } elsif ($params->{'LogFile'}) {
557 Log("ERROR in use Win32::Daemon::Simple: $@");
558 exit;
559 } elsif ($svcid) {
560 SaveParam("ERROR", $@);
561 exit;
562 } else {
563 exit(); # don't have a way to report the problem. The person should have tried it in commandline mode first.
564 }
565 } elsif (! $^C) { # if not being compiled
566 SaveParam("ERROR", undef);
567 };
568  
569 Win32::Daemon::Simple->export_to_level( 1, $caller_pack, @EXPORT);
570 }
571  
572 $loop_code = <<'-END--';
573 my $PrevState = SERVICE_START_PENDING;
574 sub SetState ($) {
575 Win32::Daemon::State($_[0]);
576 $PrevState = $_[0];
577 }
578  
579 END {
580 Win32::Daemon::State(SERVICE_STOPPED) unless $PrevState == SERVICE_STOPPED;
581 }
582  
583 sub ServiceLoop {
584 my $process = shift();
585 my $cnt = 1;
586 my $tick_cnt = 60;
587 my $state;
588 while (1) {
589 $state = Win32::Daemon::State();
590 if ($state == SERVICE_RUNNING or $state == 0x0080) {
591 # RUNNING
592 if ($state == 0x0080) {
593 SetState(SERVICE_RUNNING);
594 }
595  
596 # Check for any outstanding commands. Pass in a non zero value
597 # and it resets the Last Message to SERVICE_CONTROL_NONE.
598 if ( SERVICE_CONTROL_NONE != ( my $Message = Win32::Daemon::QueryLastMessage( 1 ))) {
599 if ( SERVICE_CONTROL_INTERROGATE == $Message ) {
600 # Got here if the Service Control Manager is requesting
601 # the current state of the service. This can happen for
602 # a variety of reasons. Report the last state we set.
603 Win32::Daemon::State( $PrevState );
604 } elsif ( SERVICE_CONTROL_SHUTDOWN == $Message ) {
605 # Yikes! The system is shutting down. We had better clean up
606 # and stop.
607 # Tell the SCM that we are preparing to shutdown and that we expect
608 # it to take 25 seconds (so don't terminate us for at least 25 seconds)...
609 Win32::Daemon::State( SERVICE_STOP_PENDING, 25000 );
610 } else {
611 # Got an unhandled control message. Set the state to
612 # whatever the previous state was.
613 Log("Unhandled service message: $Message");
614 Win32::Daemon::State( $PrevState );
615 }
616 }
617  
618 if (--$cnt == 0) {
619 print " \r" if CMDLINE;
620 $cnt = int(INTERVAL * 60);
621 eval {$process->()};
622 if ($@) {
623 Log("ERROR: $@");
624 LogNT;
625 }
626 }
627 if (TICK and (--$tick_cnt == 0)) {
628 LogNT('tick: '.Now()) ;
629 $tick_cnt = 60;
630 }
631 print "\r$cnt \r" if CMDLINE;
632 sleep 1;
633 # /RUNNING
634 } elsif ($state == SERVICE_PAUSE_PENDING) {
635 SetState(SERVICE_PAUSED);
636 Log("Paused");
637 } elsif ($state == SERVICE_PAUSED) {
638 sleep 10;
639 } elsif ($state == SERVICE_CONTINUE_PENDING) {
640 SetState(SERVICE_RUNNING);
641 Log("Continue");
642 } elsif ($state == SERVICE_STOP_PENDING or $state == SERVICE_STOPPED) {
643 SetState(SERVICE_STOPPED);
644 Log("Asked to stop");
645 last;
646 } else {
647 Log("Unexpected state : $state");
648 last;
649 }
650 }
651  
652 Win32::Daemon::StopService();
653 }
654  
655 sub DoHandler {
656 my ($handler, $do) = @_;
657 if (defined $handler) {
658 if (ref $handler) {
659 if ($handler->(1)) {
660 $do->();
661 return 1;
662 }
663 } elsif ($handler) {
664 $do->();
665 return 1;
666 }
667 return;
668 }
669 $do->();
670 return 1;
671 }
672  
673 sub DoEvents { # (\&PauseProc, \&UnpauseProc, \&StopProc)
674 my $state = Win32::Daemon::State();
675 if ($state == SERVICE_RUNNING or $state == 0x0080) {
676 # RUNNING
677 if ($state == 0x0080) {
678 Win32::Daemon::SetState(SERVICE_RUNNING);
679 }
680  
681 # Check for any outstanding commands. Pass in a non zero value
682 # and it resets the Last Message to SERVICE_CONTROL_NONE.
683 if ( SERVICE_CONTROL_NONE != ( my $Message = Win32::Daemon::QueryLastMessage( 1 ))) {
684 if ( SERVICE_CONTROL_INTERROGATE == $Message ) {
685 # Got here if the Service Control Manager is requesting
686 # the current state of the service. This can happen for
687 # a variety of reasons. Report the last state we set.
688 Win32::Daemon::State( $PrevState );
689 } elsif ( SERVICE_CONTROL_SHUTDOWN == $Message ) {
690 # Yikes! The system is shutting down. We had better clean up
691 # and stop.
692 # Tell the SCM that we are preparing to shutdown and that we expect
693 # it to take 25 seconds (so don't terminate us for at least 25 seconds)...
694 Log("Asked to stop (The server's going down!)");
695 Win32::Daemon::State( SERVICE_STOP_PENDING, 25000 );
696 DoHandler( $_[2], sub {Win32::Daemon::StopService();Log("Going down");exit;});
697 } else {
698 # Got an unhandled control message. Set the state to
699 # whatever the previous state was.
700 Log("Unhandled service message: $Message");
701 Win32::Daemon::State( $PrevState );
702 }
703 }
704 return SERVICE_RUNNING;
705 # /RUNNING
706 } elsif ($state == SERVICE_PAUSE_PENDING) {
707 if (DoHandler( $_[0], sub {SetState(SERVICE_PAUSED);Log("Paused")})) {
708 return Pause(@_[1,2]);
709 } else {
710 return SERVICE_PAUSE_PENDING;
711 }
712 } elsif ($state == SERVICE_PAUSED) {
713 return Pause(@_[1,2]);
714 } elsif ($state == SERVICE_CONTINUE_PENDING) {
715 SetState(SERVICE_RUNNING);
716 Log("Continue");
717 $_[1]->() if (defined $_[1] and ref $_[1] eq 'CODE');
718 } elsif ($state == SERVICE_STOP_PENDING or $state == SERVICE_STOPPED) {
719 Log("Asked to stop");
720 DoHandler( $_[2], sub {Win32::Daemon::StopService();Log("Going down");exit;});
721 return SERVICE_STOP_PENDING;
722 } else {
723 Log("Unexpected state : $state");
724 return $state
725 }
726 }
727  
728 sub Pause {
729 my $state;
730 while (1) {
731 sleep(5);
732 $state = Win32::Daemon::State();
733 next if $state == SERVICE_PAUSED;
734  
735 if ($state == SERVICE_STOP_PENDING or $state == SERVICE_STOPPED) {
736 Log("Asked to stop");
737 DoHandler( $_[1], sub {Win32::Daemon::StopService();Log("Going down");exit;});
738 return SERVICE_STOP_PENDING;
739 } else {
740 # unpausing
741 Log("Continue");
742 $_[0]->() if (defined $_[0] and ref $_[0] eq 'CODE');
743 SetState(SERVICE_RUNNING);
744 return SERVICE_RUNNING
745 }
746 }
747 }
748  
749 -END--
750  
751 # logging
752 $logging_code = <<'-END--';
753 {
754 my $logfile;
755 my $catchmessages = 0;
756 my $messages = '';
757 my $LOG = new FileHandle;
758 sub LogStart {
759 $logfile = $run_params->{'logfile'} || ReadParam('LogFile', $params->{'LogFile'})
760 unless $logfile;
761 open $LOG, ">> $logfile";
762 print $LOG @_, " at ", Now(),"\n";
763 print STDOUT @_,"\n" if CMDLINE;
764 close $LOG;
765 }
766 sub Log {
767 my $had_to_open = 0;
768 if (! $LOG->opened()) {
769 $had_to_open = 1;
770 unshift @_, "$svcname $svcversion\n"
771 unless -e $logfile;
772 open $LOG, ">> $logfile";
773 }
774 print $LOG @_, " at ", Now(),"\n";
775 $messages .= join '', @_,"\n"
776 if $catchmessages;
777 print STDOUT @_,"\n"
778 if CMDLINE;
779 close $LOG
780 if $had_to_open;
781 }
782 sub LogNT {
783 my $had_to_open = 0;
784 if (! $LOG->opened()) {
785 $had_to_open = 1;
786 unshift @_, "$svcname $svcversion\n"
787 unless -e $logfile;
788 open $LOG, ">> $logfile";
789 }
790 print $LOG @_,"\n";
791 $messages .= join '', @_,"\n"
792 if $catchmessages;
793 print STDOUT @_,"\n"
794 if CMDLINE;
795 close $LOG
796 if $had_to_open;
797 }
798 sub OpenLog () {
799 if (! $LOG->opened()) {
800 $logfile = ReadParam('LogFile', $params->{'LogFile'})
801 unless $logfile;
802 my $existed = -e $logfile;
803 open $LOG, ">> $logfile";
804 print $LOG "$svcname $svcversion\n"
805 unless $existed;
806 }
807 }
808 sub CloseLog () {
809 close $LOG if $LOG->opened();
810 }
811 sub CatchMessages {
812 $catchmessages = shift();
813 $messages = '';
814 }
815 sub GetMessages {
816 my $msg = $messages;
817 $messages = '';
818 return $msg;
819 }
820 sub RedirectLog {
821 $logfile = shift();
822 }
823 }
824 -END--
825  
826  
827 1;
828  
829 __END__