1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 # FILE: gosa-sd
5 #
6 # USAGE: ./gosa-sd
7 #
8 # DESCRIPTION:
9 #
10 # OPTIONS: ---
11 # REQUIREMENTS: libconfig-inifiles-perl libcrypt-rijndael-perl libxml-simple-perl
12 # libdata-dumper-simple-perl libdbd-sqlite3-perl libnet-ldap-perl
13 # libpoe-perl
14 # BUGS: ---
15 # NOTES:
16 # AUTHOR: (Andreas Rettenberger), <rettenberger@gonicus.de>
17 # COMPANY:
18 # VERSION: 1.0
19 # CREATED: 12.09.2007 08:54:41 CEST
20 # REVISION: ---
21 #===============================================================================
24 # TODO
25 #
26 # max_children wird momentan nicht mehr verwendet, jede eingehende nachricht bekommt ein eigenes POE child
28 use strict;
29 use warnings;
30 use Getopt::Long;
31 use Config::IniFiles;
32 use POSIX;
34 use Fcntl;
35 use IO::Socket::INET;
36 use IO::Handle;
37 use IO::Select;
38 use Symbol qw(qualify_to_ref);
39 use Crypt::Rijndael;
40 use MIME::Base64;
41 use Digest::MD5 qw(md5 md5_hex md5_base64);
42 use XML::Simple;
43 use Data::Dumper;
44 use Sys::Syslog qw( :DEFAULT setlogsock);
45 use Cwd;
46 use File::Spec;
47 use File::Basename;
48 use File::Find;
49 use File::Copy;
50 use File::Path;
51 use GOSA::DBsqlite;
52 use GOSA::GosaSupportDaemon;
53 use POE qw(Component::Server::TCP Wheel::Run Filter::Reference);
54 use Net::LDAP;
55 use Net::LDAP::Util qw(:escape);
56 use Time::HiRes qw( usleep);
57 use DateTime;
59 my $modules_path = "/usr/lib/gosa-si/modules";
60 use lib "/usr/lib/gosa-si/modules";
62 # revision number of server and program name
63 my $server_version = '$HeadURL: https://oss.gonicus.de/repositories/gosa/trunk/gosa-si/gosa-si-server $:$Rev: 10826 $';
64 my $server_headURL;
65 my $server_revision;
66 my $server_status;
67 our $prg= basename($0);
69 our $global_kernel;
70 my ($foreground, $ping_timeout);
71 my ($server);
72 my ($gosa_server, $job_queue_timeout, $job_queue_loop_delay);
73 my ($messaging_db_loop_delay);
74 my ($known_modules);
75 my ($procid, $pid);
76 my ($arp_fifo);
77 my ($xml);
78 my $sources_list;
79 my $max_clients;
80 my %repo_files=();
81 my $repo_path;
82 my %repo_dirs=();
83 # variables declared in config file are always set to 'our'
84 our (%cfg_defaults, $log_file, $pid_file,
85 $server_ip, $server_port, $ClientPackages_key,
86 $arp_activ, $gosa_unit_tag,
87 $GosaPackages_key, $gosa_timeout,
88 $foreign_server_string, $server_domain, $ServerPackages_key, $foreign_servers_register_delay,
89 $wake_on_lan_passwd, $job_synchronization, $modified_jobs_loop_delay,
90 $arp_enabled, $arp_interface,
91 $opsi_enabled, $opsi_server, $opsi_admin, $opsi_password,
92 );
94 # additional variable which should be globaly accessable
95 our $server_address;
96 our $server_mac_address;
97 our $gosa_address;
98 our $no_arp;
99 our $verbose;
100 our $forground;
101 our $cfg_file;
102 our ($ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $ldap_server_dn);
104 # specifies the verbosity of the daemon_log
105 $verbose = 0 ;
107 # if foreground is not null, script will be not forked to background
108 $foreground = 0 ;
110 # specifies the timeout seconds while checking the online status of a registrating client
111 $ping_timeout = 5;
113 $no_arp = 0;
114 my $packages_list_under_construction = "/tmp/packages_list_creation_in_progress";
115 my @packages_list_statements;
116 my $watch_for_new_jobs_in_progress = 0;
118 # holds all incoming decrypted messages
119 our $incoming_db;
120 our $incoming_tn = 'incoming';
121 my $incoming_file_name;
122 my @incoming_col_names = ("id INTEGER PRIMARY KEY",
123 "timestamp DEFAULT 'none'",
124 "headertag DEFAULT 'none'",
125 "targettag DEFAULT 'none'",
126 "xmlmessage DEFAULT 'none'",
127 "module DEFAULT 'none'",
128 "sessionid DEFAULT '0'",
129 );
131 # holds all gosa jobs
132 our $job_db;
133 our $job_queue_tn = 'jobs';
134 my $job_queue_file_name;
135 my @job_queue_col_names = ("id INTEGER PRIMARY KEY",
136 "timestamp DEFAULT 'none'",
137 "status DEFAULT 'none'",
138 "result DEFAULT 'none'",
139 "progress DEFAULT 'none'",
140 "headertag DEFAULT 'none'",
141 "targettag DEFAULT 'none'",
142 "xmlmessage DEFAULT 'none'",
143 "macaddress DEFAULT 'none'",
144 "plainname DEFAULT 'none'",
145 "siserver DEFAULT 'none'",
146 "modified DEFAULT '0'",
147 );
149 # holds all other gosa-si-server
150 our $known_server_db;
151 our $known_server_tn = "known_server";
152 my $known_server_file_name;
153 my @known_server_col_names = ("hostname", "status", "hostkey", "timestamp");
155 # holds all registrated clients
156 our $known_clients_db;
157 our $known_clients_tn = "known_clients";
158 my $known_clients_file_name;
159 my @known_clients_col_names = ("hostname", "status", "hostkey", "timestamp", "macaddress", "events", "keylifetime");
161 # holds all registered clients at a foreign server
162 our $foreign_clients_db;
163 our $foreign_clients_tn = "foreign_clients";
164 my $foreign_clients_file_name;
165 my @foreign_clients_col_names = ("hostname", "macaddress", "regserver", "timestamp");
167 # holds all logged in user at each client
168 our $login_users_db;
169 our $login_users_tn = "login_users";
170 my $login_users_file_name;
171 my @login_users_col_names = ("client", "user", "timestamp");
173 # holds all fai server, the debian release and tag
174 our $fai_server_db;
175 our $fai_server_tn = "fai_server";
176 my $fai_server_file_name;
177 our @fai_server_col_names = ("timestamp", "server", "release", "sections", "tag");
179 our $fai_release_db;
180 our $fai_release_tn = "fai_release";
181 my $fai_release_file_name;
182 our @fai_release_col_names = ("timestamp", "release", "class", "type", "state");
184 # holds all packages available from different repositories
185 our $packages_list_db;
186 our $packages_list_tn = "packages_list";
187 my $packages_list_file_name;
188 our @packages_list_col_names = ("distribution", "package", "version", "section", "description", "template", "timestamp");
189 my $outdir = "/tmp/packages_list_db";
190 my $arch = "i386";
192 # holds all messages which should be delivered to a user
193 our $messaging_db;
194 our $messaging_tn = "messaging";
195 our @messaging_col_names = ("id INTEGER", "subject", "message_from", "message_to",
196 "flag", "direction", "delivery_time", "message", "timestamp" );
197 my $messaging_file_name;
199 # path to directory to store client install log files
200 our $client_fai_log_dir = "/var/log/fai";
202 # queue which stores taskes until one of the $max_children children are ready to process the task
203 my @tasks = qw();
204 my @msgs_to_decrypt = qw();
205 my $max_children = 2;
208 # loop delay for job queue to look for opsi jobs
209 my $job_queue_opsi_delay = 10;
210 our $opsi_client;
211 our $opsi_url;
215 %cfg_defaults = (
216 "general" => {
217 "log-file" => [\$log_file, "/var/run/".$prg.".log"],
218 "pid-file" => [\$pid_file, "/var/run/".$prg.".pid"],
219 },
220 "server" => {
221 "ip" => [\$server_ip, "0.0.0.0"],
222 "port" => [\$server_port, "20081"],
223 "known-clients" => [\$known_clients_file_name, '/var/lib/gosa-si/clients.db' ],
224 "known-servers" => [\$known_server_file_name, '/var/lib/gosa-si/servers.db'],
225 "incoming" => [\$incoming_file_name, '/var/lib/gosa-si/incoming.db'],
226 "login-users" => [\$login_users_file_name, '/var/lib/gosa-si/users.db'],
227 "fai-server" => [\$fai_server_file_name, '/var/lib/gosa-si/fai_server.db'],
228 "fai-release" => [\$fai_release_file_name, '/var/lib/gosa-si/fai_release.db'],
229 "packages-list" => [\$packages_list_file_name, '/var/lib/gosa-si/packages.db'],
230 "messaging" => [\$messaging_file_name, '/var/lib/gosa-si/messaging.db'],
231 "foreign-clients" => [\$foreign_clients_file_name, '/var/lib/gosa-si/foreign_clients.db'],
232 "source-list" => [\$sources_list, '/etc/apt/sources.list'],
233 "repo-path" => [\$repo_path, '/srv/www/repository'],
234 "ldap-uri" => [\$ldap_uri, ""],
235 "ldap-base" => [\$ldap_base, ""],
236 "ldap-admin-dn" => [\$ldap_admin_dn, ""],
237 "ldap-admin-password" => [\$ldap_admin_password, ""],
238 "gosa-unit-tag" => [\$gosa_unit_tag, ""],
239 "max-clients" => [\$max_clients, 10],
240 "wol-password" => [\$wake_on_lan_passwd, ""],
241 },
242 "GOsaPackages" => {
243 "job-queue" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
244 "job-queue-loop-delay" => [\$job_queue_loop_delay, 3],
245 "messaging-db-loop-delay" => [\$messaging_db_loop_delay, 3],
246 "key" => [\$GosaPackages_key, "none"],
247 },
248 "ClientPackages" => {
249 "key" => [\$ClientPackages_key, "none"],
250 },
251 "ServerPackages"=> {
252 "address" => [\$foreign_server_string, ""],
253 "domain" => [\$server_domain, ""],
254 "key" => [\$ServerPackages_key, "none"],
255 "key-lifetime" => [\$foreign_servers_register_delay, 120],
256 "job-synchronization-enabled" => [\$job_synchronization, "true"],
257 "synchronization-loop" => [\$modified_jobs_loop_delay, 5],
258 },
259 "ArpHandler" => {
260 "enabled" => [\$arp_enabled, "true"],
261 "interface" => [\$arp_interface, "all"],
262 },
263 "Opsi" => {
264 "enabled" => [\$opsi_enabled, "false"],
265 "server" => [\$opsi_server, "localhost"],
266 "admin" => [\$opsi_admin, "opsi-admin"],
267 "password" => [\$opsi_password, "secret"],
268 },
270 );
273 #=== FUNCTION ================================================================
274 # NAME: usage
275 # PARAMETERS: nothing
276 # RETURNS: nothing
277 # DESCRIPTION: print out usage text to STDERR
278 #===============================================================================
279 sub usage {
280 print STDERR << "EOF" ;
281 usage: $prg [-hvf] [-c config]
283 -h : this (help) message
284 -c <file> : config file
285 -f : foreground, process will not be forked to background
286 -v : be verbose (multiple to increase verbosity)
287 -no-arp : starts $prg without connection to arp module
289 EOF
290 print "\n" ;
291 }
294 #=== FUNCTION ================================================================
295 # NAME: logging
296 # PARAMETERS: level - string - default 'info'
297 # msg - string -
298 # facility - string - default 'LOG_DAEMON'
299 # RETURNS: nothing
300 # DESCRIPTION: function for logging
301 #===============================================================================
302 sub daemon_log {
303 # log into log_file
304 my( $msg, $level ) = @_;
305 if(not defined $msg) { return }
306 if(not defined $level) { $level = 1 }
307 if(defined $log_file){
308 open(LOG_HANDLE, ">>$log_file");
309 chmod 0600, $log_file;
310 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
311 print STDERR "cannot open $log_file: $!";
312 return
313 }
314 chomp($msg);
315 #$msg =~s/\n//g; # no newlines are allowed in log messages, this is important for later log parsing
316 if($level <= $verbose){
317 my ($seconds, $minutes, $hours, $monthday, $month,
318 $year, $weekday, $yearday, $sommertime) = localtime(time);
319 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
320 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
321 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
322 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
323 $month = $monthnames[$month];
324 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
325 $year+=1900;
326 my $name = $prg;
328 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
329 print LOG_HANDLE $log_msg;
330 if( $foreground ) {
331 print STDERR $log_msg;
332 }
333 }
334 close( LOG_HANDLE );
335 }
336 }
339 #=== FUNCTION ================================================================
340 # NAME: check_cmdline_param
341 # PARAMETERS: nothing
342 # RETURNS: nothing
343 # DESCRIPTION: validates commandline parameter
344 #===============================================================================
345 sub check_cmdline_param () {
346 my $err_config;
347 my $err_counter = 0;
348 if(not defined($cfg_file)) {
349 $cfg_file = "/etc/gosa-si/server.conf";
350 if(! -r $cfg_file) {
351 $err_config = "please specify a config file";
352 $err_counter += 1;
353 }
354 }
355 if( $err_counter > 0 ) {
356 &usage( "", 1 );
357 if( defined( $err_config)) { print STDERR "$err_config\n"}
358 print STDERR "\n";
359 exit( -1 );
360 }
361 }
364 #=== FUNCTION ================================================================
365 # NAME: check_pid
366 # PARAMETERS: nothing
367 # RETURNS: nothing
368 # DESCRIPTION: handels pid processing
369 #===============================================================================
370 sub check_pid {
371 $pid = -1;
372 # Check, if we are already running
373 if( open(LOCK_FILE, "<$pid_file") ) {
374 $pid = <LOCK_FILE>;
375 if( defined $pid ) {
376 chomp( $pid );
377 if( -f "/proc/$pid/stat" ) {
378 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
379 if( $stat ) {
380 daemon_log("ERROR: Already running",1);
381 close( LOCK_FILE );
382 exit -1;
383 }
384 }
385 }
386 close( LOCK_FILE );
387 unlink( $pid_file );
388 }
390 # create a syslog msg if it is not to possible to open PID file
391 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
392 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
393 if (open(LOCK_FILE, '<', $pid_file)
394 && ($pid = <LOCK_FILE>))
395 {
396 chomp($pid);
397 $msg .= "(PID $pid)\n";
398 } else {
399 $msg .= "(unable to read PID)\n";
400 }
401 if( ! ($foreground) ) {
402 openlog( $0, "cons,pid", "daemon" );
403 syslog( "warning", $msg );
404 closelog();
405 }
406 else {
407 print( STDERR " $msg " );
408 }
409 exit( -1 );
410 }
411 }
413 #=== FUNCTION ================================================================
414 # NAME: import_modules
415 # PARAMETERS: module_path - string - abs. path to the directory the modules
416 # are stored
417 # RETURNS: nothing
418 # DESCRIPTION: each file in module_path which ends with '.pm' and activation
419 # state is on is imported by "require 'file';"
420 #===============================================================================
421 sub import_modules {
422 daemon_log(" ", 1);
424 if (not -e $modules_path) {
425 daemon_log("0 ERROR: cannot find directory or directory is not readable: $modules_path", 1);
426 }
428 opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
429 while (defined (my $file = readdir (DIR))) {
430 if (not $file =~ /(\S*?).pm$/) {
431 next;
432 }
433 my $mod_name = $1;
435 # ArpHandler switch
436 if( $file =~ /ArpHandler.pm/ ) {
437 if( $arp_enabled eq "false" ) { next; }
438 }
440 eval { require $file; };
441 if ($@) {
442 daemon_log("0 ERROR: gosa-si-server could not load module $file", 1);
443 daemon_log("$@", 5);
444 } else {
445 my $info = eval($mod_name.'::get_module_info()');
446 # Only load module if get_module_info() returns a non-null object
447 if( $info ) {
448 my ($input_address, $input_key, $input, $input_active, $input_type) = @{$info};
449 $known_modules->{$mod_name} = $info;
450 daemon_log("0 INFO: module $mod_name loaded", 5);
451 }
452 }
453 }
454 close (DIR);
455 }
457 #=== FUNCTION ================================================================
458 # NAME: password_check
459 # PARAMETERS: nothing
460 # RETURNS: nothing
461 # DESCRIPTION: escalates an critical error if two modules exist which are avaialable by
462 # the same password
463 #===============================================================================
464 sub password_check {
465 my $passwd_hash = {};
466 while (my ($mod_name, $mod_info) = each %$known_modules) {
467 my $mod_passwd = @$mod_info[1];
468 if (not defined $mod_passwd) { next; }
469 if (not exists $passwd_hash->{$mod_passwd}) {
470 $passwd_hash->{$mod_passwd} = $mod_name;
472 # escalates critical error
473 } else {
474 &daemon_log("0 ERROR: two loaded modules do have the same password. Please modify the 'key'-parameter in config file");
475 &daemon_log("0 ERROR: module='$mod_name' and module='".$passwd_hash->{$mod_passwd}."'");
476 exit( -1 );
477 }
478 }
480 }
483 #=== FUNCTION ================================================================
484 # NAME: sig_int_handler
485 # PARAMETERS: signal - string - signal arose from system
486 # RETURNS: nothing
487 # DESCRIPTION: handels tasks to be done befor signal becomes active
488 #===============================================================================
489 sub sig_int_handler {
490 my ($signal) = @_;
492 # if (defined($ldap_handle)) {
493 # $ldap_handle->disconnect;
494 # }
495 # TODO alle verbliebenden ldap verbindungen aus allen heaps beenden
498 daemon_log("shutting down gosa-si-server", 1);
499 system("kill `ps -C gosa-si-server -o pid=`");
500 }
501 $SIG{INT} = \&sig_int_handler;
504 sub check_key_and_xml_validity {
505 my ($crypted_msg, $module_key, $session_id) = @_;
506 my $msg;
507 my $msg_hash;
508 my $error_string;
509 eval{
510 $msg = &decrypt_msg($crypted_msg, $module_key);
512 if ($msg =~ /<xml>/i){
513 $msg =~ s/\s+/ /g; # just for better daemon_log
514 daemon_log("$session_id DEBUG: decrypted_msg: \n$msg", 8);
515 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
517 ##############
518 # check header
519 if( not exists $msg_hash->{'header'} ) { die "no header specified"; }
520 my $header_l = $msg_hash->{'header'};
521 if( 1 > @{$header_l} ) { die 'empty header tag'; }
522 if( 1 < @{$header_l} ) { die 'more than one header specified'; }
523 my $header = @{$header_l}[0];
524 if( 0 == length $header) { die 'empty string in header tag'; }
526 ##############
527 # check source
528 if( not exists $msg_hash->{'source'} ) { die "no source specified"; }
529 my $source_l = $msg_hash->{'source'};
530 if( 1 > @{$source_l} ) { die 'empty source tag'; }
531 if( 1 < @{$source_l} ) { die 'more than one source specified'; }
532 my $source = @{$source_l}[0];
533 if( 0 == length $source) { die 'source error'; }
535 ##############
536 # check target
537 if( not exists $msg_hash->{'target'} ) { die "no target specified"; }
538 my $target_l = $msg_hash->{'target'};
539 if( 1 > @{$target_l} ) { die 'empty target tag'; }
540 }
541 };
542 if($@) {
543 daemon_log("$session_id DEBUG: do not understand the message: $@", 7);
544 $msg = undef;
545 $msg_hash = undef;
546 }
548 return ($msg, $msg_hash);
549 }
552 sub check_outgoing_xml_validity {
553 my ($msg, $session_id) = @_;
555 my $msg_hash;
556 eval{
557 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
559 ##############
560 # check header
561 my $header_l = $msg_hash->{'header'};
562 if( 1 != @{$header_l} ) {
563 die 'no or more than one headers specified';
564 }
565 my $header = @{$header_l}[0];
566 if( 0 == length $header) {
567 die 'header has length 0';
568 }
570 ##############
571 # check source
572 my $source_l = $msg_hash->{'source'};
573 if( 1 != @{$source_l} ) {
574 die 'no or more than 1 sources specified';
575 }
576 my $source = @{$source_l}[0];
577 if( 0 == length $source) {
578 die 'source has length 0';
579 }
580 unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
581 $source =~ /^GOSA$/i ) {
582 die "source '$source' is neither a complete ip-address with port nor 'GOSA'";
583 }
585 ##############
586 # check target
587 my $target_l = $msg_hash->{'target'};
588 if( 0 == @{$target_l} ) {
589 die "no targets specified";
590 }
591 foreach my $target (@$target_l) {
592 if( 0 == length $target) {
593 die "target has length 0";
594 }
595 unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
596 $target =~ /^GOSA$/i ||
597 $target =~ /^\*$/ ||
598 $target =~ /KNOWN_SERVER/i ||
599 $target =~ /JOBDB/i ||
600 $target =~ /^([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})$/i ){
601 die "target '$target' is not a complete ip-address with port or a valid target name or a mac-address";
602 }
603 }
604 };
605 if($@) {
606 daemon_log("$session_id ERROR: outgoing msg is not gosa-si envelope conform: $@", 1);
607 daemon_log("$@ ".(defined($msg) && length($msg)>0)?$msg:"Empty Message", 1);
608 $msg_hash = undef;
609 }
611 return ($msg_hash);
612 }
615 sub input_from_known_server {
616 my ($input, $remote_ip, $session_id) = @_ ;
617 my ($msg, $msg_hash, $module);
619 my $sql_statement= "SELECT * FROM known_server";
620 my $query_res = $known_server_db->select_dbentry( $sql_statement );
622 while( my ($hit_num, $hit) = each %{ $query_res } ) {
623 my $host_name = $hit->{hostname};
624 if( not $host_name =~ "^$remote_ip") {
625 next;
626 }
627 my $host_key = $hit->{hostkey};
628 daemon_log("$session_id DEBUG: input_from_known_server: host_name: $host_name", 7);
629 daemon_log("$session_id DEBUG: input_from_known_server: host_key: $host_key", 7);
631 # check if module can open msg envelope with module key
632 my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key, $session_id);
633 if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
634 daemon_log("$session_id DEBUG: input_from_known_server: deciphering raise error", 7);
635 daemon_log("$@", 8);
636 next;
637 }
638 else {
639 $msg = $tmp_msg;
640 $msg_hash = $tmp_msg_hash;
641 $module = "ServerPackages";
642 last;
643 }
644 }
646 if( (!$msg) || (!$msg_hash) || (!$module) ) {
647 daemon_log("$session_id DEBUG: Incoming message is not from a known server", 7);
648 }
650 return ($msg, $msg_hash, $module);
651 }
654 sub input_from_known_client {
655 my ($input, $remote_ip, $session_id) = @_ ;
656 my ($msg, $msg_hash, $module);
658 my $sql_statement= "SELECT * FROM known_clients";
659 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
660 while( my ($hit_num, $hit) = each %{ $query_res } ) {
661 my $host_name = $hit->{hostname};
662 if( not $host_name =~ /^$remote_ip:\d*$/) {
663 next;
664 }
665 my $host_key = $hit->{hostkey};
666 &daemon_log("$session_id DEBUG: input_from_known_client: host_name: $host_name", 7);
667 &daemon_log("$session_id DEBUG: input_from_known_client: host_key: $host_key", 7);
669 # check if module can open msg envelope with module key
670 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key, $session_id);
672 if( (!$msg) || (!$msg_hash) ) {
673 &daemon_log("$session_id DEGUG: input_from_known_client: deciphering raise error", 7);
674 &daemon_log("$@", 8);
675 next;
676 }
677 else {
678 $module = "ClientPackages";
679 last;
680 }
681 }
683 if( (!$msg) || (!$msg_hash) || (!$module) ) {
684 &daemon_log("$session_id DEBUG: Incoming message is not from a known client", 7);
685 }
687 return ($msg, $msg_hash, $module);
688 }
691 sub input_from_unknown_host {
692 no strict "refs";
693 my ($input, $session_id) = @_ ;
694 my ($msg, $msg_hash, $module);
695 my $error_string;
697 my %act_modules = %$known_modules;
699 while( my ($mod, $info) = each(%act_modules)) {
701 # check a key exists for this module
702 my $module_key = ${$mod."_key"};
703 if( not defined $module_key ) {
704 if( $mod eq 'ArpHandler' ) {
705 next;
706 }
707 daemon_log("$session_id ERROR: no key specified in config file for $mod", 1);
708 next;
709 }
710 daemon_log("$session_id DEBUG: $mod: $module_key", 7);
712 # check if module can open msg envelope with module key
713 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key, $session_id);
714 if( (not defined $msg) || (not defined $msg_hash) ) {
715 next;
716 }
717 else {
718 $module = $mod;
719 last;
720 }
721 }
723 if( (!$msg) || (!$msg_hash) || (!$module)) {
724 daemon_log("$session_id DEBUG: Incoming message is not from an unknown host", 7);
725 }
727 return ($msg, $msg_hash, $module);
728 }
731 sub create_ciphering {
732 my ($passwd) = @_;
733 if((!defined($passwd)) || length($passwd)==0) {
734 $passwd = "";
735 }
736 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
737 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
738 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
739 $my_cipher->set_iv($iv);
740 return $my_cipher;
741 }
744 sub encrypt_msg {
745 my ($msg, $key) = @_;
746 my $my_cipher = &create_ciphering($key);
747 my $len;
748 {
749 use bytes;
750 $len= 16-length($msg)%16;
751 }
752 $msg = "\0"x($len).$msg;
753 $msg = $my_cipher->encrypt($msg);
754 chomp($msg = &encode_base64($msg));
755 # there are no newlines allowed inside msg
756 $msg=~ s/\n//g;
757 return $msg;
758 }
761 sub decrypt_msg {
763 my ($msg, $key) = @_ ;
764 $msg = &decode_base64($msg);
765 my $my_cipher = &create_ciphering($key);
766 $msg = $my_cipher->decrypt($msg);
767 $msg =~ s/\0*//g;
768 return $msg;
769 }
772 sub get_encrypt_key {
773 my ($target) = @_ ;
774 my $encrypt_key;
775 my $error = 0;
777 # target can be in known_server
778 if( not defined $encrypt_key ) {
779 my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
780 my $query_res = $known_server_db->select_dbentry( $sql_statement );
781 while( my ($hit_num, $hit) = each %{ $query_res } ) {
782 my $host_name = $hit->{hostname};
783 if( $host_name ne $target ) {
784 next;
785 }
786 $encrypt_key = $hit->{hostkey};
787 last;
788 }
789 }
791 # target can be in known_client
792 if( not defined $encrypt_key ) {
793 my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
794 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
795 while( my ($hit_num, $hit) = each %{ $query_res } ) {
796 my $host_name = $hit->{hostname};
797 if( $host_name ne $target ) {
798 next;
799 }
800 $encrypt_key = $hit->{hostkey};
801 last;
802 }
803 }
805 return $encrypt_key;
806 }
809 #=== FUNCTION ================================================================
810 # NAME: open_socket
811 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
812 # [PeerPort] string necessary if port not appended by PeerAddr
813 # RETURNS: socket IO::Socket::INET
814 # DESCRIPTION: open a socket to PeerAddr
815 #===============================================================================
816 sub open_socket {
817 my ($PeerAddr, $PeerPort) = @_ ;
818 if(defined($PeerPort)){
819 $PeerAddr = $PeerAddr.":".$PeerPort;
820 }
821 my $socket;
822 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
823 Porto => "tcp",
824 Type => SOCK_STREAM,
825 Timeout => 5,
826 );
827 if(not defined $socket) {
828 return;
829 }
830 # &daemon_log("DEBUG: open_socket: $PeerAddr", 7);
831 return $socket;
832 }
835 sub get_local_ip_for_remote_ip {
836 my $remote_ip= shift;
837 my $result="0.0.0.0";
839 if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
840 if($remote_ip eq "127.0.0.1") {
841 $result = "127.0.0.1";
842 } else {
843 my $PROC_NET_ROUTE= ('/proc/net/route');
845 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
846 or die "Could not open $PROC_NET_ROUTE";
848 my @ifs = <PROC_NET_ROUTE>;
850 close(PROC_NET_ROUTE);
852 # Eat header line
853 shift @ifs;
854 chomp @ifs;
855 foreach my $line(@ifs) {
856 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
857 my $destination;
858 my $mask;
859 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
860 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
861 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
862 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
863 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
864 # destination matches route, save mac and exit
865 $result= &get_ip($Iface);
866 last;
867 }
868 }
869 }
870 } else {
871 daemon_log("0 WARNING: get_local_ip_for_remote_ip() was called with a non-ip parameter: '$remote_ip'", 1);
872 }
873 return $result;
874 }
877 sub send_msg_to_target {
878 my ($msg, $address, $encrypt_key, $msg_header, $session_id) = @_ ;
879 my $error = 0;
880 my $header;
881 my $timestamp = &get_time();
882 my $new_status;
883 my $act_status;
884 my ($sql_statement, $res);
886 if( $msg_header ) {
887 $header = "'$msg_header'-";
888 } else {
889 $header = "";
890 }
892 # Patch the source ip
893 if($msg =~ /<source>0\.0\.0\.0:\d*?<\/source>/) {
894 my $remote_ip = &get_local_ip_for_remote_ip(sprintf("%s", $address =~ /^([0-9\.]*?):.*$/));
895 $msg =~ s/<source>(0\.0\.0\.0):(\d*?)<\/source>/<source>$remote_ip:$2<\/source>/s;
896 }
898 # encrypt xml msg
899 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
901 # opensocket
902 my $socket = &open_socket($address);
903 if( !$socket ) {
904 daemon_log("$session_id WARNING: cannot send ".$header."msg to $address , host not reachable", 3);
905 $error++;
906 }
908 if( $error == 0 ) {
909 # send xml msg
910 print $socket $crypted_msg."\n";
912 daemon_log("$session_id INFO: send ".$header."msg to $address", 5);
913 daemon_log("$session_id DEBUG: message:\n$msg", 9);
915 }
917 # close socket in any case
918 if( $socket ) {
919 close $socket;
920 }
922 if( $error > 0 ) { $new_status = "down"; }
923 else { $new_status = $msg_header; }
926 # known_clients
927 $sql_statement = "SELECT * FROM $known_clients_tn WHERE hostname='$address'";
928 $res = $known_clients_db->select_dbentry($sql_statement);
929 if( keys(%$res) == 1) {
930 $act_status = exists $res->{1}->{'status'} ? $res->{1}->{'status'} : "";
931 if ($act_status eq "down" && $new_status eq "down") {
932 $sql_statement = "DELETE FROM known_clients WHERE hostname='$address'";
933 $res = $known_clients_db->del_dbentry($sql_statement);
934 daemon_log("$session_id WARNING: failed 2x to send msg to host '$address', delete host from known_clients", 3);
935 } else {
936 $sql_statement = "UPDATE known_clients SET status='$new_status', timestamp='$timestamp' WHERE hostname='$address'";
937 $res = $known_clients_db->update_dbentry($sql_statement);
938 if($new_status eq "down"){
939 daemon_log("$session_id WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
940 } else {
941 daemon_log("$session_id INFO: set '$address' from status '$act_status' to '$new_status'", 5);
942 }
943 }
944 }
946 # known_server
947 $sql_statement = "SELECT * FROM $known_server_tn WHERE hostname='$address'";
948 $res = $known_server_db->select_dbentry($sql_statement);
949 if( keys(%$res) == 1) {
950 $act_status = exists $res->{1}->{'status'} ? $res->{1}->{'status'} : "";
951 if ($act_status eq "down" && $new_status eq "down") {
952 $sql_statement = "DELETE FROM known_server WHERE hostname='$address'";
953 $res = $known_server_db->del_dbentry($sql_statement);
954 daemon_log("$session_id WARNING: failed 2x to send a message to host '$address', delete host from known_server", 3);
955 }
956 else {
957 $sql_statement = "UPDATE known_server SET status='$new_status', timestamp='$timestamp' WHERE hostname='$address'";
958 $res = $known_server_db->update_dbentry($sql_statement);
959 if($new_status eq "down"){
960 daemon_log("$session_id WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
961 } else {
962 daemon_log("$session_id INFO: set '$address' from status '$act_status' to '$new_status'", 5);
963 }
964 }
965 }
966 return $error;
967 }
970 sub update_jobdb_status_for_send_msgs {
971 my ($answer, $error) = @_;
972 if( $answer =~ /<jobdb_id>(\d+)<\/jobdb_id>/ ) {
973 my $jobdb_id = $1;
975 # sending msg faild
976 if( $error ) {
977 if (not $answer =~ /<header>trigger_action_reinstall<\/header>/) {
978 my $sql_statement = "UPDATE $job_queue_tn ".
979 "SET status='error', result='can not deliver msg, please consult log file' ".
980 "WHERE id=$jobdb_id";
981 my $res = $job_db->update_dbentry($sql_statement);
982 }
984 # sending msg was successful
985 } else {
986 my $sql_statement = "UPDATE $job_queue_tn ".
987 "SET status='done' ".
988 "WHERE id=$jobdb_id AND status='processed'";
989 my $res = $job_db->update_dbentry($sql_statement);
990 }
991 }
992 }
995 sub sig_handler {
996 my ($kernel, $signal) = @_[KERNEL, ARG0] ;
997 daemon_log("0 INFO got signal '$signal'", 1);
998 $kernel->sig_handled();
999 return;
1000 }
1003 sub msg_to_decrypt {
1004 my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
1005 my $session_id = $session->ID;
1006 my ($msg, $msg_hash, $module);
1007 my $error = 0;
1009 # hole neue msg aus @msgs_to_decrypt
1010 my $next_msg = shift @msgs_to_decrypt;
1012 # entschlüssle sie
1014 # msg is from a new client or gosa
1015 ($msg, $msg_hash, $module) = &input_from_unknown_host($next_msg, $session_id);
1016 # msg is from a gosa-si-server
1017 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
1018 ($msg, $msg_hash, $module) = &input_from_known_server($next_msg, $heap->{'remote_ip'}, $session_id);
1019 }
1020 # msg is from a gosa-si-client
1021 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
1022 ($msg, $msg_hash, $module) = &input_from_known_client($next_msg, $heap->{'remote_ip'}, $session_id);
1023 }
1024 # an error occurred
1025 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
1026 # if an incoming msg could not be decrypted (maybe a wrong key), send client a ping. If the client
1027 # could not understand a msg from its server the client cause a re-registering process
1028 daemon_log("$session_id WARNING cannot understand incoming msg, send 'ping'-msg to all host with ip '".$heap->{remote_ip}.
1029 "' to cause a re-registering of the client if necessary", 3);
1030 my $sql_statement = "SELECT * FROM $main::known_clients_tn WHERE (hostname LIKE '".$heap->{'remote_ip'}."%')";
1031 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
1032 while( my ($hit_num, $hit) = each %{ $query_res } ) {
1033 my $host_name = $hit->{'hostname'};
1034 my $host_key = $hit->{'hostkey'};
1035 my $ping_msg = "<xml> <header>gosa_ping</header> <source>$server_address</source> <target>$host_name</target></xml>";
1036 my $error = &send_msg_to_target($ping_msg, $host_name, $host_key, "gosa_ping", $session_id);
1037 &update_jobdb_status_for_send_msgs($ping_msg, $error);
1038 }
1039 $error++;
1040 }
1043 my $header;
1044 my $target;
1045 my $source;
1046 my $done = 0;
1047 my $sql;
1048 my $res;
1050 # check whether this message should be processed here
1051 if ($error == 0) {
1052 $header = @{$msg_hash->{'header'}}[0];
1053 $target = @{$msg_hash->{'target'}}[0];
1054 $source = @{$msg_hash->{'source'}}[0];
1055 my $not_found_in_known_clients_db = 0;
1056 my $not_found_in_known_server_db = 0;
1057 my $not_found_in_foreign_clients_db = 0;
1058 my $local_address;
1059 my ($target_ip, $target_port) = split(':', $target);
1060 if ($target =~ /^\d+\.\d+\.\d+\.\d+:\d+$/) {
1061 $local_address = &get_local_ip_for_remote_ip($target_ip).":$server_port";
1062 } else {
1063 $local_address = $server_address;
1064 }
1066 # target and source is equal to GOSA -> process here
1067 if (not $done) {
1068 if ($target eq "GOSA" && $source eq "GOSA") {
1069 $done = 1;
1070 }
1071 }
1073 # target is own address without forward_to_gosa-tag -> process here
1074 if (not $done) {
1075 if (($target eq $local_address) && (not exists $msg_hash->{'forward_to_gosa'})) {
1076 $done = 1;
1077 if ($source eq "GOSA") {
1078 $msg =~ s/<\/xml>/<forward_to_gosa>$local_address,$session_id<\/forward_to_gosa><\/xml>/;
1079 }
1080 #print STDERR "target is own address without forward_to_gosa-tag -> process here\n";
1081 }
1082 }
1084 # target is a client address in known_clients -> process here
1085 if (not $done) {
1086 $sql = "SELECT * FROM $known_clients_tn WHERE (hostname='$target' OR macaddress LIKE '$target')";
1087 $res = $known_clients_db->select_dbentry($sql);
1088 if (keys(%$res) > 0) {
1089 $done = 1;
1090 my $hostname = $res->{1}->{'hostname'};
1091 $msg =~ s/<target>$target<\/target>/<target>$hostname<\/target>/;
1092 #print STDERR "target is a client address in known_clients -> process here\n";
1093 my $local_address = &get_local_ip_for_remote_ip($target_ip).":$server_port";
1094 if ($source eq "GOSA") {
1095 $msg =~ s/<\/xml>/<forward_to_gosa>$local_address,$session_id<\/forward_to_gosa><\/xml>/;
1096 }
1098 } else {
1099 $not_found_in_known_clients_db = 1;
1100 }
1101 }
1103 # target ist own address with forward_to_gosa-tag not pointing to myself -> process here
1104 if (not $done) {
1105 my $forward_to_gosa = @{$msg_hash->{'forward_to_gosa'}}[0];
1106 my $gosa_at;
1107 my $gosa_session_id;
1108 if (($target eq $local_address) && (defined $forward_to_gosa)){
1109 my ($gosa_at, $gosa_session_id) = split(/,/, $forward_to_gosa);
1110 if ($gosa_at ne $local_address) {
1111 $done = 1;
1112 #print STDERR "target is own address with forward_to_gosa-tag not pointing to myself -> process here\n";
1113 }
1114 }
1115 }
1117 # if message should be processed here -> add message to incoming_db
1118 if ($done) {
1119 # if a job or a gosa message comes from a foreign server, fake module to GosaPackages
1120 # so gosa-si-server knows how to process this kind of messages
1121 if ($header =~ /^gosa_/ || $header =~ /^job_/) {
1122 $module = "GosaPackages";
1123 }
1125 my $res = $incoming_db->add_dbentry( {table=>$incoming_tn,
1126 primkey=>[],
1127 headertag=>$header,
1128 targettag=>$target,
1129 xmlmessage=>&encode_base64($msg),
1130 timestamp=>&get_time,
1131 module=>$module,
1132 sessionid=>$session_id,
1133 } );
1134 }
1136 # target is own address with forward_to_gosa-tag pointing at myself -> forward to gosa
1137 if (not $done) {
1138 my $forward_to_gosa = @{$msg_hash->{'forward_to_gosa'}}[0];
1139 my $gosa_at;
1140 my $gosa_session_id;
1141 if (($target eq $local_address) && (defined $forward_to_gosa)){
1142 my ($gosa_at, $gosa_session_id) = split(/,/, $forward_to_gosa);
1143 if ($gosa_at eq $local_address) {
1144 my $session_reference = $kernel->ID_id_to_session($gosa_session_id);
1145 if( defined $session_reference ) {
1146 $heap = $session_reference->get_heap();
1147 }
1148 if(exists $heap->{'client'}) {
1149 $msg = &encrypt_msg($msg, $GosaPackages_key);
1150 $heap->{'client'}->put($msg);
1151 &daemon_log("$session_id INFO: incoming '$header' message forwarded to GOsa", 5);
1152 }
1153 $done = 1;
1154 #print STDERR "target is own address with forward_to_gosa-tag pointing at myself -> forward to gosa\n";
1155 }
1156 }
1158 }
1160 # target is a client address in foreign_clients -> forward to registration server
1161 if (not $done) {
1162 $sql = "SELECT * FROM $foreign_clients_tn WHERE (hostname='$target' OR macaddress LIKE '$target')";
1163 $res = $foreign_clients_db->select_dbentry($sql);
1164 if (keys(%$res) > 0) {
1165 my $hostname = $res->{1}->{'hostname'};
1166 my ($host_ip, $host_port) = split(/:/, $hostname);
1167 my $local_address = &get_local_ip_for_remote_ip($host_ip).":$server_port";
1168 my $regserver = $res->{1}->{'regserver'};
1169 my $sql = "SELECT * FROM $known_server_tn WHERE hostname='$regserver'";
1170 my $res = $known_server_db->select_dbentry($sql);
1171 if (keys(%$res) > 0) {
1172 my $regserver_key = $res->{1}->{'hostkey'};
1173 $msg =~ s/<source>GOSA<\/source>/<source>$local_address<\/source>/;
1174 $msg =~ s/<target>$target<\/target>/<target>$hostname<\/target>/;
1175 if ($source eq "GOSA") {
1176 $msg =~ s/<\/xml>/<forward_to_gosa>$local_address,$session_id<\/forward_to_gosa><\/xml>/;
1177 }
1178 &send_msg_to_target($msg, $regserver, $regserver_key, $header, $session_id);
1179 }
1180 $done = 1;
1181 #print STDERR "target is a client address in foreign_clients -> forward to registration server\n";
1182 } else {
1183 $not_found_in_foreign_clients_db = 1;
1184 }
1185 }
1187 # target is a server address -> forward to server
1188 if (not $done) {
1189 $sql = "SELECT * FROM $known_server_tn WHERE hostname='$target'";
1190 $res = $known_server_db->select_dbentry($sql);
1191 if (keys(%$res) > 0) {
1192 my $hostkey = $res->{1}->{'hostkey'};
1194 if ($source eq "GOSA") {
1195 $msg =~ s/<source>GOSA<\/source>/<source>$local_address<\/source>/;
1196 $msg =~ s/<\/xml>/<forward_to_gosa>$local_address,$session_id<\/forward_to_gosa><\/xml>/;
1198 }
1200 &send_msg_to_target($msg, $target, $hostkey, $header, $session_id);
1201 $done = 1;
1202 #print STDERR "target is a server address -> forward to server\n";
1203 } else {
1204 $not_found_in_known_server_db = 1;
1205 }
1206 }
1209 # target is not in foreign_clients_db, known_server_db or known_clients_db, maybe it is a complete new one -> process here
1210 if ( $not_found_in_foreign_clients_db
1211 && $not_found_in_known_server_db
1212 && $not_found_in_known_clients_db) {
1213 my $res = $incoming_db->add_dbentry( {table=>$incoming_tn,
1214 primkey=>[],
1215 headertag=>$header,
1216 targettag=>$target,
1217 xmlmessage=>&encode_base64($msg),
1218 timestamp=>&get_time,
1219 module=>$module,
1220 sessionid=>$session_id,
1221 } );
1222 $done = 1;
1223 }
1226 if (not $done) {
1227 daemon_log("$session_id ERROR: do not know what to do with this message: $msg", 1);
1228 if ($source eq "GOSA") {
1229 my %data = ('error_msg' => &encode_base64($msg), 'error_string' => "Do not know what to do with this message!");
1230 my $error_msg = &build_msg("error", $local_address, "GOSA", \%data );
1232 my $session_reference = $kernel->ID_id_to_session($session_id);
1233 if( defined $session_reference ) {
1234 $heap = $session_reference->get_heap();
1235 }
1236 if(exists $heap->{'client'}) {
1237 $error_msg = &encrypt_msg($error_msg, $GosaPackages_key);
1238 $heap->{'client'}->put($error_msg);
1239 }
1240 }
1241 }
1243 }
1245 return;
1246 }
1249 sub next_task {
1250 my ($session, $heap, $task) = @_[SESSION, HEAP, ARG0];
1251 my $running_task = POE::Wheel::Run->new(
1252 Program => sub { process_task($session, $heap, $task) },
1253 StdioFilter => POE::Filter::Reference->new(),
1254 StdoutEvent => "task_result",
1255 StderrEvent => "task_debug",
1256 CloseEvent => "task_done",
1257 );
1258 $heap->{task}->{ $running_task->ID } = $running_task;
1259 }
1261 sub handle_task_result {
1262 my ($kernel, $heap, $result) = @_[KERNEL, HEAP, ARG0];
1263 my $client_answer = $result->{'answer'};
1264 if( $client_answer =~ s/session_id=(\d+)$// ) {
1265 my $session_id = $1;
1266 if( defined $session_id ) {
1267 my $session_reference = $kernel->ID_id_to_session($session_id);
1268 if( defined $session_reference ) {
1269 $heap = $session_reference->get_heap();
1270 }
1271 }
1273 if(exists $heap->{'client'}) {
1274 $heap->{'client'}->put($client_answer);
1275 }
1276 }
1277 $kernel->sig(CHLD => "child_reap");
1278 }
1280 sub handle_task_debug {
1281 my $result = $_[ARG0];
1282 print STDERR "$result\n";
1283 }
1285 sub handle_task_done {
1286 my ( $kernel, $heap, $task_id ) = @_[ KERNEL, HEAP, ARG0 ];
1287 delete $heap->{task}->{$task_id};
1288 }
1290 sub process_task {
1291 no strict "refs";
1292 #CHECK: Not @_[...]?
1293 my ($session, $heap, $task) = @_;
1294 my $error = 0;
1295 my $answer_l;
1296 my ($answer_header, @answer_target_l, $answer_source);
1297 my $client_answer = "";
1299 # prepare all variables needed to process message
1300 #my $msg = $task->{'xmlmessage'};
1301 my $msg = &decode_base64($task->{'xmlmessage'});
1302 my $incoming_id = $task->{'id'};
1303 my $module = $task->{'module'};
1304 my $header = $task->{'headertag'};
1305 my $session_id = $task->{'sessionid'};
1306 my $msg_hash = $xml->XMLin($msg, ForceArray=>1);
1307 my $source = @{$msg_hash->{'source'}}[0];
1309 # set timestamp of incoming client uptodate, so client will not
1310 # be deleted from known_clients because of expiration
1311 my $act_time = &get_time();
1312 my $sql = "UPDATE $known_clients_tn SET timestamp='$act_time' WHERE hostname='$source'";
1313 my $res = $known_clients_db->exec_statement($sql);
1315 ######################
1316 # process incoming msg
1317 if( $error == 0) {
1318 daemon_log("$session_id INFO: Incoming msg (session_id=$session_id) with header '".@{$msg_hash->{'header'}}[0]."'", 5);
1319 daemon_log("$session_id DEBUG: Processing module ".$module, 7);
1320 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $session_id);
1322 if ( 0 < @{$answer_l} ) {
1323 my $answer_str = join("\n", @{$answer_l});
1324 while ($answer_str =~ /<header>(\w+)<\/header>/g) {
1325 daemon_log("$session_id INFO: got answer message with header '$1'", 5);
1326 }
1327 daemon_log("$session_id DEBUG: $module: got answer from module: \n".$answer_str,8);
1328 } else {
1329 daemon_log("$session_id DEBUG: $module: got no answer from module!" ,8);
1330 }
1332 }
1333 if( !$answer_l ) { $error++ };
1335 ########
1336 # answer
1337 if( $error == 0 ) {
1339 foreach my $answer ( @{$answer_l} ) {
1340 # check outgoing msg to xml validity
1341 my $answer_hash = &check_outgoing_xml_validity($answer, $session_id);
1342 if( not defined $answer_hash ) { next; }
1344 $answer_header = @{$answer_hash->{'header'}}[0];
1345 @answer_target_l = @{$answer_hash->{'target'}};
1346 $answer_source = @{$answer_hash->{'source'}}[0];
1348 # deliver msg to all targets
1349 foreach my $answer_target ( @answer_target_l ) {
1351 # targets of msg are all gosa-si-clients in known_clients_db
1352 if( $answer_target eq "*" ) {
1353 # answer is for all clients
1354 my $sql_statement= "SELECT * FROM known_clients";
1355 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
1356 while( my ($hit_num, $hit) = each %{ $query_res } ) {
1357 my $host_name = $hit->{hostname};
1358 my $host_key = $hit->{hostkey};
1359 my $error = &send_msg_to_target($answer, $host_name, $host_key, $answer_header, $session_id);
1360 &update_jobdb_status_for_send_msgs($answer, $error);
1361 }
1362 }
1364 # targets of msg are all gosa-si-server in known_server_db
1365 elsif( $answer_target eq "KNOWN_SERVER" ) {
1366 # answer is for all server in known_server
1367 my $sql_statement= "SELECT * FROM $known_server_tn";
1368 my $query_res = $known_server_db->select_dbentry( $sql_statement );
1369 while( my ($hit_num, $hit) = each %{ $query_res } ) {
1370 my $host_name = $hit->{hostname};
1371 my $host_key = $hit->{hostkey};
1372 $answer =~ s/<target>\S+<\/target>/<target>$host_name<\/target>/g;
1373 my $error = &send_msg_to_target($answer, $host_name, $host_key, $answer_header, $session_id);
1374 &update_jobdb_status_for_send_msgs($answer, $error);
1375 }
1376 }
1378 # target of msg is GOsa
1379 elsif( $answer_target eq "GOSA" ) {
1380 my $session_id = ($1) if $answer =~ /<session_id>(\d+?)<\/session_id>/;
1381 my $add_on = "";
1382 if( defined $session_id ) {
1383 $add_on = ".session_id=$session_id";
1384 }
1385 # answer is for GOSA and has to returned to connected client
1386 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
1387 $client_answer = $gosa_answer.$add_on;
1388 }
1390 # target of msg is job queue at this host
1391 elsif( $answer_target eq "JOBDB") {
1392 $answer =~ /<header>(\S+)<\/header>/;
1393 my $header;
1394 if( defined $1 ) { $header = $1; }
1395 my $error = &send_msg_to_target($answer, $server_address, $GosaPackages_key, $header, $session_id);
1396 &update_jobdb_status_for_send_msgs($answer, $error);
1397 }
1399 # target of msg is a mac address
1400 elsif( $answer_target =~ /^([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})$/i ) {
1401 daemon_log("$session_id INFO: target is mac address '$answer_target', looking for host in known_clients", 5);
1402 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress LIKE '$answer_target'";
1403 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
1404 my $found_ip_flag = 0;
1405 while( my ($hit_num, $hit) = each %{ $query_res } ) {
1406 my $host_name = $hit->{hostname};
1407 my $host_key = $hit->{hostkey};
1408 $answer =~ s/$answer_target/$host_name/g;
1409 daemon_log("$session_id INFO: found host '$host_name', associated to '$answer_target'", 5);
1410 my $error = &send_msg_to_target($answer, $host_name, $host_key, $answer_header, $session_id);
1411 &update_jobdb_status_for_send_msgs($answer, $error);
1412 $found_ip_flag++ ;
1413 }
1414 if( $found_ip_flag == 0) {
1415 daemon_log("$session_id WARNING: no host found in known_clients with mac address '$answer_target'", 3);
1416 }
1418 # answer is for one specific host
1419 } else {
1420 # get encrypt_key
1421 my $encrypt_key = &get_encrypt_key($answer_target);
1422 if( not defined $encrypt_key ) {
1423 # unknown target
1424 daemon_log("$session_id WARNING: unknown target '$answer_target'", 3);
1425 next;
1426 }
1427 my $error = &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header,$session_id);
1428 &update_jobdb_status_for_send_msgs($answer, $error);
1429 }
1430 }
1431 }
1432 }
1434 my $filter = POE::Filter::Reference->new();
1435 my %result = (
1436 status => "seems ok to me",
1437 answer => $client_answer,
1438 );
1440 my $output = $filter->put( [ \%result ] );
1441 print @$output;
1444 }
1446 sub session_start {
1447 my ($kernel) = $_[KERNEL];
1448 $global_kernel = $kernel;
1449 $kernel->yield('register_at_foreign_servers');
1450 $kernel->yield('create_fai_server_db', $fai_server_tn );
1451 $kernel->yield('create_fai_release_db', $fai_release_tn );
1452 $kernel->yield('watch_for_next_tasks');
1453 $kernel->sig(USR1 => "sig_handler");
1454 $kernel->sig(USR2 => "recreate_packages_db");
1455 $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
1456 $kernel->delay_set('watch_for_done_jobs', $job_queue_loop_delay);
1457 $kernel->delay_set('watch_for_modified_jobs', $modified_jobs_loop_delay);
1458 $kernel->delay_set('watch_for_new_messages', $messaging_db_loop_delay);
1459 $kernel->delay_set('watch_for_delivery_messages', $messaging_db_loop_delay);
1460 $kernel->delay_set('watch_for_done_messages', $messaging_db_loop_delay);
1461 $kernel->delay_set('watch_for_old_known_clients', $job_queue_loop_delay);
1463 # Start opsi check
1464 if ($opsi_enabled eq "true") {
1465 $kernel->delay_set('watch_for_opsi_jobs', $job_queue_opsi_delay);
1466 }
1468 }
1471 sub watch_for_done_jobs {
1472 #CHECK: $heap for what?
1473 my ($kernel,$heap) = @_[KERNEL, HEAP];
1475 my $sql_statement = "SELECT * FROM ".$job_queue_tn." WHERE ((status='done') AND (modified='0'))";
1476 my $res = $job_db->select_dbentry( $sql_statement );
1478 while( my ($id, $hit) = each %{$res} ) {
1479 my $jobdb_id = $hit->{id};
1480 my $sql_statement = "DELETE FROM $job_queue_tn WHERE id=$jobdb_id";
1481 my $res = $job_db->del_dbentry($sql_statement);
1482 }
1484 $kernel->delay_set('watch_for_done_jobs',$job_queue_loop_delay);
1485 }
1488 sub watch_for_opsi_jobs {
1489 my ($kernel) = $_[KERNEL];
1491 # This is not very nice to look for opsi install jobs, but headertag has to be trigger_action_reinstall. The only way to identify a
1492 # opsi install job is to parse the xml message. There is still the correct header.
1493 my $sql_statement = "SELECT * FROM ".$job_queue_tn." WHERE ((xmlmessage LIKE '%opsi_install_client</header>%') AND (status='processing'))";
1494 my $res = $job_db->select_dbentry( $sql_statement );
1496 # Ask OPSI for an update of the running jobs
1497 while (my ($id, $hit) = each %$res ) {
1498 # Determine current parameters of the job
1499 my $hostId = $hit->{'plainname'};
1500 my $macaddress = $hit->{'macaddress'};
1501 my $progress = $hit->{'progress'};
1503 my $result= {};
1505 # For hosts, only return the products that are or get installed
1506 my $callobj;
1507 $callobj = {
1508 method => 'getProductStates_hash',
1509 params => [ $hostId ],
1510 id => 1,
1511 };
1513 my $hres = $opsi_client->call($opsi_url, $callobj);
1514 my ($hres_err, $hres_err_string) = &check_opsi_res($hres);
1515 if (&check_opsi_res($hres)) {
1516 my $htmp= $hres->result->{$hostId};
1518 # check state != not_installed or action == setup -> load and add
1519 my $products= 0;
1520 my $installed= 0;
1521 my $installing = 0;
1522 my $error= 0;
1523 my @installed_list;
1524 my @error_list;
1525 my $act_status = "none";
1526 foreach my $product (@{$htmp}){
1528 if ($product->{'installationStatus'} ne "not_installed" or
1529 $product->{'actionRequest'} eq "setup"){
1531 # Increase number of products for this host
1532 $products++;
1534 if ($product->{'installationStatus'} eq "failed"){
1535 $result->{$product->{'productId'}}= "error";
1536 unshift(@error_list, $product->{'productId'});
1537 $error++;
1538 }
1539 if ($product->{'installationStatus'} eq "installed" && $product->{'actionRequest'} eq "none"){
1540 $result->{$product->{'productId'}}= "installed";
1541 unshift(@installed_list, $product->{'productId'});
1542 $installed++;
1543 }
1544 if ($product->{'installationStatus'} eq "installing"){
1545 $result->{$product->{'productId'}}= "installing";
1546 $installing++;
1547 $act_status = "installing - ".$product->{'productId'};
1548 }
1549 }
1550 }
1552 # Estimate "rough" progress
1553 $result->{'progress'}= int($installed * 100 / $products);
1555 # Set updates in job queue
1556 if ((not $error) && (not $installing) && ($installed)) {
1557 $act_status = "installed - ".join(", ", @installed_list);
1558 }
1559 if ($error) {
1560 $act_status = "error - ".join(", ", @error_list);
1561 }
1562 if ($progress ne $result->{'progress'} ) {
1563 # Updating progress and result
1564 my $update_statement = "UPDATE $job_queue_tn SET modified='1', ";
1565 $update_statement .= "progress='".$result->{'progress'}."', result='$act_status' WHERE macaddress='$macaddress'";
1566 my $update_res = $job_db->update_dbentry($update_statement);
1567 }
1568 if ($progress eq 100) {
1569 # Updateing status
1570 my $done_statement = "UPDATE $job_queue_tn SET modified='1', ";
1571 if ($error) {
1572 $done_statement .= "status='error'";
1573 } else {
1574 $done_statement .= "status='done'";
1575 }
1576 $done_statement .= " WHERE macaddress='$macaddress'";
1577 my $done_res = $job_db->update_dbentry($done_statement);
1578 }
1581 }
1582 }
1584 $kernel->delay_set('watch_for_opsi_jobs', $job_queue_opsi_delay);
1585 }
1588 # if a job got an update or was modified anyway, send to all other si-server an update message
1589 # of this jobs
1590 sub watch_for_modified_jobs {
1591 my ($kernel,$heap) = @_[KERNEL, HEAP];
1593 my $sql_statement = "SELECT * FROM $job_queue_tn WHERE ((siserver='localhost') AND (modified='1'))";
1594 my $res = $job_db->select_dbentry( $sql_statement );
1596 # if db contains no jobs which should be update, do nothing
1597 if (keys %$res != 0) {
1599 if ($job_synchronization eq "true") {
1600 # make out of the db result a gosa-si message
1601 my $update_msg = &db_res2si_msg ($res, "foreign_job_updates", "KNOWN_SERVER", "MY_LOCAL_ADDRESS");
1603 # update all other SI-server
1604 &inform_all_other_si_server($update_msg);
1605 }
1607 # set jobs all jobs to modified = 0, wait until the next modification for updates of other si-server
1608 $sql_statement = "UPDATE $job_queue_tn SET modified='0' ";
1609 $res = $job_db->update_dbentry($sql_statement);
1610 }
1612 $kernel->delay_set('watch_for_modified_jobs', $modified_jobs_loop_delay);
1613 }
1616 sub watch_for_new_jobs {
1617 if($watch_for_new_jobs_in_progress == 0) {
1618 $watch_for_new_jobs_in_progress = 1;
1619 my ($kernel,$heap) = @_[KERNEL, HEAP];
1621 # check gosa job quaeue for jobs with executable timestamp
1622 my $timestamp = &get_time();
1623 my $sql_statement = "SELECT * FROM $job_queue_tn WHERE status='waiting' AND (CAST (timestamp AS INTEGER)) < $timestamp ORDER BY timestamp";
1624 my $res = $job_db->exec_statement( $sql_statement );
1626 # Merge all new jobs that would do the same actions
1627 my @drops;
1628 my $hits;
1629 foreach my $hit (reverse @{$res} ) {
1630 my $macaddress= lc @{$hit}[8];
1631 my $headertag= @{$hit}[5];
1632 if(
1633 defined($hits->{$macaddress}) &&
1634 defined($hits->{$macaddress}->{$headertag}) &&
1635 defined($hits->{$macaddress}->{$headertag}[0])
1636 ) {
1637 push @drops, "DELETE FROM $job_queue_tn WHERE id = $hits->{$macaddress}->{$headertag}[0]";
1638 }
1639 $hits->{$macaddress}->{$headertag}= $hit;
1640 }
1642 # Delete new jobs with a matching job in state 'processing'
1643 foreach my $macaddress (keys %{$hits}) {
1644 foreach my $jobdb_headertag (keys %{$hits->{$macaddress}}) {
1645 my $jobdb_id = @{$hits->{$macaddress}->{$jobdb_headertag}}[0];
1646 if(defined($jobdb_id)) {
1647 my $sql_statement = "SELECT * FROM $job_queue_tn WHERE macaddress LIKE '$macaddress' AND headertag='$jobdb_headertag' AND status='processing'";
1648 my $res = $job_db->exec_statement( $sql_statement );
1649 foreach my $hit (@{$res}) {
1650 push @drops, "DELETE FROM $job_queue_tn WHERE id=$jobdb_id";
1651 }
1652 } else {
1653 daemon_log("J ERROR: Job without id exists for macaddress $macaddress!", 1);
1654 }
1655 }
1656 }
1658 # Commit deletion
1659 $job_db->exec_statementlist(\@drops);
1661 # Look for new jobs that could be executed
1662 foreach my $macaddress (keys %{$hits}) {
1664 # Look if there is an executing job
1665 my $sql_statement = "SELECT * FROM $job_queue_tn WHERE macaddress LIKE '$macaddress' AND status='processing'";
1666 my $res = $job_db->exec_statement( $sql_statement );
1668 # Skip new jobs for host if there is a processing job
1669 if(defined($res) and defined @{$res}[0]) {
1670 next;
1671 }
1673 foreach my $jobdb_headertag (keys %{$hits->{$macaddress}}) {
1674 my $jobdb_id = @{$hits->{$macaddress}->{$jobdb_headertag}}[0];
1675 if(defined($jobdb_id)) {
1676 my $job_msg = @{$hits->{$macaddress}->{$jobdb_headertag}}[7];
1678 daemon_log("J DEBUG: its time to execute $job_msg", 7);
1679 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress LIKE '$macaddress'";
1680 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
1682 # expect macaddress is unique!!!!!!
1683 my $target = $res_hash->{1}->{hostname};
1685 # change header
1686 $job_msg =~ s/<header>job_/<header>gosa_/;
1688 # add sqlite_id
1689 $job_msg =~ s/<\/xml>$/<jobdb_id>$jobdb_id<\/jobdb_id><\/xml>/;
1691 $job_msg =~ /<header>(\S+)<\/header>/;
1692 my $header = $1 ;
1693 my $func_error = &send_msg_to_target($job_msg, $server_address, $GosaPackages_key, $header, "J");
1695 # update status in job queue to 'processing'
1696 $sql_statement = "UPDATE $job_queue_tn SET status='processing' WHERE id=$jobdb_id";
1697 my $res = $job_db->update_dbentry($sql_statement);
1698 # TODO: abfangen ob alles in ordnung ist oder nicht, wenn nicht error schmeißen
1700 # We don't want parallel processing
1701 last;
1702 }
1703 }
1704 }
1706 $watch_for_new_jobs_in_progress = 0;
1707 $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
1708 }
1709 }
1712 sub watch_for_new_messages {
1713 my ($kernel,$heap) = @_[KERNEL, HEAP];
1714 my @coll_user_msg; # collection list of outgoing messages
1716 # check messaging_db for new incoming messages with executable timestamp
1717 my $timestamp = &get_time();
1718 my $sql_statement = "SELECT * FROM $messaging_tn WHERE ( (CAST(timestamp AS INTEGER))<$timestamp AND flag='n' AND direction='in' )";
1719 my $res = $messaging_db->exec_statement( $sql_statement );
1720 foreach my $hit (@{$res}) {
1722 # create outgoing messages
1723 my $message_to = @{$hit}[3];
1724 # translate message_to to plain login name
1725 my @message_to_l = split(/,/, $message_to);
1726 my %receiver_h;
1727 foreach my $receiver (@message_to_l) {
1728 if ($receiver =~ /^u_([\s\S]*)$/) {
1729 $receiver_h{$1} = 0;
1730 } elsif ($receiver =~ /^g_([\s\S]*)$/) {
1731 my $group_name = $1;
1732 # fetch all group members from ldap and add them to receiver hash
1733 my $ldap_handle = &get_ldap_handle();
1734 if (defined $ldap_handle) {
1735 my $mesg = $ldap_handle->search(
1736 base => $ldap_base,
1737 scope => 'sub',
1738 attrs => ['memberUid'],
1739 filter => "cn=$group_name",
1740 );
1741 if ($mesg->count) {
1742 my @entries = $mesg->entries;
1743 foreach my $entry (@entries) {
1744 my @receivers= $entry->get_value("memberUid");
1745 foreach my $receiver (@receivers) {
1746 $receiver_h{$1} = 0;
1747 }
1748 }
1749 }
1750 # translating errors ?
1751 if ($mesg->code) {
1752 daemon_log("M ERROR: unable to translate group '$group_name' to user list for message delivery: $mesg->error", 1);
1753 }
1754 # ldap handle error ?
1755 } else {
1756 daemon_log("M ERROR: unable to translate group '$group_name' to user list for message delivery: no ldap handle available", 1);
1757 }
1758 } else {
1759 my $sbjct = &encode_base64(@{$hit}[1]);
1760 my $msg = &encode_base64(@{$hit}[7]);
1761 &daemon_log("M WARNING: unknown receiver '$receiver' for a user-message '$sbjct - $msg'", 3);
1762 }
1763 }
1764 my @receiver_l = keys(%receiver_h);
1766 my $message_id = @{$hit}[0];
1768 #add each outgoing msg to messaging_db
1769 my $receiver;
1770 foreach $receiver (@receiver_l) {
1771 my $sql_statement = "INSERT INTO $messaging_tn (id, subject, message_from, message_to, flag, direction, delivery_time, message, timestamp) ".
1772 "VALUES ('".
1773 $message_id."', '". # id
1774 @{$hit}[1]."', '". # subject
1775 @{$hit}[2]."', '". # message_from
1776 $receiver."', '". # message_to
1777 "none"."', '". # flag
1778 "out"."', '". # direction
1779 @{$hit}[6]."', '". # delivery_time
1780 @{$hit}[7]."', '". # message
1781 $timestamp."'". # timestamp
1782 ")";
1783 &daemon_log("M DEBUG: $sql_statement", 1);
1784 my $res = $messaging_db->exec_statement($sql_statement);
1785 &daemon_log("M INFO: message '".@{$hit}[0]."' is prepared for delivery to receiver '$receiver'", 5);
1786 }
1788 # set incoming message to flag d=deliverd
1789 $sql_statement = "UPDATE $messaging_tn SET flag='p' WHERE id='$message_id'";
1790 &daemon_log("M DEBUG: $sql_statement", 7);
1791 $res = $messaging_db->update_dbentry($sql_statement);
1792 &daemon_log("M INFO: message '$message_id' is set to flag 'p' (processed)", 5);
1793 }
1795 $kernel->delay_set('watch_for_new_messages', $messaging_db_loop_delay);
1796 return;
1797 }
1799 sub watch_for_delivery_messages {
1800 my ($kernel, $heap) = @_[KERNEL, HEAP];
1802 # select outgoing messages
1803 my $sql_statement = "SELECT * FROM $messaging_tn WHERE ( flag='p' AND direction='out' )";
1804 #&daemon_log("0 DEBUG: $sql", 7);
1805 my $res = $messaging_db->exec_statement( $sql_statement );
1807 # build out msg for each usr
1808 foreach my $hit (@{$res}) {
1809 my $receiver = @{$hit}[3];
1810 my $msg_id = @{$hit}[0];
1811 my $subject = @{$hit}[1];
1812 my $message = @{$hit}[7];
1814 # resolve usr -> host where usr is logged in
1815 my $sql = "SELECT * FROM $login_users_tn WHERE (user='$receiver')";
1816 #&daemon_log("0 DEBUG: $sql", 7);
1817 my $res = $login_users_db->exec_statement($sql);
1819 # reciver is logged in nowhere
1820 if (not ref(@$res[0]) eq "ARRAY") { next; }
1822 my $send_succeed = 0;
1823 foreach my $hit (@$res) {
1824 my $receiver_host = @$hit[0];
1825 &daemon_log("M DEBUG: user '$receiver' is logged in at host '$receiver_host'", 7);
1827 # fetch key to encrypt msg propperly for usr/host
1828 my $sql = "SELECT * FROM $known_clients_tn WHERE (hostname='$receiver_host')";
1829 &daemon_log("0 DEBUG: $sql", 7);
1830 my $res = $known_clients_db->exec_statement($sql);
1832 # host is already down
1833 if (not ref(@$res[0]) eq "ARRAY") { next; }
1835 # host is on
1836 my $receiver_key = @{@{$res}[0]}[2];
1837 my %data = ('subject' => $subject, 'message' => $message, 'usr' => $receiver);
1838 my $out_msg = &build_msg("usr_msg", $server_address, $receiver_host, \%data );
1839 my $error = &send_msg_to_target($out_msg, $receiver_host, $receiver_key, "usr_msg", 0);
1840 if ($error == 0 ) {
1841 $send_succeed++ ;
1842 }
1843 }
1845 if ($send_succeed) {
1846 # set outgoing msg at db to deliverd
1847 my $sql = "UPDATE $messaging_tn SET flag='d' WHERE (id='$msg_id' AND direction='out' AND message_to='$receiver')";
1848 &daemon_log("0 DEBUG: $sql", 7);
1849 my $res = $messaging_db->exec_statement($sql);
1850 }
1851 }
1853 $kernel->delay_set('watch_for_delivery_messages', $messaging_db_loop_delay);
1854 return;
1855 }
1858 sub watch_for_done_messages {
1859 my ($kernel,$heap) = @_[KERNEL, HEAP];
1861 my $sql = "SELECT * FROM $messaging_tn WHERE (flag='p' AND direction='in')";
1862 #&daemon_log("0 DEBUG: $sql", 7);
1863 my $res = $messaging_db->exec_statement($sql);
1865 foreach my $hit (@{$res}) {
1866 my $msg_id = @{$hit}[0];
1868 my $sql = "SELECT * FROM $messaging_tn WHERE (id='$msg_id' AND direction='out' AND (NOT flag='s'))";
1869 #&daemon_log("0 DEBUG: $sql", 7);
1870 my $res = $messaging_db->exec_statement($sql);
1872 # not all usr msgs have been seen till now
1873 if ( ref(@$res[0]) eq "ARRAY") { next; }
1875 $sql = "DELETE FROM $messaging_tn WHERE (id='$msg_id')";
1876 #&daemon_log("0 DEBUG: $sql", 7);
1877 $res = $messaging_db->exec_statement($sql);
1879 }
1881 $kernel->delay_set('watch_for_done_messages', $messaging_db_loop_delay);
1882 return;
1883 }
1886 sub watch_for_old_known_clients {
1887 my ($kernel,$heap) = @_[KERNEL, HEAP];
1889 my $sql_statement = "SELECT * FROM $known_clients_tn";
1890 my $res = $known_clients_db->select_dbentry( $sql_statement );
1892 my $act_time = int(&get_time());
1894 while ( my ($hit_num, $hit) = each %$res) {
1895 my $expired_timestamp = int($hit->{'timestamp'});
1896 $expired_timestamp =~ /(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/;
1897 my $dt = DateTime->new( year => $1,
1898 month => $2,
1899 day => $3,
1900 hour => $4,
1901 minute => $5,
1902 second => $6,
1903 );
1905 $dt->add( seconds => 2 * int($hit->{'keylifetime'}) );
1906 $expired_timestamp = $dt->ymd('').$dt->hms('')."\n";
1907 if ($act_time > $expired_timestamp) {
1908 my $hostname = $hit->{'hostname'};
1909 my $del_sql = "DELETE FROM $known_clients_tn WHERE hostname='$hostname'";
1910 my $del_res = $known_clients_db->exec_statement($del_sql);
1912 &main::daemon_log("0 INFO: timestamp '".$hit->{'timestamp'}."' of client '$hostname' is expired('$expired_timestamp'), client will be deleted from known_clients_db", 5);
1913 }
1915 }
1917 $kernel->delay_set('watch_for_old_known_clients', $job_queue_loop_delay);
1918 }
1921 sub watch_for_next_tasks {
1922 my ($kernel,$heap) = @_[KERNEL, HEAP];
1924 my $sql = "SELECT * FROM $incoming_tn";
1925 my $res = $incoming_db->select_dbentry($sql);
1927 while ( my ($hit_num, $hit) = each %$res) {
1928 my $headertag = $hit->{'headertag'};
1929 if ($headertag =~ /^answer_(\d+)/) {
1930 # do not start processing, this message is for a still running POE::Wheel
1931 next;
1932 }
1933 my $message_id = $hit->{'id'};
1934 $kernel->yield('next_task', $hit);
1936 my $sql = "DELETE FROM $incoming_tn WHERE id=$message_id";
1937 my $res = $incoming_db->exec_statement($sql);
1938 }
1940 $kernel->delay_set('watch_for_next_tasks', 0.1);
1941 }
1944 sub get_ldap_handle {
1945 my ($session_id) = @_;
1946 my $heap;
1947 my $ldap_handle;
1949 if (not defined $session_id ) { $session_id = 0 };
1950 if ($session_id =~ /[^0-9]*/) { $session_id = 0 };
1952 if ($session_id == 0) {
1953 daemon_log("$session_id DEBUG: get_ldap_handle invoked without a session_id, create a new ldap_handle", 7);
1954 $ldap_handle = Net::LDAP->new( $ldap_uri );
1955 $ldap_handle->bind($ldap_admin_dn, password => $ldap_admin_password) or daemon_log("$session_id ERROR: Bind to LDAP $ldap_uri as $ldap_admin_dn failed!");
1957 } else {
1958 my $session_reference = $global_kernel->ID_id_to_session($session_id);
1959 if( defined $session_reference ) {
1960 $heap = $session_reference->get_heap();
1961 }
1963 if (not defined $heap) {
1964 daemon_log("$session_id DEBUG: cannot get heap for session_id '$session_id'", 7);
1965 return;
1966 }
1968 # TODO: This "if" is nonsense, because it doesn't prove that the
1969 # used handle is still valid - or if we've to reconnect...
1970 #if (not exists $heap->{ldap_handle}) {
1971 $ldap_handle = Net::LDAP->new( $ldap_uri );
1972 $ldap_handle->bind($ldap_admin_dn, password => $ldap_admin_password) or daemon_log("$session_id ERROR: Bind to LDAP $ldap_uri as $ldap_admin_dn failed!");
1973 $heap->{ldap_handle} = $ldap_handle;
1974 #}
1975 }
1976 return $ldap_handle;
1977 }
1980 sub change_fai_state {
1981 my ($st, $targets, $session_id) = @_;
1982 $session_id = 0 if not defined $session_id;
1983 # Set FAI state to localboot
1984 my %mapActions= (
1985 reboot => '',
1986 update => 'softupdate',
1987 localboot => 'localboot',
1988 reinstall => 'install',
1989 rescan => '',
1990 wake => '',
1991 memcheck => 'memcheck',
1992 sysinfo => 'sysinfo',
1993 install => 'install',
1994 );
1996 # Return if this is unknown
1997 if (!exists $mapActions{ $st }){
1998 daemon_log("$session_id ERROR: unknown action '$st', can not translate ot FAIstate", 1);
1999 return;
2000 }
2002 my $state= $mapActions{ $st };
2004 my $ldap_handle = &get_ldap_handle($session_id);
2005 if( defined($ldap_handle) ) {
2007 # Build search filter for hosts
2008 my $search= "(&(objectClass=GOhard)";
2009 foreach (@{$targets}){
2010 $search.= "(macAddress=$_)";
2011 }
2012 $search.= ")";
2014 # If there's any host inside of the search string, procress them
2015 if (!($search =~ /macAddress/)){
2016 daemon_log("$session_id ERROR: no macAddress found in filter statement for LDAP search: '$search'", 1);
2017 return;
2018 }
2020 # Perform search for Unit Tag
2021 my $mesg = $ldap_handle->search(
2022 base => $ldap_base,
2023 scope => 'sub',
2024 attrs => ['dn', 'FAIstate', 'objectClass'],
2025 filter => "$search"
2026 );
2028 if ($mesg->count) {
2029 my @entries = $mesg->entries;
2030 if (0 == @entries) {
2031 daemon_log("$session_id ERROR: ldap search failed: ldap_base=$ldap_base, filter=$search", 1);
2032 }
2034 foreach my $entry (@entries) {
2035 # Only modify entry if it is not set to '$state'
2036 if ($entry->get_value("FAIstate") ne "$state"){
2037 daemon_log("$session_id INFO: Setting FAIstate to '$state' for ".$entry->dn, 5);
2038 my $result;
2039 my %tmp = map { $_ => 1 } $entry->get_value("objectClass");
2040 if (exists $tmp{'FAIobject'}){
2041 if ($state eq ''){
2042 $result= $ldap_handle->modify($entry->dn, changes => [
2043 delete => [ FAIstate => [] ] ]);
2044 } else {
2045 $result= $ldap_handle->modify($entry->dn, changes => [
2046 replace => [ FAIstate => $state ] ]);
2047 }
2048 } elsif ($state ne ''){
2049 $result= $ldap_handle->modify($entry->dn, changes => [
2050 add => [ objectClass => 'FAIobject' ],
2051 add => [ FAIstate => $state ] ]);
2052 }
2054 # Errors?
2055 if ($result->code){
2056 daemon_log("$session_id Error: Setting FAIstate to '$state' for ".$entry->dn. "failed: ".$result->error, 1);
2057 }
2058 } else {
2059 daemon_log("$session_id DEBUG FAIstate at host '".$entry->dn."' already at state '$st'", 7);
2060 }
2061 }
2062 } else {
2063 daemon_log("$session_id ERROR: LDAP search failed: ldap_base=$ldap_base, filter=$search", 1);
2064 }
2066 # if no ldap handle defined
2067 } else {
2068 daemon_log("$session_id ERROR: no LDAP handle defined for update FAIstate", 1);
2069 }
2071 return;
2072 }
2075 sub change_goto_state {
2076 my ($st, $targets, $session_id) = @_;
2077 $session_id = 0 if not defined $session_id;
2079 # Switch on or off?
2080 my $state= $st eq 'active' ? 'active': 'locked';
2082 my $ldap_handle = &get_ldap_handle($session_id);
2083 if( defined($ldap_handle) ) {
2085 # Build search filter for hosts
2086 my $search= "(&(objectClass=GOhard)";
2087 foreach (@{$targets}){
2088 $search.= "(macAddress=$_)";
2089 }
2090 $search.= ")";
2092 # If there's any host inside of the search string, procress them
2093 if (!($search =~ /macAddress/)){
2094 return;
2095 }
2097 # Perform search for Unit Tag
2098 my $mesg = $ldap_handle->search(
2099 base => $ldap_base,
2100 scope => 'sub',
2101 attrs => ['dn', 'gotoMode'],
2102 filter => "$search"
2103 );
2105 if ($mesg->count) {
2106 my @entries = $mesg->entries;
2107 foreach my $entry (@entries) {
2109 # Only modify entry if it is not set to '$state'
2110 if ($entry->get_value("gotoMode") ne $state){
2112 daemon_log("$session_id INFO: Setting gotoMode to '$state' for ".$entry->dn, 5);
2113 my $result;
2114 $result= $ldap_handle->modify($entry->dn, changes => [
2115 replace => [ gotoMode => $state ] ]);
2117 # Errors?
2118 if ($result->code){
2119 &daemon_log("$session_id Error: Setting gotoMode to '$state' for ".$entry->dn. "failed: ".$result->error, 1);
2120 }
2122 }
2123 }
2124 } else {
2125 daemon_log("$session_id ERROR: LDAP search failed in function change_goto_state: ldap_base=$ldap_base, filter=$search", 1);
2126 }
2128 }
2129 }
2132 sub run_recreate_packages_db {
2133 my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
2134 my $session_id = $session->ID;
2135 &main::daemon_log("$session_id INFO: Recreating FAI Packages DB ('$fai_release_tn', '$fai_server_tn', '$packages_list_tn')", 5);
2136 $kernel->yield('create_fai_release_db', $fai_release_tn);
2137 $kernel->yield('create_fai_server_db', $fai_server_tn);
2138 return;
2139 }
2142 sub run_create_fai_server_db {
2143 my ($kernel, $session, $heap, $table_name) = @_[KERNEL, SESSION, HEAP, ARG0];
2144 my $session_id = $session->ID;
2145 my $task = POE::Wheel::Run->new(
2146 Program => sub { &create_fai_server_db($table_name,$kernel, undef, $session_id) },
2147 StdoutEvent => "session_run_result",
2148 StderrEvent => "session_run_debug",
2149 CloseEvent => "session_run_done",
2150 );
2152 $heap->{task}->{ $task->ID } = $task;
2153 return;
2154 }
2157 sub create_fai_server_db {
2158 my ($table_name, $kernel, $dont_create_packages_list, $session_id) = @_;
2159 my $result;
2161 if (not defined $session_id) { $session_id = 0; }
2162 my $ldap_handle = &get_ldap_handle();
2163 if(defined($ldap_handle)) {
2164 daemon_log("$session_id INFO: create_fai_server_db: start", 5);
2165 my $mesg= $ldap_handle->search(
2166 base => $ldap_base,
2167 scope => 'sub',
2168 attrs => ['FAIrepository', 'gosaUnitTag'],
2169 filter => "(&(FAIrepository=*)(objectClass=FAIrepositoryServer))",
2170 );
2171 if($mesg->{'resultCode'} == 0 &&
2172 $mesg->count != 0) {
2173 foreach my $entry (@{$mesg->{entries}}) {
2174 if($entry->exists('FAIrepository')) {
2175 # Add an entry for each Repository configured for server
2176 foreach my $repo(@{$entry->get_value('FAIrepository', asref => 1)}) {
2177 my($tmp_url,$tmp_server,$tmp_release,$tmp_sections) = split(/\|/, $repo);
2178 my $tmp_tag= $entry->get_value('gosaUnitTag') || "";
2179 $result= $fai_server_db->add_dbentry( {
2180 table => $table_name,
2181 primkey => ['server', 'release', 'tag'],
2182 server => $tmp_url,
2183 release => $tmp_release,
2184 sections => $tmp_sections,
2185 tag => (length($tmp_tag)>0)?$tmp_tag:"",
2186 } );
2187 }
2188 }
2189 }
2190 }
2191 daemon_log("$session_id INFO: create_fai_server_db: finished", 5);
2193 # TODO: Find a way to post the 'create_packages_list_db' event
2194 if(not defined($dont_create_packages_list)) {
2195 &create_packages_list_db(undef, undef, $session_id);
2196 }
2197 }
2199 $ldap_handle->disconnect;
2200 return $result;
2201 }
2204 sub run_create_fai_release_db {
2205 my ($session, $heap, $table_name) = @_[SESSION, HEAP, ARG0];
2206 my $session_id = $session->ID;
2207 my $task = POE::Wheel::Run->new(
2208 Program => sub { &create_fai_release_db($table_name, $session_id) },
2209 StdoutEvent => "session_run_result",
2210 StderrEvent => "session_run_debug",
2211 CloseEvent => "session_run_done",
2212 );
2214 $heap->{task}->{ $task->ID } = $task;
2215 return;
2216 }
2219 sub create_fai_release_db {
2220 my ($table_name, $session_id) = @_;
2221 my $result;
2223 # used for logging
2224 if (not defined $session_id) { $session_id = 0; }
2226 my $ldap_handle = &get_ldap_handle();
2227 if(defined($ldap_handle)) {
2228 daemon_log("$session_id INFO: create_fai_release_db: start",5);
2229 my $mesg= $ldap_handle->search(
2230 base => $ldap_base,
2231 scope => 'sub',
2232 attrs => [],
2233 filter => "(&(objectClass=organizationalUnit)(ou=fai))",
2234 );
2235 if($mesg->{'resultCode'} == 0 &&
2236 $mesg->count != 0) {
2237 # Walk through all possible FAI container ou's
2238 my @sql_list;
2239 my $timestamp= &get_time();
2240 foreach my $ou (@{$mesg->{entries}}) {
2241 my $tmp_classes= resolve_fai_classes($ou->dn, $ldap_handle, $session_id);
2242 if(defined($tmp_classes) && ref($tmp_classes) eq 'HASH') {
2243 my @tmp_array=get_fai_release_entries($tmp_classes);
2244 if(@tmp_array) {
2245 foreach my $entry (@tmp_array) {
2246 if(defined($entry) && ref($entry) eq 'HASH') {
2247 my $sql=
2248 "INSERT INTO $table_name "
2249 ."(timestamp, release, class, type, state) VALUES ("
2250 .$timestamp.","
2251 ."'".$entry->{'release'}."',"
2252 ."'".$entry->{'class'}."',"
2253 ."'".$entry->{'type'}."',"
2254 ."'".$entry->{'state'}."')";
2255 push @sql_list, $sql;
2256 }
2257 }
2258 }
2259 }
2260 }
2262 daemon_log("$session_id DEBUG: Inserting ".scalar @sql_list." entries to DB",8);
2263 if(@sql_list) {
2264 unshift @sql_list, "VACUUM";
2265 unshift @sql_list, "DELETE FROM $table_name";
2266 $fai_release_db->exec_statementlist(\@sql_list);
2267 }
2268 daemon_log("$session_id DEBUG: Done with inserting",7);
2269 }
2270 daemon_log("$session_id INFO: create_fai_release_db: finished",5);
2271 }
2272 $ldap_handle->disconnect;
2273 return $result;
2274 }
2276 sub get_fai_types {
2277 my $tmp_classes = shift || return undef;
2278 my @result;
2280 foreach my $type(keys %{$tmp_classes}) {
2281 if(defined($tmp_classes->{$type}[0]) && (!($tmp_classes->{$type}[0] =~ /^.*?removed.*?$/))) {
2282 my $entry = {
2283 type => $type,
2284 state => $tmp_classes->{$type}[0],
2285 };
2286 push @result, $entry;
2287 }
2288 }
2290 return @result;
2291 }
2293 sub get_fai_state {
2294 my $result = "";
2295 my $tmp_classes = shift || return $result;
2297 foreach my $type(keys %{$tmp_classes}) {
2298 if(defined($tmp_classes->{$type}[0])) {
2299 $result = $tmp_classes->{$type}[0];
2301 # State is equal for all types in class
2302 last;
2303 }
2304 }
2306 return $result;
2307 }
2309 sub resolve_fai_classes {
2310 my ($fai_base, $ldap_handle, $session_id) = @_;
2311 if (not defined $session_id) { $session_id = 0; }
2312 my $result;
2313 my @possible_fai_classes= ("FAIscript", "FAIhook", "FAIpartitionTable", "FAItemplate", "FAIvariable", "FAIprofile", "FAIpackageList");
2314 my $fai_filter= "(|(&(objectClass=FAIclass)(|(objectClass=".join(")(objectClass=", @possible_fai_classes).")))(objectClass=FAIbranch))";
2315 my $fai_classes;
2317 daemon_log("$session_id DEBUG: Searching for FAI entries in base $fai_base",7);
2318 my $mesg= $ldap_handle->search(
2319 base => $fai_base,
2320 scope => 'sub',
2321 attrs => ['cn','objectClass','FAIstate'],
2322 filter => $fai_filter,
2323 );
2324 daemon_log("$session_id DEBUG: Found ".$mesg->count()." FAI entries",7);
2326 if($mesg->{'resultCode'} == 0 &&
2327 $mesg->count != 0) {
2328 foreach my $entry (@{$mesg->{entries}}) {
2329 if($entry->exists('cn')) {
2330 my $tmp_dn= $entry->dn();
2332 # Skip classname and ou dn parts for class
2333 my $tmp_release = ($1) if $tmp_dn =~ /^[^,]+,[^,]+,(.*?),$fai_base$/;
2335 # Skip classes without releases
2336 if((!defined($tmp_release)) || length($tmp_release)==0) {
2337 next;
2338 }
2340 my $tmp_cn= $entry->get_value('cn');
2341 my $tmp_state= $entry->get_value('FAIstate');
2343 my $tmp_type;
2344 # Get FAI type
2345 for my $oclass(@{$entry->get_value('objectClass', asref => 1)}) {
2346 if(grep $_ eq $oclass, @possible_fai_classes) {
2347 $tmp_type= $oclass;
2348 last;
2349 }
2350 }
2352 if($tmp_release =~ /^.*?,.*?$/ && (!($tmp_release =~ /^.*?\\,.*?$/))) {
2353 # A Subrelease
2354 my @sub_releases = split(/,/, $tmp_release);
2356 # Walk through subreleases and build hash tree
2357 my $hash;
2358 while(my $tmp_sub_release = pop @sub_releases) {
2359 $hash .= "\{'$tmp_sub_release'\}->";
2360 }
2361 eval('push @{$fai_classes->'.$hash.'{$tmp_cn}->{$tmp_type}}, (defined($tmp_state) && length($tmp_state)>0)?$tmp_state:"";');
2362 } else {
2363 # A branch, no subrelease
2364 push @{$fai_classes->{$tmp_release}->{$tmp_cn}->{$tmp_type}}, (defined($tmp_state) && length($tmp_state)>0)?$tmp_state:"";
2365 }
2366 } elsif (!$entry->exists('cn')) {
2367 my $tmp_dn= $entry->dn();
2368 my $tmp_release = ($1) if $tmp_dn =~ /^(.*?),$fai_base$/;
2370 # Skip classes without releases
2371 if((!defined($tmp_release)) || length($tmp_release)==0) {
2372 next;
2373 }
2375 if($tmp_release =~ /^.*?,.*?$/ && (!($tmp_release =~ /^.*?\\,.*?$/))) {
2376 # A Subrelease
2377 my @sub_releases= split(/,/, $tmp_release);
2379 # Walk through subreleases and build hash tree
2380 my $hash;
2381 while(my $tmp_sub_release = pop @sub_releases) {
2382 $hash .= "\{'$tmp_sub_release'\}->";
2383 }
2384 # Remove the last two characters
2385 chop($hash);
2386 chop($hash);
2388 eval('$fai_classes->'.$hash.'= {}');
2389 } else {
2390 # A branch, no subrelease
2391 if(!exists($fai_classes->{$tmp_release})) {
2392 $fai_classes->{$tmp_release} = {};
2393 }
2394 }
2395 }
2396 }
2398 # The hash is complete, now we can honor the copy-on-write based missing entries
2399 foreach my $release (keys %$fai_classes) {
2400 $result->{$release}= deep_copy(apply_fai_inheritance($fai_classes->{$release}));
2401 }
2402 }
2403 return $result;
2404 }
2406 sub apply_fai_inheritance {
2407 my $fai_classes = shift || return {};
2408 my $tmp_classes;
2410 # Get the classes from the branch
2411 foreach my $class (keys %{$fai_classes}) {
2412 # Skip subreleases
2413 if($class =~ /^ou=.*$/) {
2414 next;
2415 } else {
2416 $tmp_classes->{$class}= deep_copy($fai_classes->{$class});
2417 }
2418 }
2420 # Apply to each subrelease
2421 foreach my $subrelease (keys %{$fai_classes}) {
2422 if($subrelease =~ /ou=/) {
2423 foreach my $tmp_class (keys %{$tmp_classes}) {
2424 if(!exists($fai_classes->{$subrelease}->{$tmp_class})) {
2425 $fai_classes->{$subrelease}->{$tmp_class} =
2426 deep_copy($tmp_classes->{$tmp_class});
2427 } else {
2428 foreach my $type (keys %{$tmp_classes->{$tmp_class}}) {
2429 if(!exists($fai_classes->{$subrelease}->{$tmp_class}->{$type})) {
2430 $fai_classes->{$subrelease}->{$tmp_class}->{$type}=
2431 deep_copy($tmp_classes->{$tmp_class}->{$type});
2432 }
2433 }
2434 }
2435 }
2436 }
2437 }
2439 # Find subreleases in deeper levels
2440 foreach my $subrelease (keys %{$fai_classes}) {
2441 if($subrelease =~ /ou=/) {
2442 foreach my $subsubrelease (keys %{$fai_classes->{$subrelease}}) {
2443 if($subsubrelease =~ /ou=/) {
2444 apply_fai_inheritance($fai_classes->{$subrelease});
2445 }
2446 }
2447 }
2448 }
2450 return $fai_classes;
2451 }
2453 sub get_fai_release_entries {
2454 my $tmp_classes = shift || return;
2455 my $parent = shift || "";
2456 my @result = shift || ();
2458 foreach my $entry (keys %{$tmp_classes}) {
2459 if(defined($entry)) {
2460 if($entry =~ /^ou=.*$/) {
2461 my $release_name = $entry;
2462 $release_name =~ s/ou=//g;
2463 if(length($parent)>0) {
2464 $release_name = $parent."/".$release_name;
2465 }
2466 my @bufentries = get_fai_release_entries($tmp_classes->{$entry}, $release_name, @result);
2467 foreach my $bufentry(@bufentries) {
2468 push @result, $bufentry;
2469 }
2470 } else {
2471 my @types = get_fai_types($tmp_classes->{$entry});
2472 foreach my $type (@types) {
2473 push @result,
2474 {
2475 'class' => $entry,
2476 'type' => $type->{'type'},
2477 'release' => $parent,
2478 'state' => $type->{'state'},
2479 };
2480 }
2481 }
2482 }
2483 }
2485 return @result;
2486 }
2488 sub deep_copy {
2489 my $this = shift;
2490 if (not ref $this) {
2491 $this;
2492 } elsif (ref $this eq "ARRAY") {
2493 [map deep_copy($_), @$this];
2494 } elsif (ref $this eq "HASH") {
2495 +{map { $_ => deep_copy($this->{$_}) } keys %$this};
2496 } else { die "what type is $_?" }
2497 }
2500 sub session_run_result {
2501 my ($kernel, $heap, $client_answer) = @_[KERNEL, HEAP, ARG0];
2502 $kernel->sig(CHLD => "child_reap");
2503 }
2505 sub session_run_debug {
2506 my $result = $_[ARG0];
2507 print STDERR "$result\n";
2508 }
2510 sub session_run_done {
2511 my ( $kernel, $heap, $task_id ) = @_[ KERNEL, HEAP, ARG0 ];
2512 delete $heap->{task}->{$task_id};
2513 }
2516 sub create_sources_list {
2517 my $session_id = shift;
2518 my $ldap_handle = &main::get_ldap_handle;
2519 my $result="/tmp/gosa_si_tmp_sources_list";
2521 # Remove old file
2522 if(stat($result)) {
2523 unlink($result);
2524 &main::daemon_log("$session_id DEBUG: remove an old version of '$result'", 7);
2525 }
2527 my $fh;
2528 open($fh, ">$result");
2529 if (not defined $fh) {
2530 &main::daemon_log("$session_id DEBUG: cannot open '$result' for writing", 7);
2531 return undef;
2532 }
2533 if(defined($main::ldap_server_dn) and length($main::ldap_server_dn) > 0) {
2534 my $mesg=$ldap_handle->search(
2535 base => $main::ldap_server_dn,
2536 scope => 'base',
2537 attrs => 'FAIrepository',
2538 filter => 'objectClass=FAIrepositoryServer'
2539 );
2540 if($mesg->count) {
2541 foreach my $entry(@{$mesg->{'entries'}}) {
2542 foreach my $value(@{$entry->get_value('FAIrepository', asref => 1)}) {
2543 my ($server, $tag, $release, $sections)= split /\|/, $value;
2544 my $line = "deb $server $release";
2545 $sections =~ s/,/ /g;
2546 $line.= " $sections";
2547 print $fh $line."\n";
2548 }
2549 }
2550 }
2551 } else {
2552 if (defined $main::ldap_server_dn){
2553 &main::daemon_log("$session_id ERROR: something wrong with ldap_server_dn '$main::ldap_server_dn', abort create_sources_list", 1);
2554 } else {
2555 &main::daemon_log("$session_id ERROR: no ldap_server_dn found, abort create_sources_list", 1);
2556 }
2557 }
2558 close($fh);
2560 return $result;
2561 }
2564 sub run_create_packages_list_db {
2565 my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
2566 my $session_id = $session->ID;
2568 my $task = POE::Wheel::Run->new(
2569 Priority => +20,
2570 Program => sub {&create_packages_list_db(undef, undef, $session_id)},
2571 StdoutEvent => "session_run_result",
2572 StderrEvent => "session_run_debug",
2573 CloseEvent => "session_run_done",
2574 );
2575 $heap->{task}->{ $task->ID } = $task;
2576 }
2579 sub create_packages_list_db {
2580 my ($ldap_handle, $sources_file, $session_id) = @_;
2582 # it should not be possible to trigger a recreation of packages_list_db
2583 # while packages_list_db is under construction, so set flag packages_list_under_construction
2584 # which is tested befor recreation can be started
2585 if (-r $packages_list_under_construction) {
2586 daemon_log("$session_id WARNING: packages_list_db is right now under construction, please wait until this process is finished", 3);
2587 return;
2588 } else {
2589 daemon_log("$session_id INFO: create_packages_list_db: start", 5);
2590 # set packages_list_under_construction to true
2591 system("touch $packages_list_under_construction");
2592 @packages_list_statements=();
2593 }
2595 if (not defined $session_id) { $session_id = 0; }
2596 if (not defined $ldap_handle) {
2597 $ldap_handle= &get_ldap_handle();
2599 if (not defined $ldap_handle) {
2600 daemon_log("$session_id ERROR: no ldap_handle available to create_packages_list_db", 1);
2601 unlink($packages_list_under_construction);
2602 return;
2603 }
2604 }
2605 if (not defined $sources_file) {
2606 &main::daemon_log("$session_id INFO: no sources_file given for creating packages list so trigger creation of it", 5);
2607 $sources_file = &create_sources_list($session_id);
2608 }
2610 if (not defined $sources_file) {
2611 &main::daemon_log("$session_id ERROR: no sources_file given under '$sources_file', skip create_packages_list_db", 1);
2612 unlink($packages_list_under_construction);
2613 return;
2614 }
2616 my $line;
2618 open(CONFIG, "<$sources_file") or do {
2619 daemon_log( "$session_id ERROR: create_packages_list_db: Failed to open '$sources_file'", 1);
2620 unlink($packages_list_under_construction);
2621 return;
2622 };
2624 # Read lines
2625 while ($line = <CONFIG>){
2626 # Unify
2627 chop($line);
2628 $line =~ s/^\s+//;
2629 $line =~ s/^\s+/ /;
2631 # Strip comments
2632 $line =~ s/#.*$//g;
2634 # Skip empty lines
2635 if ($line =~ /^\s*$/){
2636 next;
2637 }
2639 # Interpret deb line
2640 if ($line =~ /^deb [^\s]+\s[^\s]+\s[^\s]+/){
2641 my( $baseurl, $dist, $sections ) = ($line =~ /^deb\s([^\s]+)\s+([^\s]+)\s+(.*)$/);
2642 my $section;
2643 foreach $section (split(' ', $sections)){
2644 &parse_package_info( $baseurl, $dist, $section, $session_id );
2645 }
2646 }
2647 }
2649 close (CONFIG);
2652 find(\&cleanup_and_extract, keys( %repo_dirs ));
2653 &main::strip_packages_list_statements();
2654 unshift @packages_list_statements, "VACUUM";
2655 $packages_list_db->exec_statementlist(\@packages_list_statements);
2656 unlink($packages_list_under_construction);
2657 daemon_log("$session_id INFO: create_packages_list_db: finished", 5);
2658 return;
2659 }
2661 # This function should do some intensive task to minimize the db-traffic
2662 sub strip_packages_list_statements {
2663 my @existing_entries= @{$packages_list_db->exec_statement("SELECT * FROM $main::packages_list_tn")};
2664 my @new_statement_list=();
2665 my $hash;
2666 my $insert_hash;
2667 my $update_hash;
2668 my $delete_hash;
2669 my $local_timestamp=get_time();
2671 foreach my $existing_entry (@existing_entries) {
2672 $hash->{@{$existing_entry}[0]}->{@{$existing_entry}[1]}->{@{$existing_entry}[2]}= $existing_entry;
2673 }
2675 foreach my $statement (@packages_list_statements) {
2676 if($statement =~ /^INSERT/i) {
2677 # Assign the values from the insert statement
2678 my ($distribution,$package,$version,$section,$description,$template,$timestamp) = ($1,$2,$3,$4,$5,$6,$7) if $statement =~
2679 /^INSERT\s+?INTO\s+?$main::packages_list_tn\s+?VALUES\s*?\('(.*?)',\s*?'(.*?)',\s*?'(.*?)',\s*?'(.*?)',\s*?'(.*?)',\s*?'(.*?)',\s*?'(.*?)'\s*?\)$/si;
2680 if(exists($hash->{$distribution}->{$package}->{$version})) {
2681 # If section or description has changed, update the DB
2682 if(
2683 (! (@{$hash->{$distribution}->{$package}->{$version}}[3] eq $section)) or
2684 (! (@{$hash->{$distribution}->{$package}->{$version}}[4] eq $description))
2685 ) {
2686 @{$update_hash->{$distribution}->{$package}->{$version}} = ($distribution,$package,$version,$section,$description,undef);
2687 }
2688 } else {
2689 # Insert a non-existing entry to db
2690 @{$insert_hash->{$distribution}->{$package}->{$version}} = ($distribution,$package,$version,$section,$description,$template);
2691 }
2692 } elsif ($statement =~ /^UPDATE/i) {
2693 my ($template,$package,$version) = ($1,$2,$3) if $statement =~
2694 /^update\s+?$main::packages_list_tn\s+?set\s+?template\s*?=\s*?'(.*?)'\s+?where\s+?package\s*?=\s*?'(.*?)'\s+?and\s+?version\s*?=\s*?'(.*?)'\s*?;$/si;
2695 foreach my $distribution (keys %{$hash}) {
2696 if(exists($insert_hash->{$distribution}->{$package}->{$version})) {
2697 # update the insertion hash to execute only one query per package (insert instead insert+update)
2698 @{$insert_hash->{$distribution}->{$package}->{$version}}[5]= $template;
2699 } elsif(exists($hash->{$distribution}->{$package}->{$version})) {
2700 if( ! (@{$hash->{$distribution}->{$package}->{$version}}[5] eq $template)) {
2701 my $section;
2702 my $description;
2703 if(defined(@{$update_hash->{$distribution}->{$package}->{$version}}[3]) and
2704 length(@{$update_hash->{$distribution}->{$package}->{$version}}[3]) > 0 ) {
2705 $section= @{$update_hash->{$distribution}->{$package}->{$version}}[3];
2706 }
2707 if(defined(@{$update_hash->{$distribution}->{$package}->{$version}}[4])) {
2708 $description= @{$update_hash->{$distribution}->{$package}->{$version}}[4];
2709 }
2710 @{$update_hash->{$distribution}->{$package}->{$version}} = ($distribution,$package,$version,$section,$description,$template);
2711 }
2712 }
2713 }
2714 }
2715 }
2717 # TODO: Check for orphaned entries
2719 # unroll the insert_hash
2720 foreach my $distribution (keys %{$insert_hash}) {
2721 foreach my $package (keys %{$insert_hash->{$distribution}}) {
2722 foreach my $version (keys %{$insert_hash->{$distribution}->{$package}}) {
2723 push @new_statement_list, "INSERT INTO $main::packages_list_tn VALUES ('$distribution','$package','$version',"
2724 ."'@{$insert_hash->{$distribution}->{$package}->{$version}}[3]',"
2725 ."'@{$insert_hash->{$distribution}->{$package}->{$version}}[4]',"
2726 ."'@{$insert_hash->{$distribution}->{$package}->{$version}}[5]',"
2727 ."'$local_timestamp')";
2728 }
2729 }
2730 }
2732 # unroll the update hash
2733 foreach my $distribution (keys %{$update_hash}) {
2734 foreach my $package (keys %{$update_hash->{$distribution}}) {
2735 foreach my $version (keys %{$update_hash->{$distribution}->{$package}}) {
2736 my $set = "";
2737 if(defined(@{$update_hash->{$distribution}->{$package}->{$version}}[3])) {
2738 $set .= "section = '@{$update_hash->{$distribution}->{$package}->{$version}}[3]', ";
2739 }
2740 if(defined(@{$update_hash->{$distribution}->{$package}->{$version}}[4])) {
2741 $set .= "description = '@{$update_hash->{$distribution}->{$package}->{$version}}[4]', ";
2742 }
2743 if(defined(@{$update_hash->{$distribution}->{$package}->{$version}}[5])) {
2744 $set .= "template = '@{$update_hash->{$distribution}->{$package}->{$version}}[5]', ";
2745 }
2746 if(defined($set) and length($set) > 0) {
2747 $set .= "timestamp = '$local_timestamp'";
2748 } else {
2749 next;
2750 }
2751 push @new_statement_list,
2752 "UPDATE $main::packages_list_tn SET $set WHERE"
2753 ." distribution = '$distribution'"
2754 ." AND package = '$package'"
2755 ." AND version = '$version'";
2756 }
2757 }
2758 }
2760 @packages_list_statements = @new_statement_list;
2761 }
2764 sub parse_package_info {
2765 my ($baseurl, $dist, $section, $session_id)= @_;
2766 my ($package);
2767 if (not defined $session_id) { $session_id = 0; }
2768 my ($path) = ($baseurl =~ m%://[^/]*(.*)$%);
2769 $repo_dirs{ "${repo_path}/pool" } = 1;
2771 foreach $package ("Packages.gz"){
2772 daemon_log("$session_id DEBUG: create_packages_list: fetch $baseurl, $dist, $section", 7);
2773 get_package( "$baseurl/dists/$dist/$section/binary-$arch/$package", "$outdir/$dist/$section", $session_id );
2774 parse_package( "$outdir/$dist/$section", $dist, $path, $session_id );
2775 }
2777 }
2780 sub get_package {
2781 my ($url, $dest, $session_id)= @_;
2782 if (not defined $session_id) { $session_id = 0; }
2784 my $tpath = dirname($dest);
2785 -d "$tpath" || mkpath "$tpath";
2787 # This is ugly, but I've no time to take a look at "how it works in perl"
2788 if(0 == system("wget '$url' -O '$dest' 2>/dev/null") ) {
2789 system("gunzip -cd '$dest' > '$dest.in'");
2790 daemon_log("$session_id DEBUG: run command: gunzip -cd '$dest' > '$dest.in'", 5);
2791 unlink($dest);
2792 daemon_log("$session_id DEBUG: delete file '$dest'", 5);
2793 } else {
2794 daemon_log("$session_id ERROR: create_packages_list_db: get_packages: fetching '$url' failed!", 1);
2795 }
2796 return 0;
2797 }
2800 sub parse_package {
2801 my ($path, $dist, $srv_path, $session_id)= @_;
2802 if (not defined $session_id) { $session_id = 0;}
2803 my ($package, $version, $section, $description);
2804 my $PACKAGES;
2805 my $timestamp = &get_time();
2807 if(not stat("$path.in")) {
2808 daemon_log("$session_id ERROR: create_packages_list: parse_package: file '$path.in' is not readable",1);
2809 return;
2810 }
2812 open($PACKAGES, "<$path.in");
2813 if(not defined($PACKAGES)) {
2814 daemon_log("$session_id ERROR: create_packages_list_db: parse_package: cannot open '$path.in'",1);
2815 return;
2816 }
2818 # Read lines
2819 while (<$PACKAGES>){
2820 my $line = $_;
2821 # Unify
2822 chop($line);
2824 # Use empty lines as a trigger
2825 if ($line =~ /^\s*$/){
2826 my $sql = "INSERT INTO packages_list VALUES ('$dist', '$package', '$version', '$section', '$description', '', '$timestamp')";
2827 push(@packages_list_statements, $sql);
2828 $package = "none";
2829 $version = "none";
2830 $section = "none";
2831 $description = "none";
2832 next;
2833 }
2835 # Trigger for package name
2836 if ($line =~ /^Package:\s/){
2837 ($package)= ($line =~ /^Package: (.*)$/);
2838 next;
2839 }
2841 # Trigger for version
2842 if ($line =~ /^Version:\s/){
2843 ($version)= ($line =~ /^Version: (.*)$/);
2844 next;
2845 }
2847 # Trigger for description
2848 if ($line =~ /^Description:\s/){
2849 ($description)= &encode_base64(($line =~ /^Description: (.*)$/));
2850 next;
2851 }
2853 # Trigger for section
2854 if ($line =~ /^Section:\s/){
2855 ($section)= ($line =~ /^Section: (.*)$/);
2856 next;
2857 }
2859 # Trigger for filename
2860 if ($line =~ /^Filename:\s/){
2861 my ($filename) = ($line =~ /^Filename: (.*)$/);
2862 store_fileinfo( $package, $filename, $dist, $srv_path, $version, $repo_path );
2863 next;
2864 }
2865 }
2867 close( $PACKAGES );
2868 unlink( "$path.in" );
2869 }
2872 sub store_fileinfo {
2873 my( $package, $file, $dist, $path, $vers, $srvdir) = @_;
2875 my %fileinfo = (
2876 'package' => $package,
2877 'dist' => $dist,
2878 'version' => $vers,
2879 );
2881 $repo_files{ "${srvdir}/$file" } = \%fileinfo;
2882 }
2885 sub cleanup_and_extract {
2886 my $fileinfo = $repo_files{ $File::Find::name };
2888 if( defined $fileinfo ) {
2890 my $dir = "$outdir/$fileinfo->{ 'dist' }/debconf.d";
2891 my $sql;
2892 my $package = $fileinfo->{ 'package' };
2893 my $newver = $fileinfo->{ 'version' };
2895 mkpath($dir);
2896 system( "dpkg -e '$File::Find::name' '$dir/DEBIAN'" );
2898 if( -f "$dir/DEBIAN/templates" ) {
2900 daemon_log("DEBUG: Found debconf templates in '$package' - $newver", 7);
2902 my $tmpl= "";
2903 {
2904 local $/=undef;
2905 open FILE, "$dir/DEBIAN/templates";
2906 $tmpl = &encode_base64(<FILE>);
2907 close FILE;
2908 }
2909 rmtree("$dir/DEBIAN/templates");
2911 $sql= "update $main::packages_list_tn set template = '$tmpl' where package = '$package' and version = '$newver';";
2912 push @packages_list_statements, $sql;
2913 }
2914 }
2916 return;
2917 }
2920 sub register_at_foreign_servers {
2921 my ($kernel) = $_[KERNEL];
2923 # hole alle bekannten server aus known_server_db
2924 my $server_sql = "SELECT * FROM $known_server_tn";
2925 my $server_res = $known_server_db->exec_statement($server_sql);
2927 # no entries in known_server_db
2928 if (not ref(@$server_res[0]) eq "ARRAY") {
2929 # TODO
2930 }
2932 # detect already connected clients
2933 my $client_sql = "SELECT * FROM $known_clients_tn";
2934 my $client_res = $known_clients_db->exec_statement($client_sql);
2936 # send my server details to all other gosa-si-server within the network
2937 foreach my $hit (@$server_res) {
2938 my $hostname = @$hit[0];
2939 my $hostkey = &create_passwd;
2941 # add already connected clients to registration message
2942 my $myhash = &create_xml_hash('new_server', $server_address, $hostname);
2943 &add_content2xml_hash($myhash, 'key', $hostkey);
2944 map(&add_content2xml_hash($myhash, 'client', @{$_}[0].",".@{$_}[4]), @$client_res);
2946 # build registration message and send it
2947 my $foreign_server_msg = &create_xml_string($myhash);
2948 my $error = &send_msg_to_target($foreign_server_msg, $hostname, $ServerPackages_key, "new_server", 0);
2949 }
2951 $kernel->delay_set("register_at_foreign_servers", $foreign_servers_register_delay);
2952 return;
2953 }
2956 #==== MAIN = main ==============================================================
2957 # parse commandline options
2958 Getopt::Long::Configure( "bundling" );
2959 GetOptions("h|help" => \&usage,
2960 "c|config=s" => \$cfg_file,
2961 "f|foreground" => \$foreground,
2962 "v|verbose+" => \$verbose,
2963 "no-arp+" => \$no_arp,
2964 );
2966 # read and set config parameters
2967 &check_cmdline_param ;
2968 &read_configfile($cfg_file, %cfg_defaults);
2969 &check_pid;
2971 $SIG{CHLD} = 'IGNORE';
2973 # forward error messages to logfile
2974 if( ! $foreground ) {
2975 open( STDIN, '+>/dev/null' );
2976 open( STDOUT, '+>&STDIN' );
2977 open( STDERR, '+>&STDIN' );
2978 }
2980 # Just fork, if we are not in foreground mode
2981 if( ! $foreground ) {
2982 chdir '/' or die "Can't chdir to /: $!";
2983 $pid = fork;
2984 setsid or die "Can't start a new session: $!";
2985 umask 0;
2986 } else {
2987 $pid = $$;
2988 }
2990 # Do something useful - put our PID into the pid_file
2991 if( 0 != $pid ) {
2992 open( LOCK_FILE, ">$pid_file" );
2993 print LOCK_FILE "$pid\n";
2994 close( LOCK_FILE );
2995 if( !$foreground ) {
2996 exit( 0 )
2997 };
2998 }
3000 # parse head url and revision from svn
3001 my $server_status_hash = { 'developmental'=>'revision', 'stable'=>'release'};
3002 $server_version =~ /^\$HeadURL: (\S+) \$:\$Rev: (\d+) \$$/;
3003 $server_headURL = defined $1 ? $1 : 'unknown' ;
3004 $server_revision = defined $2 ? $2 : 'unknown' ;
3005 if ($server_headURL =~ /\/tag\// ||
3006 $server_headURL =~ /\/branches\// ) {
3007 $server_status = "stable";
3008 } else {
3009 $server_status = "developmental" ;
3010 }
3013 daemon_log(" ", 1);
3014 daemon_log("$0 started!", 1);
3015 daemon_log("status: $server_status", 1);
3016 daemon_log($server_status_hash->{$server_status}.": $server_revision", 1);
3018 # connect to incoming_db
3019 unlink($incoming_file_name);
3020 $incoming_db = GOSA::DBsqlite->new($incoming_file_name);
3021 $incoming_db->create_table($incoming_tn, \@incoming_col_names);
3023 # connect to gosa-si job queue
3024 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
3025 $job_db->create_table($job_queue_tn, \@job_queue_col_names);
3027 # connect to known_clients_db
3028 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
3029 $known_clients_db->create_table($known_clients_tn, \@known_clients_col_names);
3031 # connect to foreign_clients_db
3032 $foreign_clients_db = GOSA::DBsqlite->new($foreign_clients_file_name);
3033 $foreign_clients_db->create_table($foreign_clients_tn, \@foreign_clients_col_names);
3035 # connect to known_server_db
3036 unlink($known_server_file_name);
3037 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
3038 $known_server_db->create_table($known_server_tn, \@known_server_col_names);
3040 # connect to login_usr_db
3041 $login_users_db = GOSA::DBsqlite->new($login_users_file_name);
3042 $login_users_db->create_table($login_users_tn, \@login_users_col_names);
3044 # connect to fai_server_db and fai_release_db
3045 unlink($fai_server_file_name);
3046 $fai_server_db = GOSA::DBsqlite->new($fai_server_file_name);
3047 $fai_server_db->create_table($fai_server_tn, \@fai_server_col_names);
3049 unlink($fai_release_file_name);
3050 $fai_release_db = GOSA::DBsqlite->new($fai_release_file_name);
3051 $fai_release_db->create_table($fai_release_tn, \@fai_release_col_names);
3053 # connect to packages_list_db
3054 #unlink($packages_list_file_name);
3055 unlink($packages_list_under_construction);
3056 $packages_list_db = GOSA::DBsqlite->new($packages_list_file_name);
3057 $packages_list_db->create_table($packages_list_tn, \@packages_list_col_names);
3059 # connect to messaging_db
3060 $messaging_db = GOSA::DBsqlite->new($messaging_file_name);
3061 $messaging_db->create_table($messaging_tn, \@messaging_col_names);
3064 # create xml object used for en/decrypting
3065 $xml = new XML::Simple();
3068 # foreign servers
3069 my @foreign_server_list;
3071 # add foreign server from cfg file
3072 if ($foreign_server_string ne "") {
3073 my @cfg_foreign_server_list = split(",", $foreign_server_string);
3074 foreach my $foreign_server (@cfg_foreign_server_list) {
3075 push(@foreign_server_list, $foreign_server);
3076 }
3077 }
3079 # add foreign server from dns
3080 my @tmp_servers;
3081 if ( !$server_domain) {
3082 # Try our DNS Searchlist
3083 for my $domain(get_dns_domains()) {
3084 chomp($domain);
3085 my @tmp_domains= &get_server_addresses($domain);
3086 if(@tmp_domains) {
3087 for my $tmp_server(@tmp_domains) {
3088 push @tmp_servers, $tmp_server;
3089 }
3090 }
3091 }
3092 if(@tmp_servers && length(@tmp_servers)==0) {
3093 daemon_log("0 WARNING: no foreign gosa-si-server found in DNS for domain '$server_domain'", 3);
3094 }
3095 } else {
3096 @tmp_servers = &get_server_addresses($server_domain);
3097 if( 0 == @tmp_servers ) {
3098 daemon_log("0 WARNING: no foreign gosa-si-server found in DNS for domain '$server_domain'", 3);
3099 }
3100 }
3101 foreach my $server (@tmp_servers) {
3102 unshift(@foreign_server_list, $server);
3103 }
3104 # eliminate duplicate entries
3105 @foreign_server_list = &del_doubles(@foreign_server_list);
3106 my $all_foreign_server = join(", ", @foreign_server_list);
3107 daemon_log("0 INFO: found foreign server in config file and DNS: $all_foreign_server", 5);
3109 # add all found foreign servers to known_server
3110 my $act_timestamp = &get_time();
3111 foreach my $foreign_server (@foreign_server_list) {
3113 # do not add myself to known_server_db
3114 if (&is_local($foreign_server)) { next; }
3115 ######################################
3117 my $res = $known_server_db->add_dbentry( {table=>$known_server_tn,
3118 primkey=>['hostname'],
3119 hostname=>$foreign_server,
3120 status=>'not_jet_registered',
3121 hostkey=>"none",
3122 timestamp=>$act_timestamp,
3123 } );
3124 }
3127 # Import all modules
3128 &import_modules;
3130 # Check wether all modules are gosa-si valid passwd check
3131 &password_check;
3133 # Prepare for using Opsi
3134 if ($opsi_enabled eq "true") {
3135 use JSON::RPC::Client;
3136 use XML::Quote qw(:all);
3137 $opsi_url= "https://".$opsi_admin.":".$opsi_password."@".$opsi_server.":4447/rpc";
3138 $opsi_client = new JSON::RPC::Client;
3139 }
3142 POE::Component::Server::TCP->new(
3143 Alias => "TCP_SERVER",
3144 Port => $server_port,
3145 ClientInput => sub {
3146 my ($kernel, $input) = @_[KERNEL, ARG0];
3147 push(@tasks, $input);
3148 push(@msgs_to_decrypt, $input);
3149 $kernel->yield("msg_to_decrypt");
3150 },
3151 InlineStates => {
3152 msg_to_decrypt => \&msg_to_decrypt,
3153 next_task => \&next_task,
3154 task_result => \&handle_task_result,
3155 task_done => \&handle_task_done,
3156 task_debug => \&handle_task_debug,
3157 child_reap => sub { "Do nothing special. I'm just a comment, but i'm necessary!" },
3158 }
3159 );
3161 daemon_log("start socket for incoming xml messages at port '$server_port' ", 1);
3163 # create session for repeatedly checking the job queue for jobs
3164 POE::Session->create(
3165 inline_states => {
3166 _start => \&session_start,
3167 register_at_foreign_servers => \®ister_at_foreign_servers,
3168 sig_handler => \&sig_handler,
3169 next_task => \&next_task,
3170 task_result => \&handle_task_result,
3171 task_done => \&handle_task_done,
3172 task_debug => \&handle_task_debug,
3173 watch_for_next_tasks => \&watch_for_next_tasks,
3174 watch_for_new_messages => \&watch_for_new_messages,
3175 watch_for_delivery_messages => \&watch_for_delivery_messages,
3176 watch_for_done_messages => \&watch_for_done_messages,
3177 watch_for_new_jobs => \&watch_for_new_jobs,
3178 watch_for_modified_jobs => \&watch_for_modified_jobs,
3179 watch_for_done_jobs => \&watch_for_done_jobs,
3180 watch_for_opsi_jobs => \&watch_for_opsi_jobs,
3181 watch_for_old_known_clients => \&watch_for_old_known_clients,
3182 create_packages_list_db => \&run_create_packages_list_db,
3183 create_fai_server_db => \&run_create_fai_server_db,
3184 create_fai_release_db => \&run_create_fai_release_db,
3185 recreate_packages_db => \&run_recreate_packages_db,
3186 session_run_result => \&session_run_result,
3187 session_run_debug => \&session_run_debug,
3188 session_run_done => \&session_run_done,
3189 child_reap => sub { "Do nothing special. I'm just a comment, but i'm necessary!" },
3190 }
3191 );
3194 POE::Kernel->run();
3195 exit;