1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 # FILE: gosa-si-server
5 #
6 # USAGE: ./gosa-si-server
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 #===============================================================================
23 use strict;
24 use warnings;
25 use Getopt::Long;
26 use Config::IniFiles;
27 use POSIX;
29 use Fcntl qw/:flock/;
30 use IO::Socket::INET;
31 use IO::Handle;
32 use IO::Select;
33 use Symbol qw(qualify_to_ref);
34 use Crypt::Rijndael;
35 use MIME::Base64;
36 use Digest::MD5 qw(md5 md5_hex md5_base64);
37 use XML::Simple;
38 use Data::Dumper;
39 use Sys::Syslog qw( :DEFAULT setlogsock);
40 use Time::HiRes qw( usleep clock_gettime );
41 use Cwd;
42 use File::Spec;
43 use File::Basename;
44 use File::Find;
45 use File::Copy;
46 use File::Path;
47 use GOSA::GosaSupportDaemon;
48 use POE qw(Component::Server::TCP Wheel::Run Filter::Reference);
49 use Net::LDAP;
50 use Net::LDAP::Util qw(:escape);
52 my $server_version = '$HeadURL: https://oss.gonicus.de/repositories/gosa/trunk/gosa-si/gosa-si-server $:$Rev$';
54 # revision number of server and program name
55 my $server_headURL;
56 my $server_revision;
57 my $server_status;
58 our $prg= basename($0);
59 our $verbose= 0;
61 my $db_module = "DBsqlite";
62 {
63 no strict "refs";
64 require ("GOSA/".$db_module.".pm");
65 ("GOSA/".$db_module)->import;
66 }
68 my $modules_path = "/usr/lib/gosa-si/modules";
69 use lib "/usr/lib/gosa-si/modules";
71 our $global_kernel;
72 my ($foreground, $ping_timeout);
73 my ($server);
74 my ($gosa_server, $job_queue_timeout, $job_queue_loop_delay);
75 my ($messaging_db_loop_delay);
76 my ($procid, $pid);
77 my $arp_fifo;
78 my $debug_parts = 0;
79 my $debug_parts_bitstring;
80 my ($xml);
81 my $sources_list;
82 my $max_clients;
83 my %repo_files=();
84 my $repo_path;
85 my %repo_dirs=();
87 # Variables declared in config file are always set to 'our'
88 our (%cfg_defaults, $log_file, $pid_file,
89 $server_ip, $server_port, $ClientPackages_key, $dns_lookup,
90 $arp_activ, $gosa_unit_tag,
91 $GosaPackages_key, $gosa_timeout,
92 $serverPackages_enabled, $foreign_server_string, $server_domain, $ServerPackages_key, $foreign_servers_register_delay,
93 $wake_on_lan_passwd, $job_synchronization, $modified_jobs_loop_delay,
94 $arp_enabled, $arp_interface,
95 $opsi_enabled, $opsi_server, $opsi_admin, $opsi_password,
96 $new_systems_ou,
97 $arch,
98 );
100 # additional variable which should be globaly accessable
101 our $server_address;
102 our $server_mac_address;
103 our $gosa_address;
104 our $no_arp;
105 our $forground;
106 our $cfg_file;
107 our ($ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $ldap_server_dn, $ldap_version, $ldap_retry_sec);
108 our ($mysql_username, $mysql_password, $mysql_database, $mysql_host);
109 our $known_modules;
110 our $known_functions;
111 our $root_uid;
112 our $adm_gid;
114 # if foreground is not null, script will be not forked to background
115 $foreground = 0 ;
117 # specifies the timeout seconds while checking the online status of a registrating client
118 $ping_timeout = 5;
120 $no_arp = 0;
121 my $packages_list_under_construction = "/tmp/packages_list_creation_in_progress";
122 my @packages_list_statements;
123 my $watch_for_new_jobs_in_progress = 0;
125 # holds all incoming decrypted messages
126 our $incoming_db;
127 our $incoming_tn = 'incoming';
128 my $incoming_file_name;
129 my @incoming_col_names = ("id INTEGER PRIMARY KEY",
130 "timestamp VARCHAR(14) DEFAULT 'none'",
131 "headertag VARCHAR(255) DEFAULT 'none'",
132 "targettag VARCHAR(255) DEFAULT 'none'",
133 "xmlmessage TEXT",
134 "module VARCHAR(255) DEFAULT 'none'",
135 "sessionid VARCHAR(255) DEFAULT '0'",
136 );
138 # holds all gosa jobs
139 our $job_db;
140 our $job_queue_tn = 'jobs';
141 my $job_queue_file_name;
142 my @job_queue_col_names = ("id INTEGER PRIMARY KEY",
143 "timestamp VARCHAR(14) DEFAULT 'none'",
144 "status VARCHAR(255) DEFAULT 'none'",
145 "result TEXT",
146 "progress VARCHAR(255) DEFAULT 'none'",
147 "headertag VARCHAR(255) DEFAULT 'none'",
148 "targettag VARCHAR(255) DEFAULT 'none'",
149 "xmlmessage TEXT",
150 "macaddress VARCHAR(17) DEFAULT 'none'",
151 "plainname VARCHAR(255) DEFAULT 'none'",
152 "siserver VARCHAR(255) DEFAULT 'none'",
153 "modified INTEGER DEFAULT '0'",
154 "periodic VARCHAR(6) DEFAULT 'none'",
155 );
157 # holds all other gosa-si-server
158 our $known_server_db;
159 our $known_server_tn = "known_server";
160 my $known_server_file_name;
161 my @known_server_col_names = ("hostname VARCHAR(255)", "macaddress VARCHAR(17)", "status VARCHAR(255)", "hostkey VARCHAR(255)", "loaded_modules TEXT", "timestamp VARCHAR(14)", "update_time VARCHAR(14)");
163 # holds all registrated clients
164 our $known_clients_db;
165 our $known_clients_tn = "known_clients";
166 my $known_clients_file_name;
167 my @known_clients_col_names = ("hostname VARCHAR(255)", "status VARCHAR(255)", "hostkey VARCHAR(255)", "timestamp VARCHAR(14)", "macaddress VARCHAR(17)", "events TEXT", "keylifetime VARCHAR(255)");
169 # holds all registered clients at a foreign server
170 our $foreign_clients_db;
171 our $foreign_clients_tn = "foreign_clients";
172 my $foreign_clients_file_name;
173 my @foreign_clients_col_names = ("hostname VARCHAR(255)", "macaddress VARCHAR(17)", "regserver VARCHAR(255)", "timestamp VARCHAR(14)");
175 # holds all logged in user at each client
176 our $login_users_db;
177 our $login_users_tn = "login_users";
178 my $login_users_file_name;
179 my @login_users_col_names = ("client VARCHAR(255)", "user VARCHAR(255)", "timestamp VARCHAR(14)", "regserver VARCHAR(255) DEFAULT 'localhost'");
181 # holds all fai server, the debian release and tag
182 our $fai_server_db;
183 our $fai_server_tn = "fai_server";
184 my $fai_server_file_name;
185 our @fai_server_col_names = ("timestamp VARCHAR(14)", "server VARCHAR(255)", "fai_release VARCHAR(255)", "sections VARCHAR(255)", "tag VARCHAR(255)");
187 our $fai_release_db;
188 our $fai_release_tn = "fai_release";
189 my $fai_release_file_name;
190 our @fai_release_col_names = ("timestamp VARCHAR(14)", "fai_release VARCHAR(255)", "class VARCHAR(255)", "type VARCHAR(255)", "state VARCHAR(255)");
192 # holds all packages available from different repositories
193 our $packages_list_db;
194 our $packages_list_tn = "packages_list";
195 my $packages_list_file_name;
196 our @packages_list_col_names = ("distribution VARCHAR(255)", "package VARCHAR(255)", "version VARCHAR(255)", "section VARCHAR(255)", "description TEXT", "template LONGBLOB", "timestamp VARCHAR(14)");
197 my $outdir = "/tmp/packages_list_db";
199 # holds all messages which should be delivered to a user
200 our $messaging_db;
201 our $messaging_tn = "messaging";
202 our @messaging_col_names = ("id INTEGER", "subject TEXT", "message_from VARCHAR(255)", "message_to VARCHAR(255)",
203 "flag VARCHAR(255)", "direction VARCHAR(255)", "delivery_time VARCHAR(255)", "message TEXT", "timestamp VARCHAR(14)" );
204 my $messaging_file_name;
206 # path to directory to store client install log files
207 our $client_fai_log_dir = "/var/log/fai";
209 # queue which stores taskes until one of the $max_children children are ready to process the task
210 #my @tasks = qw();
211 my @msgs_to_decrypt = qw();
212 my $max_children = 2;
215 # loop delay for job queue to look for opsi jobs
216 my $job_queue_opsi_delay = 10;
217 our $opsi_client;
218 our $opsi_url;
220 # Lifetime of logged in user information. If no update information comes after n seconds,
221 # the user is expeceted to be no longer logged in or the host is no longer running. Because
222 # of this, the user is deleted from login_users_db
223 our $logged_in_user_date_of_expiry = 600;
225 # List of month names, used in function daemon_log
226 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
228 # List of accepted periodical xml tags related to cpan modul DateTime
229 our $check_periodic = {"months"=>'', "weeks"=>'', "days"=>'', "hours"=>'', "minutes"=>''};
232 %cfg_defaults = (
233 "general" => {
234 "log-file" => [\$log_file, "/var/run/".$prg.".log"],
235 "pid-file" => [\$pid_file, "/var/run/".$prg.".pid"],
236 },
237 "server" => {
238 "ip" => [\$server_ip, "0.0.0.0"],
239 "port" => [\$server_port, "20081"],
240 "known-clients" => [\$known_clients_file_name, '/var/lib/gosa-si/clients.db' ],
241 "known-servers" => [\$known_server_file_name, '/var/lib/gosa-si/servers.db'],
242 "incoming" => [\$incoming_file_name, '/var/lib/gosa-si/incoming.db'],
243 "login-users" => [\$login_users_file_name, '/var/lib/gosa-si/users.db'],
244 "fai-server" => [\$fai_server_file_name, '/var/lib/gosa-si/fai_server.db'],
245 "fai-release" => [\$fai_release_file_name, '/var/lib/gosa-si/fai_release.db'],
246 "packages-list" => [\$packages_list_file_name, '/var/lib/gosa-si/packages.db'],
247 "messaging" => [\$messaging_file_name, '/var/lib/gosa-si/messaging.db'],
248 "foreign-clients" => [\$foreign_clients_file_name, '/var/lib/gosa-si/foreign_clients.db'],
249 "source-list" => [\$sources_list, '/etc/apt/sources.list'],
250 "repo-path" => [\$repo_path, '/srv/www'],
251 "debian-arch" => [\$arch, 'i386'],
252 "ldap-uri" => [\$ldap_uri, ""],
253 "ldap-base" => [\$ldap_base, ""],
254 "ldap-admin-dn" => [\$ldap_admin_dn, ""],
255 "ldap-admin-password" => [\$ldap_admin_password, ""],
256 "ldap-version" => [\$ldap_version, 3],
257 "ldap-retry-sec" => [\$ldap_retry_sec, 10],
258 "gosa-unit-tag" => [\$gosa_unit_tag, ""],
259 "max-clients" => [\$max_clients, 10],
260 "wol-password" => [\$wake_on_lan_passwd, ""],
261 "mysql-username" => [\$mysql_username, "gosa_si"],
262 "mysql-password" => [\$mysql_password, ""],
263 "mysql-database" => [\$mysql_database, "gosa_si"],
264 "mysql-host" => [\$mysql_host, "127.0.0.1"],
265 },
266 "GOsaPackages" => {
267 "job-queue" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
268 "job-queue-loop-delay" => [\$job_queue_loop_delay, 3],
269 "messaging-db-loop-delay" => [\$messaging_db_loop_delay, 3],
270 "key" => [\$GosaPackages_key, "none"],
271 "new-systems-ou" => [\$new_systems_ou, 'ou=workstations,ou=systems'],
272 },
273 "ClientPackages" => {
274 "key" => [\$ClientPackages_key, "none"],
275 "user-date-of-expiry" => [\$logged_in_user_date_of_expiry, 600],
276 },
277 "ServerPackages"=> {
278 "enabled" => [\$serverPackages_enabled, "true"],
279 "address" => [\$foreign_server_string, ""],
280 "dns-lookup" => [\$dns_lookup, "true"],
281 "domain" => [\$server_domain, ""],
282 "key" => [\$ServerPackages_key, "none"],
283 "key-lifetime" => [\$foreign_servers_register_delay, 120],
284 "job-synchronization-enabled" => [\$job_synchronization, "true"],
285 "synchronization-loop" => [\$modified_jobs_loop_delay, 5],
286 },
287 "ArpHandler" => {
288 "enabled" => [\$arp_enabled, "false"],
289 "interface" => [\$arp_interface, "all"],
290 },
291 "Opsi" => {
292 "enabled" => [\$opsi_enabled, "false"],
293 "server" => [\$opsi_server, "localhost"],
294 "admin" => [\$opsi_admin, "opsi-admin"],
295 "password" => [\$opsi_password, "secret"],
296 },
298 );
301 #=== FUNCTION ================================================================
302 # NAME: usage
303 # PARAMETERS: nothing
304 # RETURNS: nothing
305 # DESCRIPTION: print out usage text to STDERR
306 #===============================================================================
307 sub usage {
308 print STDERR << "EOF" ;
309 usage: $prg [-hvf] [-c config] [-d number]
311 -h : this (help) message
312 -c <file> : config file
313 -f : foreground, process will not be forked to background
314 -v : be verbose (multiple to increase verbosity)
315 'v': error logs
316 'vvv': warning plus error logs
317 'vvvvv': info plus warning logs
318 'vvvvvvv': debug plus info logs
319 -no-arp : starts $prg without connection to arp module
320 -d <int> : if verbose level is higher than 7x 'v' specified parts can be debugged
321 1 : report incoming messages
322 2 : report unencrypted outgoing messages
323 4 : report encrypting key for messages
324 8 : report decrypted incoming message and verification if the message complies gosa-si requirements
325 16 : message processing
326 32 : ldap connectivity
327 64 : database status and connectivity
328 128 : main process
329 256 : creation of packages_list_db
330 512 : ARP debug information
331 EOF
332 exit(0);
333 }
336 #=== FUNCTION ================================================================
337 # NAME: logging
338 # PARAMETERS: level - string - default 'info'
339 # msg - string -
340 # facility - string - default 'LOG_DAEMON'
341 # RETURNS: nothing
342 # DESCRIPTION: function for logging
343 #===============================================================================
344 sub daemon_log {
345 my( $msg, $level ) = @_;
346 if (not defined $msg) { return }
347 if (not defined $level) { $level = 1 }
348 my $to_be_logged = 0;
350 # Write log line if line level is lower than verbosity given in commandline
351 if ($level <= $verbose)
352 {
353 $to_be_logged = 1 ;
354 }
356 # Write if debug flag is set and bitstring matches
357 if ($debug_parts > 0)
358 {
359 my $tmp_level = ($level - 10 >= 0) ? $level - 10 : 0 ;
360 my $tmp_level_bitstring = unpack("B32", pack("N", $tmp_level));
361 if (int($debug_parts_bitstring & $tmp_level_bitstring))
362 {
363 $to_be_logged = 1;
364 }
365 }
367 if ($to_be_logged)
368 {
369 if(defined $log_file){
370 my $open_log_fh = sysopen(LOG_HANDLE, $log_file, O_WRONLY | O_CREAT | O_APPEND , 0440);
371 if(not $open_log_fh) {
372 print STDERR "cannot open $log_file: $!";
373 return;
374 }
375 # Check owner and group of log_file and update settings if necessary
376 my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat($log_file);
377 if((not $uid eq $root_uid) || (not $gid eq $adm_gid)) {
378 chown($root_uid, $adm_gid, $log_file);
379 }
381 # Prepare time string for log message
382 my ($seconds,$minutes,$hours,$monthday,$month,$year,$weekday,$yearday,$sommertime) = localtime(time);
383 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
384 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
385 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
386 $month = $monthnames[$month];
387 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
388 $year+=1900;
390 # Microseconds since epoch
391 my $microSeconds = sprintf("%.2f", &Time::HiRes::clock_gettime());
392 $microSeconds =~ s/^\d*(.\d\d)$/$1/;
394 # Build log message and write it to log file and commandline
395 chomp($msg);
396 my $log_msg = "$month $monthday $hours:$minutes:$seconds$microSeconds $prg $msg\n";
397 flock(LOG_HANDLE, LOCK_EX);
398 seek(LOG_HANDLE, 0, 2);
399 print LOG_HANDLE $log_msg;
400 flock(LOG_HANDLE, LOCK_UN);
401 if( $foreground )
402 {
403 print STDERR $log_msg;
404 }
405 close( LOG_HANDLE );
406 }
407 }
408 }
411 #=== FUNCTION ================================================================
412 # NAME: check_cmdline_param
413 # PARAMETERS: nothing
414 # RETURNS: nothing
415 # DESCRIPTION: validates commandline parameter
416 #===============================================================================
417 sub check_cmdline_param () {
418 my $err_counter = 0;
420 # Check configuration file
421 if(not defined($cfg_file)) {
422 $cfg_file = "/etc/gosa-si/server.conf";
423 if(! -r $cfg_file) {
424 print STDERR "Please specify a config file.\n";
425 $err_counter++;
426 }
427 }
429 # Prepare identification which gosa-si parts should be debugged and which not
430 if (defined $debug_parts)
431 {
432 if ($debug_parts =~ /^\d+$/)
433 {
434 $debug_parts_bitstring = unpack("B32", pack("N", $debug_parts));
435 }
436 else
437 {
438 print STDERR "Value '$debug_parts' invalid for option d (number expected)\n";
439 $err_counter++;
440 }
441 }
443 # Exit if an error occour
444 if( $err_counter > 0 ) { &usage( "", 1 ); }
445 }
448 #=== FUNCTION ================================================================
449 # NAME: check_pid
450 # PARAMETERS: nothing
451 # RETURNS: nothing
452 # DESCRIPTION: handels pid processing
453 #===============================================================================
454 sub check_pid {
455 $pid = -1;
456 # Check, if we are already running
457 if( open( my $LOCK_FILE, "<", "$pid_file" ) ) {
458 $pid = <$LOCK_FILE>;
459 if( defined $pid ) {
460 chomp( $pid );
461 if( -f "/proc/$pid/stat" ) {
462 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
463 if( $stat ) {
464 print STDERR "\nERROR: Already running!\n";
465 close( $LOCK_FILE );
466 exit -1;
467 }
468 }
469 }
470 close( $LOCK_FILE );
471 unlink( $pid_file );
472 }
474 # create a syslog msg if it is not to possible to open PID file
475 if (not sysopen(my $LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
476 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
477 if (open(my $LOCK_FILE, '<', $pid_file)
478 && ($pid = <$LOCK_FILE>))
479 {
480 chomp($pid);
481 $msg .= "(PID $pid)\n";
482 } else {
483 $msg .= "(unable to read PID)\n";
484 }
485 if( ! ($foreground) ) {
486 openlog( $0, "cons,pid", "daemon" );
487 syslog( "warning", $msg );
488 closelog();
489 }
490 else {
491 print( STDERR " $msg " );
492 }
493 exit( -1 );
494 }
495 }
497 #=== FUNCTION ================================================================
498 # NAME: import_modules
499 # PARAMETERS: module_path - string - abs. path to the directory the modules
500 # are stored
501 # RETURNS: nothing
502 # DESCRIPTION: each file in module_path which ends with '.pm' and activation
503 # state is on is imported by "require 'file';"
504 #===============================================================================
505 sub import_modules {
506 if (not -e $modules_path) {
507 daemon_log("0 ERROR: cannot find directory or directory is not readable: $modules_path", 1);
508 }
510 opendir (DIR, $modules_path) or die "ERROR while loading modules from directory $modules_path : $!\n";
512 while (defined (my $file = readdir (DIR))) {
513 if (not $file =~ /(\S*?).pm$/) {
514 next;
515 }
516 my $mod_name = $1;
518 # ArpHandler switch
519 if( $file =~ /ArpHandler.pm/ ) {
520 if( $arp_enabled eq "false" ) { next; }
521 }
523 # ServerPackages switch
524 if ($file eq "ServerPackages.pm" && $serverPackages_enabled eq "false")
525 {
526 $dns_lookup = "false";
527 next;
528 }
530 eval { require $file; };
531 if ($@) {
532 daemon_log("0 ERROR: gosa-si-server could not load module $file", 1);
533 daemon_log("$@", 1);
534 exit;
535 } else {
536 my $info = eval($mod_name.'::get_module_info()');
537 # Only load module if get_module_info() returns a non-null object
538 if( $info ) {
539 my ($input_address, $input_key, $event_hash) = @{$info};
540 $known_modules->{$mod_name} = $info;
541 daemon_log("0 INFO: module $mod_name loaded", 5);
542 }
543 }
544 }
545 close (DIR);
546 }
548 #=== FUNCTION ================================================================
549 # NAME: password_check
550 # PARAMETERS: nothing
551 # RETURNS: nothing
552 # DESCRIPTION: escalates an critical error if two modules exist which are avaialable by
553 # the same password
554 #===============================================================================
555 sub password_check {
556 my $passwd_hash = {};
557 while (my ($mod_name, $mod_info) = each %$known_modules) {
558 my $mod_passwd = @$mod_info[1];
559 if (not defined $mod_passwd) { next; }
560 if (not exists $passwd_hash->{$mod_passwd}) {
561 $passwd_hash->{$mod_passwd} = $mod_name;
563 # escalates critical error
564 } else {
565 &daemon_log("0 ERROR: two loaded modules do have the same password. Please modify the 'key'-parameter in config file");
566 &daemon_log("0 ERROR: module='$mod_name' and module='".$passwd_hash->{$mod_passwd}."'");
567 exit( -1 );
568 }
569 }
571 }
574 #=== FUNCTION ================================================================
575 # NAME: sig_int_handler
576 # PARAMETERS: signal - string - signal arose from system
577 # RETURNS: nothing
578 # DESCRIPTION: handels tasks to be done befor signal becomes active
579 #===============================================================================
580 sub sig_int_handler {
581 my ($signal) = @_;
583 # if (defined($ldap_handle)) {
584 # $ldap_handle->disconnect;
585 # }
586 # TODO alle verbliebenden ldap verbindungen aus allen heaps beenden
589 daemon_log("shutting down gosa-si-server", 1);
590 system("kill `ps -C gosa-si-server -o pid=`");
591 }
592 $SIG{INT} = \&sig_int_handler;
595 sub check_key_and_xml_validity {
596 my ($crypted_msg, $module_key, $session_id) = @_;
597 my $msg;
598 my $msg_hash;
599 my $error_string;
600 eval{
601 $msg = &decrypt_msg($crypted_msg, $module_key);
603 if ($msg =~ /<xml>/i){
604 $msg =~ s/\s+/ /g; # just for better daemon_log
605 daemon_log("$session_id DEBUG: decrypted_msg: \n$msg", 18);
606 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
608 ##############
609 # check header
610 if( not exists $msg_hash->{'header'} ) { die "no header specified"; }
611 my $header_l = $msg_hash->{'header'};
612 if( (1 > @{$header_l}) || ( ( 'HASH' eq ref @{$header_l}[0]) && (1 > keys %{@{$header_l}[0]}) ) ) { die 'empty header tag'; }
613 if( 1 < @{$header_l} ) { die 'more than one header specified'; }
614 my $header = @{$header_l}[0];
615 if( 0 == length $header) { die 'empty string in header tag'; }
617 ##############
618 # check source
619 if( not exists $msg_hash->{'source'} ) { die "no source specified"; }
620 my $source_l = $msg_hash->{'source'};
621 if( (1 > @{$source_l}) || ( ( 'HASH' eq ref @{$source_l}[0]) && (1 > keys %{@{$source_l}[0]}) ) ) { die 'empty source tag'; }
622 if( 1 < @{$source_l} ) { die 'more than one source specified'; }
623 my $source = @{$source_l}[0];
624 if( 0 == length $source) { die 'source error'; }
626 ##############
627 # check target
628 if( not exists $msg_hash->{'target'} ) { die "no target specified"; }
629 my $target_l = $msg_hash->{'target'};
630 if( (1 > @{$target_l}) || ( ('HASH' eq ref @{$target_l}[0]) && (1 > keys %{@{$target_l}[0]}) ) ) { die 'empty target tag'; }
631 }
632 };
633 if($@) {
634 daemon_log("$session_id ERROR: do not understand the message: $@", 1);
635 $msg = undef;
636 $msg_hash = undef;
637 }
639 return ($msg, $msg_hash);
640 }
643 sub check_outgoing_xml_validity {
644 my ($msg, $session_id) = @_;
646 my $msg_hash;
647 eval{
648 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
650 ##############
651 # check header
652 my $header_l = $msg_hash->{'header'};
653 if( 1 != @{$header_l} ) {
654 die 'no or more than one headers specified';
655 }
656 my $header = @{$header_l}[0];
657 if( 0 == length $header) {
658 die 'header has length 0';
659 }
661 ##############
662 # check source
663 my $source_l = $msg_hash->{'source'};
664 if( 1 != @{$source_l} ) {
665 die 'no or more than 1 sources specified';
666 }
667 my $source = @{$source_l}[0];
668 if( 0 == length $source) {
669 die 'source has length 0';
670 }
672 # Check if source contains hostname instead of ip address
673 if($source =~ /^[a-z][\w\-\.]+:\d+$/i) {
674 my ($hostname,$port) = split(/:/, $source);
675 my $ip_address = inet_ntoa(scalar gethostbyname($hostname));
676 if(defined($ip_address) && $ip_address =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ && $port =~ /^\d+$/) {
677 # Write ip address to $source variable
678 $source = "$ip_address:$port";
679 $msg_hash->{source}[0] = $source ;
680 $msg =~ s/<source>.*<\/source>/<source>$source<\/source>/;
681 }
682 }
683 unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
684 $source =~ /^GOSA$/i) {
685 die "source '$source' is neither a complete ip-address with port nor 'GOSA'";
686 }
688 ##############
689 # check target
690 my $target_l = $msg_hash->{'target'};
691 if( 0 == @{$target_l} ) {
692 die "no targets specified";
693 }
694 foreach my $target (@$target_l) {
695 if( 0 == length $target) {
696 die "target has length 0";
697 }
698 unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
699 $target =~ /^GOSA$/i ||
700 $target =~ /^\*$/ ||
701 $target =~ /KNOWN_SERVER/i ||
702 $target =~ /JOBDB/i ||
703 $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 ){
704 die "target '$target' is not a complete ip-address with port or a valid target name or a mac-address";
705 }
706 }
707 };
708 if($@) {
709 daemon_log("$session_id ERROR: outgoing msg is not gosa-si envelope conform: $@", 1);
710 daemon_log("$@ ".(defined($msg) && length($msg)>0)?$msg:"Empty Message", 1);
711 $msg_hash = undef;
712 }
714 return ($msg, $msg_hash);
715 }
718 sub input_from_known_server {
719 my ($input, $remote_ip, $session_id) = @_ ;
720 my ($msg, $msg_hash, $module);
722 my $sql_statement= "SELECT * FROM known_server";
723 my $query_res = $known_server_db->select_dbentry( $sql_statement );
725 while( my ($hit_num, $hit) = each %{ $query_res } ) {
726 my $host_name = $hit->{hostname};
727 if( not $host_name =~ "^$remote_ip") {
728 next;
729 }
730 my $host_key = $hit->{hostkey};
731 daemon_log("$session_id DEBUG: input_from_known_server: host_name: $host_name", 14);
732 daemon_log("$session_id DEBUG: input_from_known_server: host_key: $host_key", 14);
734 # check if module can open msg envelope with module key
735 my ($tmp_msg, $tmp_msg_hash) = &check_key_and_xml_validity($input, $host_key, $session_id);
736 if( (!$tmp_msg) || (!$tmp_msg_hash) ) {
737 daemon_log("$session_id DEBUG: input_from_known_server: deciphering raise error", 14);
738 daemon_log("$@", 14);
739 next;
740 }
741 else {
742 $msg = $tmp_msg;
743 $msg_hash = $tmp_msg_hash;
744 $module = "ServerPackages";
745 daemon_log("$session_id DEBUG: check_key_and_xml_validity... ok", 14);
746 last;
747 }
748 }
750 if( (!$msg) || (!$msg_hash) || (!$module) ) {
751 daemon_log("$session_id DEBUG: Incoming message is not from a known server", 14);
752 }
754 return ($msg, $msg_hash, $module);
755 }
758 sub input_from_known_client {
759 my ($input, $remote_ip, $session_id) = @_ ;
760 my ($msg, $msg_hash, $module);
762 my $sql_statement= "SELECT * FROM known_clients";
763 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
764 while( my ($hit_num, $hit) = each %{ $query_res } ) {
765 my $host_name = $hit->{hostname};
766 if( not $host_name =~ /^$remote_ip/) {
767 next;
768 }
769 my $host_key = $hit->{hostkey};
770 &daemon_log("$session_id DEBUG: input_from_known_client: host_name: $host_name", 14);
771 &daemon_log("$session_id DEBUG: input_from_known_client: host_key: $host_key", 14);
773 # check if module can open msg envelope with module key
774 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $host_key, $session_id);
776 if( (!$msg) || (!$msg_hash) ) {
777 &daemon_log("$session_id DEGUG: input_from_known_client: deciphering raise error", 14);
778 next;
779 }
780 else {
781 $module = "ClientPackages";
782 daemon_log("$session_id DEBUG: check_key_and_xml_validity... ok", 14);
783 last;
784 }
785 }
787 if( (!$msg) || (!$msg_hash) || (!$module) ) {
788 &daemon_log("$session_id DEBUG: Incoming message is not from a known client", 14);
789 }
791 return ($msg, $msg_hash, $module);
792 }
795 sub input_from_unknown_host {
796 no strict "refs";
797 my ($input, $session_id) = @_ ;
798 my ($msg, $msg_hash, $module);
799 my $error_string;
801 my %act_modules = %$known_modules;
803 while( my ($mod, $info) = each(%act_modules)) {
805 # check a key exists for this module
806 my $module_key = ${$mod."_key"};
807 if( not defined $module_key ) {
808 if( $mod eq 'ArpHandler' ) {
809 next;
810 }
811 daemon_log("$session_id ERROR: no key specified in config file for $mod", 1);
812 next;
813 }
814 daemon_log("$session_id DEBUG: $mod: $module_key", 14);
816 # check if module can open msg envelope with module key
817 ($msg, $msg_hash) = &check_key_and_xml_validity($input, $module_key, $session_id);
818 if( (not defined $msg) || (not defined $msg_hash) ) {
819 next;
820 } else {
821 $module = $mod;
822 daemon_log("$session_id DEBUG: check_key_and_xml_validity... ok", 18);
823 last;
824 }
825 }
827 if( (!$msg) || (!$msg_hash) || (!$module)) {
828 daemon_log("$session_id DEBUG: Incoming message is not from an unknown host", 14);
829 }
831 return ($msg, $msg_hash, $module);
832 }
835 sub create_ciphering {
836 my ($passwd) = @_;
837 if((!defined($passwd)) || length($passwd)==0) {
838 $passwd = "";
839 }
840 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
841 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
842 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
843 $my_cipher->set_iv($iv);
844 return $my_cipher;
845 }
848 sub encrypt_msg {
849 my ($msg, $key) = @_;
850 my $my_cipher = &create_ciphering($key);
851 my $len;
852 {
853 use bytes;
854 $len= 16-length($msg)%16;
855 }
856 $msg = "\0"x($len).$msg;
857 $msg = $my_cipher->encrypt($msg);
858 chomp($msg = &encode_base64($msg));
859 # there are no newlines allowed inside msg
860 $msg=~ s/\n//g;
861 return $msg;
862 }
865 sub decrypt_msg {
867 my ($msg, $key) = @_ ;
868 $msg = &decode_base64($msg);
869 my $my_cipher = &create_ciphering($key);
870 $msg = $my_cipher->decrypt($msg);
871 $msg =~ s/\0*//g;
872 return $msg;
873 }
876 sub get_encrypt_key {
877 my ($target) = @_ ;
878 my $encrypt_key;
879 my $error = 0;
881 # target can be in known_server
882 if( not defined $encrypt_key ) {
883 my $sql_statement= "SELECT * FROM known_server WHERE hostname='$target'";
884 my $query_res = $known_server_db->select_dbentry( $sql_statement );
885 while( my ($hit_num, $hit) = each %{ $query_res } ) {
886 my $host_name = $hit->{hostname};
887 if( $host_name ne $target ) {
888 next;
889 }
890 $encrypt_key = $hit->{hostkey};
891 last;
892 }
893 }
895 # target can be in known_client
896 if( not defined $encrypt_key ) {
897 my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$target'";
898 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
899 while( my ($hit_num, $hit) = each %{ $query_res } ) {
900 my $host_name = $hit->{hostname};
901 if( $host_name ne $target ) {
902 next;
903 }
904 $encrypt_key = $hit->{hostkey};
905 last;
906 }
907 }
909 return $encrypt_key;
910 }
913 #=== FUNCTION ================================================================
914 # NAME: open_socket
915 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
916 # [PeerPort] string necessary if port not appended by PeerAddr
917 # RETURNS: socket IO::Socket::INET
918 # DESCRIPTION: open a socket to PeerAddr
919 #===============================================================================
920 sub open_socket {
921 my ($PeerAddr, $PeerPort) = @_ ;
922 if(defined($PeerPort)){
923 $PeerAddr = $PeerAddr.":".$PeerPort;
924 }
925 my $socket;
926 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
927 Porto => "tcp",
928 Type => SOCK_STREAM,
929 Timeout => 5,
930 );
931 if(not defined $socket) {
932 return;
933 }
934 # &daemon_log("DEBUG: open_socket: $PeerAddr", 7);
935 return $socket;
936 }
939 sub send_msg_to_target {
940 my ($msg, $address, $encrypt_key, $msg_header, $session_id) = @_ ;
941 my $error = 0;
942 my $header;
943 my $timestamp = &get_time();
944 my $new_status;
945 my $act_status;
946 my ($sql_statement, $res);
948 if( $msg_header ) {
949 $header = "'$msg_header'-";
950 } else {
951 $header = "";
952 }
954 # Memorize own source address
955 my $own_source_address = &get_local_ip_for_remote_ip(sprintf("%s", $address =~ /^([0-9\.]*?):.*$/));
956 $own_source_address .= ":".$server_port;
958 # Patch 0.0.0.0 source to real address
959 $msg =~ s/<source>(0\.0\.0\.0):(\d*?)<\/source>/<source>$own_source_address<\/source>/s;
960 # Patch GOSA source to real address and add forward_to_gosa tag
961 $msg =~ s/<source>GOSA<\/source>/<source>$own_source_address<\/source> <forward_to_gosa>$own_source_address,$session_id<\/forward_to_gosa>/ ;
963 # encrypt xml msg
964 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
966 # opensocket
967 my $socket = &open_socket($address);
968 if( !$socket ) {
969 daemon_log("$session_id ERROR: Cannot open socket to host '$address'. Message processing aborted!", 1);
970 $error++;
971 }
973 if( $error == 0 ) {
974 # send xml msg
975 print $socket $crypted_msg.";$own_source_address\n";
976 daemon_log("$session_id INFO: send ".$header."msg to $address", 5);
977 daemon_log("$session_id DEBUG: message:\n$msg", 12);
979 }
981 # close socket in any case
982 if( $socket ) {
983 close $socket;
984 }
986 if( $error > 0 ) { $new_status = "down"; }
987 else { $new_status = $msg_header; }
990 # known_clients
991 $sql_statement = "SELECT * FROM $known_clients_tn WHERE hostname='$address'";
992 $res = $known_clients_db->select_dbentry($sql_statement);
993 if( keys(%$res) == 1) {
994 $act_status = exists $res->{1}->{'status'} ? $res->{1}->{'status'} : "";
995 if ($act_status eq "down" && $new_status eq "down") {
996 $sql_statement = "DELETE FROM known_clients WHERE hostname='$address'";
997 $res = $known_clients_db->del_dbentry($sql_statement);
998 daemon_log("$session_id WARNING: failed 2x to send msg to host '$address', delete host from known_clients", 3);
999 } else {
1000 $sql_statement = "UPDATE known_clients SET status='$new_status', timestamp='$timestamp' WHERE hostname='$address'";
1001 $res = $known_clients_db->update_dbentry($sql_statement);
1002 if($new_status eq "down"){
1003 daemon_log("$session_id WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
1004 } else {
1005 daemon_log("$session_id DEBUG: set '$address' from status '$act_status' to '$new_status'", 138);
1006 }
1007 }
1008 }
1010 # known_server
1011 $sql_statement = "SELECT * FROM $known_server_tn WHERE hostname='$address'";
1012 $res = $known_server_db->select_dbentry($sql_statement);
1013 if( keys(%$res) == 1) {
1014 $act_status = exists $res->{1}->{'status'} ? $res->{1}->{'status'} : "";
1015 if ($act_status eq "down" && $new_status eq "down") {
1016 $sql_statement = "DELETE FROM known_server WHERE hostname='$address'";
1017 $res = $known_server_db->del_dbentry($sql_statement);
1018 daemon_log("$session_id WARNING: failed 2x to send a message to host '$address', delete host from known_server", 3);
1019 }
1020 else {
1021 $sql_statement = "UPDATE known_server SET status='$new_status', timestamp='$timestamp' WHERE hostname='$address'";
1022 $res = $known_server_db->update_dbentry($sql_statement);
1023 if($new_status eq "down"){
1024 daemon_log("$session_id WARNING: set '$address' from status '$act_status' to '$new_status'", 3);
1025 } else {
1026 daemon_log("$session_id DEBUG: set '$address' from status '$act_status' to '$new_status'", 138);
1027 }
1028 }
1029 }
1030 return $error;
1031 }
1034 sub update_jobdb_status_for_send_msgs {
1035 my ($session_id, $answer, $error) = @_;
1036 if( $answer =~ /<jobdb_id>(\d+)<\/jobdb_id>/ ) {
1037 &daemon_log("$session_id DEBUG: try to update job status", 138);
1038 my $jobdb_id = $1;
1040 $answer =~ /<header>(.*)<\/header>/;
1041 my $job_header = $1;
1043 $answer =~ /<target>(.*)<\/target>/;
1044 my $job_target = $1;
1046 # Sending msg failed
1047 if( $error ) {
1049 # Set jobs to done, jobs do not need to deliver their message in any case
1050 if (($job_header eq "trigger_action_localboot")
1051 ||($job_header eq "trigger_action_lock")
1052 ||($job_header eq "trigger_action_halt")
1053 ) {
1054 my $sql_statement = "UPDATE $job_queue_tn SET status='done' WHERE id=$jobdb_id";
1055 my $res = $job_db->update_dbentry($sql_statement);
1057 # Reactivate jobs, jobs need to deliver their message
1058 } elsif (($job_header eq "trigger_action_activate")
1059 ||($job_header eq "trigger_action_update")
1060 ||($job_header eq "trigger_action_reinstall")
1061 ||($job_header eq "trigger_activate_new")
1062 ) {
1063 if ($job_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) {
1064 &reactivate_job_with_delay($session_id, $job_target, $job_header, 30 );
1065 } else {
1066 # If we don't have the mac adress at this time, we use the plainname
1067 my $plainname_result = $job_db->select_dbentry("SELECT plainname from jobs where id=$jobdb_id");
1068 my $plainname = $job_target;
1069 if ((keys(%$plainname_result) > 0) ) {
1070 $plainname = $plainname_result->{1}->{$job_target};
1071 }
1072 &reactivate_job_with_delay($session_id, $plainname, $job_header, 30 );
1073 }
1074 # For all other messages
1075 } else {
1076 my $sql_statement = "UPDATE $job_queue_tn ".
1077 "SET status='error', result='can not deliver msg, please consult log file' ".
1078 "WHERE id=$jobdb_id";
1079 my $res = $job_db->update_dbentry($sql_statement);
1080 }
1082 # Sending msg was successful
1083 } else {
1084 # Set jobs localboot, lock, activate, halt, reboot and wake to done
1085 # jobs reinstall, update, inst_update do themself setting to done
1086 if (($job_header eq "trigger_action_localboot")
1087 ||($job_header eq "trigger_action_lock")
1088 ||($job_header eq "trigger_action_activate")
1089 ||($job_header eq "trigger_action_halt")
1090 ||($job_header eq "trigger_action_reboot")
1091 ||($job_header eq "trigger_action_wake")
1092 ||($job_header eq "trigger_wake")
1093 ) {
1095 my $sql_statement = "UPDATE $job_queue_tn ".
1096 "SET status='done' ".
1097 "WHERE id=$jobdb_id AND status='processed'";
1098 my $res = $job_db->update_dbentry($sql_statement);
1099 } else {
1100 &daemon_log("$session_id DEBUG: sending message succeed but cannot update job status.", 138);
1101 }
1102 }
1103 } else {
1104 &daemon_log("$session_id DEBUG: cannot update job status, msg has no jobdb_id-tag.", 138);
1105 }
1106 }
1108 sub reactivate_job_with_delay {
1109 my ($session_id, $target, $header, $delay) = @_ ;
1110 # Sometimes the client is still booting or does not wake up, in this case reactivate the job (if it exists) with a delay of n sec
1112 if (not defined $delay) { $delay = 30 } ;
1113 my $delay_timestamp = &calc_timestamp(&get_time(), "plus", $delay);
1115 my $sql = "UPDATE $job_queue_tn Set timestamp='$delay_timestamp', status='waiting' WHERE (macaddress LIKE '$target' OR plainname LIKE '$target') AND headertag='$header'";
1116 my $res = $job_db->update_dbentry($sql);
1117 daemon_log("$session_id INFO: '$header'-job will be reactivated at '$delay_timestamp' ".
1118 "cause client '$target' is currently not available", 5);
1119 return;
1120 }
1123 sub sig_handler {
1124 my ($kernel, $signal) = @_[KERNEL, ARG0] ;
1125 daemon_log("0 INFO got signal '$signal'", 1);
1126 $kernel->sig_handled();
1127 return;
1128 }
1131 sub msg_to_decrypt {
1132 my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
1133 my $session_id = $session->ID;
1134 my ($msg, $msg_hash, $module);
1135 my $error = 0;
1137 # fetch new msg out of @msgs_to_decrypt
1138 my $tmp_next_msg = shift @msgs_to_decrypt;
1139 my ($next_msg, $msg_source) = split(/;/, $tmp_next_msg);
1141 # msg is from a new client or gosa
1142 ($msg, $msg_hash, $module) = &input_from_unknown_host($next_msg, $session_id);
1144 # msg is from a gosa-si-server
1145 if(((!$msg) || (!$msg_hash) || (!$module)) && ($serverPackages_enabled eq "true")){
1146 if (not defined $msg_source)
1147 {
1148 # Only needed, to be compatible with older gosa-si-server versions
1149 ($msg, $msg_hash, $module) = &input_from_known_server($next_msg, $heap->{'remote_ip'}, $session_id);
1150 }
1151 else
1152 {
1153 ($msg, $msg_hash, $module) = &input_from_known_server($next_msg, $msg_source, $session_id);
1154 }
1155 }
1156 # msg is from a gosa-si-client
1157 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
1158 if (not defined $msg_source)
1159 {
1160 # Only needed, to be compatible with older gosa-si-server versions
1161 ($msg, $msg_hash, $module) = &input_from_known_client($next_msg, $heap->{'remote_ip'}, $session_id);
1162 }
1163 else
1164 {
1165 ($msg, $msg_hash, $module) = &input_from_known_client($next_msg, $msg_source, $session_id);
1166 }
1167 }
1168 # an error occurred
1169 if(( !$msg ) || ( !$msg_hash ) || ( !$module )){
1170 # If an incoming msg could not be decrypted (maybe a wrong key), decide if msg comes from a client
1171 # or a server. In case of a client, send a ping. If the client could not understand a msg from its
1172 # server the client cause a re-registering process. In case of a server, decrease update_time in kown_server_db
1173 # and trigger a re-registering process for servers
1174 if (defined $msg_source && $msg_source =~ /:$server_port$/ && $serverPackages_enabled eq "true")
1175 {
1176 daemon_log("$session_id WARNING: Cannot understand incoming msg from server '$msg_source'. Cause re-registration process for servers.", 3);
1177 my $update_statement = "UPDATE $known_server_tn SET update_time='19700101000000' WHERE hostname='$msg_source'";
1178 daemon_log("$session_id DEBUG: $update_statement", 7);
1179 my $upadte_res = $known_server_db->exec_statement($update_statement);
1180 $kernel->yield("register_at_foreign_servers");
1181 }
1182 elsif ((defined $msg_source) && (not $msg_source =~ /:$server_port$/))
1183 {
1184 daemon_log("$session_id WARNING: Cannot understand incoming msg from client '$msg_source'. Send ping-msg to cause a re-registering of the client if necessary", 3);
1185 #my $remote_ip = $heap->{'remote_ip'};
1186 #my $remote_port = $heap->{'remote_port'};
1187 my $ping_msg = "<xml> <header>gosa_ping</header> <source>$server_address</source><target>$msg_source</target></xml>";
1188 my ($test_error, $test_error_string) = &send_msg_to_target($ping_msg, "$msg_source", "dummy-key", "gosa_ping", $session_id);
1189 daemon_log("$session_id WARNING: Sending msg to cause re-registering: $ping_msg", 3);
1190 }
1191 else
1192 {
1193 my $foreign_host = defined $msg_source ? $msg_source : $heap->{'remote_ip'};
1194 daemon_log("$session_id ERROR: Incoming message from host '$foreign_host' cannot be understood. Processing aborted!", 1);
1195 daemon_log("$session_id DEBUG: Aborted message: $tmp_next_msg", 11);
1196 }
1198 $error++
1199 }
1202 my $header;
1203 my $target;
1204 my $source;
1205 my $done = 0;
1206 my $sql;
1207 my $res;
1209 # check whether this message should be processed here
1210 if ($error == 0) {
1211 $header = @{$msg_hash->{'header'}}[0];
1212 $target = @{$msg_hash->{'target'}}[0];
1213 $source = @{$msg_hash->{'source'}}[0];
1214 my $not_found_in_known_clients_db = 0;
1215 my $not_found_in_known_server_db = 0;
1216 my $not_found_in_foreign_clients_db = 0;
1217 my $local_address;
1218 my $local_mac;
1219 my ($target_ip, $target_port) = split(':', $target);
1221 # Determine the local ip address if target is an ip address
1222 if ($target =~ /^\d+\.\d+\.\d+\.\d+:\d+$/) {
1223 $local_address = &get_local_ip_for_remote_ip($target_ip).":$server_port";
1224 } else {
1225 $local_address = $server_address;
1226 }
1228 # Determine the local mac address if target is a mac address
1229 if ($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) {
1230 my $loc_ip = &get_local_ip_for_remote_ip($heap->{'remote_ip'});
1231 my $network_interface= &get_interface_for_ip($loc_ip);
1232 $local_mac = &get_mac_for_interface($network_interface);
1233 } else {
1234 $local_mac = $server_mac_address;
1235 }
1237 # target and source is equal to GOSA -> process here
1238 if (not $done) {
1239 if ($target eq "GOSA" && $source eq "GOSA") {
1240 $done = 1;
1241 &daemon_log("$session_id DEBUG: target and source is 'GOSA' -> process '$header' here", 11);
1242 }
1243 }
1245 # target is own address without forward_to_gosa-tag -> process here
1246 if (not $done) {
1247 #if ((($target eq $local_address) || ($target eq $local_mac) ) && (not exists $msg_hash->{'forward_to_gosa'})) {
1248 if (($target eq $local_address) && (not exists $msg_hash->{'forward_to_gosa'})) {
1249 $done = 1;
1250 if ($source eq "GOSA") {
1251 $msg =~ s/<\/xml>/<forward_to_gosa>$local_address,$session_id<\/forward_to_gosa><\/xml>/;
1252 }
1253 &daemon_log("$session_id DEBUG: target is own address without forward_to_gosa-tag -> process '$header' here", 11);
1254 }
1255 }
1257 # target is own address with forward_to_gosa-tag not pointing to myself -> process here
1258 if (not $done) {
1259 my $forward_to_gosa = @{$msg_hash->{'forward_to_gosa'}}[0];
1260 my $gosa_at;
1261 my $gosa_session_id;
1262 if (($target eq $local_address) && (defined $forward_to_gosa)){
1263 my ($gosa_at, $gosa_session_id) = split(/,/, $forward_to_gosa);
1264 if ($gosa_at ne $local_address) {
1265 $done = 1;
1266 &daemon_log("$session_id DEBUG: target is own address with forward_to_gosa-tag not pointing to myself -> process '$header' here", 11);
1267 }
1268 }
1269 }
1271 # Target is a client address and there is a processing function within a plugin -> process loaclly
1272 if (not $done)
1273 {
1274 # Check if target is a client address
1275 $sql = "SELECT * FROM $known_clients_tn WHERE (hostname='$target' OR macaddress LIKE '$target')";
1276 $res = $known_clients_db->select_dbentry($sql);
1277 if ((keys(%$res) > 0) )
1278 {
1279 my $hostname = $res->{1}->{'hostname'};
1280 my $reduced_header = $header;
1281 $reduced_header =~ s/gosa_//;
1282 # Check if there is a processing function within a plugin
1283 if (exists $known_functions->{$reduced_header})
1284 {
1285 $msg =~ s/<target>\S*<\/target>/<target>$hostname<\/target>/;
1286 $done = 1;
1287 &daemon_log("$session_id DEBUG: Target is client address with processing function within a plugin -> process '$header' here", 11);
1288 }
1289 }
1290 }
1292 # If header has a 'job_' prefix, do always process message locally
1293 # which means put it into job queue
1294 if ((not $done) && ($header =~ /job_/))
1295 {
1296 $done = 1;
1297 &daemon_log("$session_id DEBUG: Header has a 'job_' prefix. Put it into job queue. -> process '$header' here", 11);
1298 }
1300 # if message should be processed here -> add message to incoming_db
1301 if ($done) {
1302 # if a 'job_' or a 'gosa_' message comes from a foreign server, fake module from
1303 # ServerPackages to GosaPackages so gosa-si-server knows how to process this kind of messages
1304 if ($header =~ /^gosa_/ || $header =~ /^job_/) {
1305 $module = "GosaPackages";
1306 }
1308 my $res = $incoming_db->add_dbentry( {table=>$incoming_tn,
1309 primkey=>[],
1310 headertag=>$header,
1311 targettag=>$target,
1312 xmlmessage=>&encode_base64($msg),
1313 timestamp=>&get_time,
1314 module=>$module,
1315 sessionid=>$session_id,
1316 } );
1317 $kernel->yield('watch_for_next_tasks');
1318 }
1320 # target is own address with forward_to_gosa-tag pointing at myself -> forward to gosa
1321 if (not $done) {
1322 my $forward_to_gosa = @{$msg_hash->{'forward_to_gosa'}}[0];
1323 my $gosa_at;
1324 my $gosa_session_id;
1325 if (($target eq $local_address) && (defined $forward_to_gosa)){
1326 my ($gosa_at, $gosa_session_id) = split(/,/, $forward_to_gosa);
1327 if ($gosa_at eq $local_address) {
1328 my $session_reference = $kernel->ID_id_to_session($gosa_session_id);
1329 if( defined $session_reference ) {
1330 $heap = $session_reference->get_heap();
1331 }
1332 if(exists $heap->{'client'}) {
1333 $msg = &encrypt_msg($msg, $GosaPackages_key);
1334 $heap->{'client'}->put($msg);
1335 &daemon_log("$session_id DEBUG: incoming '$header' message forwarded to GOsa", 11);
1336 }
1337 $done = 1;
1338 &daemon_log("$session_id DEBUG: target is own address with forward_to_gosa-tag pointing at myself -> forward '$header' to gosa", 11);
1339 }
1340 }
1342 }
1344 # target is a client address in known_clients -> forward to client
1345 if (not $done) {
1346 $sql = "SELECT * FROM $known_clients_tn WHERE (hostname='$target' OR macaddress LIKE '$target')";
1347 $res = $known_clients_db->select_dbentry($sql);
1348 if (keys(%$res) > 0)
1349 {
1350 $done = 1;
1351 &daemon_log("$session_id DEBUG: target is a client address in known_clients -> forward '$header' to client", 11);
1352 my $hostkey = $res->{1}->{'hostkey'};
1353 my $hostname = $res->{1}->{'hostname'};
1354 $msg =~ s/<target>\S*<\/target>/<target>$hostname<\/target>/;
1355 $msg =~ s/<header>gosa_/<header>/;
1356 my $error= &send_msg_to_target($msg, $hostname, $hostkey, $header, $session_id);
1357 if ($error) {
1358 &daemon_log("$session_id ERROR: Some problems occurred while trying to send msg to client '$hostname': $msg", 1);
1359 }
1360 }
1361 else
1362 {
1363 $not_found_in_known_clients_db = 1;
1364 }
1365 }
1367 # target is a client address in foreign_clients -> forward to registration server
1368 if (not $done) {
1369 $sql = "SELECT * FROM $foreign_clients_tn WHERE (hostname='$target' OR macaddress LIKE '$target')";
1370 $res = $foreign_clients_db->select_dbentry($sql);
1371 if (keys(%$res) > 0) {
1372 my $hostname = $res->{1}->{'hostname'};
1373 my ($host_ip, $host_port) = split(/:/, $hostname);
1374 my $local_address = &get_local_ip_for_remote_ip($host_ip).":$server_port";
1375 my $regserver = $res->{1}->{'regserver'};
1376 my $sql = "SELECT * FROM $known_server_tn WHERE hostname='$regserver'";
1377 my $res = $known_server_db->select_dbentry($sql);
1378 if (keys(%$res) > 0) {
1379 my $regserver_key = $res->{1}->{'hostkey'};
1380 $msg =~ s/<source>GOSA<\/source>/<source>$local_address<\/source>/;
1381 $msg =~ s/<target>$target<\/target>/<target>$hostname<\/target>/;
1382 if ($source eq "GOSA") {
1383 $msg =~ s/<\/xml>/<forward_to_gosa>$local_address,$session_id<\/forward_to_gosa><\/xml>/;
1384 }
1385 my $error= &send_msg_to_target($msg, $regserver, $regserver_key, $header, $session_id);
1386 if ($error) {
1387 &daemon_log("$session_id ERROR: some problems occurred while trying to send msg to registration server: $msg", 1);
1388 }
1389 }
1390 $done = 1;
1391 &daemon_log("$session_id DEBUG: target is a client address in foreign_clients -> forward '$header' to registration server", 11);
1392 } else {
1393 $not_found_in_foreign_clients_db = 1;
1394 }
1395 }
1397 # target is a server address -> forward to server
1398 if (not $done) {
1399 $sql = "SELECT * FROM $known_server_tn WHERE (hostname='$target' OR macaddress LIKE '$target')";
1400 $res = $known_server_db->select_dbentry($sql);
1401 if (keys(%$res) > 0) {
1402 my $hostkey = $res->{1}->{'hostkey'};
1404 if ($source eq "GOSA") {
1405 $msg =~ s/<source>GOSA<\/source>/<source>$local_address<\/source>/;
1406 $msg =~ s/<\/xml>/<forward_to_gosa>$local_address,$session_id<\/forward_to_gosa><\/xml>/;
1408 }
1410 &send_msg_to_target($msg, $target, $hostkey, $header, $session_id);
1411 $done = 1;
1412 &daemon_log("$session_id DEBUG: target is a server address -> forward '$header' to server", 11);
1413 } else {
1414 $not_found_in_known_server_db = 1;
1415 }
1416 }
1419 # target is not in foreign_clients_db, known_server_db or known_clients_db, maybe it is a complete new one -> process here
1420 if ( $not_found_in_foreign_clients_db
1421 && $not_found_in_known_server_db
1422 && $not_found_in_known_clients_db) {
1423 &daemon_log("$session_id DEBUG: target is not in foreign_clients_db, known_server_db or known_clients_db, maybe it is a complete new one -> process '$header' here", 11);
1424 if ($header =~ /^gosa_/ || $header =~ /^job_/) {
1425 $module = "GosaPackages";
1426 }
1427 my $res = $incoming_db->add_dbentry( {table=>$incoming_tn,
1428 primkey=>[],
1429 headertag=>$header,
1430 targettag=>$target,
1431 xmlmessage=>&encode_base64($msg),
1432 timestamp=>&get_time,
1433 module=>$module,
1434 sessionid=>$session_id,
1435 } );
1436 $done = 1;
1437 $kernel->yield('watch_for_next_tasks');
1438 }
1441 if (not $done) {
1442 daemon_log("$session_id ERROR: do not know what to do with this message: $msg", 1);
1443 if ($source eq "GOSA") {
1444 my %data = ('error_msg' => &encode_base64($msg), 'error_string' => "Do not know what to do with this message!");
1445 my $error_msg = &build_msg("error", $local_address, "GOSA", \%data );
1447 my $session_reference = $kernel->ID_id_to_session($session_id);
1448 if( defined $session_reference ) {
1449 $heap = $session_reference->get_heap();
1450 }
1451 if(exists $heap->{'client'}) {
1452 $error_msg = &encrypt_msg($error_msg, $GosaPackages_key);
1453 $heap->{'client'}->put($error_msg);
1454 }
1455 }
1456 }
1458 }
1460 return;
1461 }
1464 sub next_task {
1465 my ($session, $heap, $task) = @_[SESSION, HEAP, ARG0, ARG1];
1466 my $running_task = POE::Wheel::Run->new(
1467 Program => sub { process_task($session, $heap, $task) },
1468 StdioFilter => POE::Filter::Reference->new(),
1469 StdoutEvent => "task_result",
1470 StderrEvent => "task_debug",
1471 CloseEvent => "task_done",
1472 );
1473 $heap->{task}->{ $running_task->ID } = $running_task;
1474 }
1476 sub handle_task_result {
1477 my ($kernel, $heap, $result) = @_[KERNEL, HEAP, ARG0];
1478 my $client_answer = $result->{'answer'};
1479 if( $client_answer =~ s/session_id=(\d+)$// ) {
1480 my $session_id = $1;
1481 if( defined $session_id ) {
1482 my $session_reference = $kernel->ID_id_to_session($session_id);
1483 if( defined $session_reference ) {
1484 $heap = $session_reference->get_heap();
1485 }
1486 }
1488 if(exists $heap->{'client'}) {
1489 $heap->{'client'}->put($client_answer);
1490 }
1491 }
1492 $kernel->sig(CHLD => "child_reap");
1493 }
1495 sub handle_task_debug {
1496 my $result = $_[ARG0];
1497 print STDERR "$result\n";
1498 }
1500 sub handle_task_done {
1501 my ( $kernel, $heap, $task_id ) = @_[ KERNEL, HEAP, ARG0 ];
1502 delete $heap->{task}->{$task_id};
1503 if (exists $heap->{ldap_handle}->{$task_id}) {
1504 &release_ldap_handle($heap->{ldap_handle}->{$task_id});
1505 }
1506 }
1508 sub process_task {
1509 no strict "refs";
1510 #CHECK: Not @_[...]?
1511 my ($session, $heap, $task) = @_;
1512 my $error = 0;
1513 my $answer_l;
1514 my ($answer_header, @answer_target_l, $answer_source);
1515 my $client_answer = "";
1517 # prepare all variables needed to process message
1518 #my $msg = $task->{'xmlmessage'};
1519 my $msg = &decode_base64($task->{'xmlmessage'});
1520 my $incoming_id = $task->{'id'};
1521 my $module = $task->{'module'};
1522 my $header = $task->{'headertag'};
1523 my $session_id = $task->{'sessionid'};
1524 my $msg_hash;
1525 eval {
1526 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
1527 };
1528 daemon_log("ERROR: XML failure '$@'") if ($@);
1529 my $source = @{$msg_hash->{'source'}}[0];
1531 # set timestamp of incoming client uptodate, so client will not
1532 # be deleted from known_clients because of expiration
1533 my $cur_time = &get_time();
1534 my $sql = "UPDATE $known_clients_tn SET timestamp='$cur_time' WHERE hostname='$source'";
1535 my $res = $known_clients_db->exec_statement($sql);
1537 ######################
1538 # process incoming msg
1539 if( $error == 0) {
1540 daemon_log("$session_id INFO: Incoming msg (session_id=$session_id) with header '".@{$msg_hash->{'header'}}[0]."'", 5);
1541 daemon_log("$session_id DEBUG: Processing module ".$module, 26);
1542 $answer_l = &{ $module."::process_incoming_msg" }($msg, $msg_hash, $session_id);
1544 if ( 0 < @{$answer_l} ) {
1545 my $answer_str = join("\n", @{$answer_l});
1546 my @headers;
1547 while ($answer_str =~ /<header>(\w+)<\/header>/g) {
1548 push(@headers, $1);
1549 }
1550 daemon_log("$session_id DEBUG: got answer message(s) with header: '".join("', '", @headers)."'", 26);
1551 } else {
1552 daemon_log("$session_id DEBUG: $module: got no answer from module!" ,26);
1553 }
1555 }
1556 if( !$answer_l ) { $error++ };
1558 ########
1559 # answer
1560 if( $error == 0 ) {
1562 foreach my $answer ( @{$answer_l} ) {
1563 # check outgoing msg to xml validity
1564 my ($answer, $answer_hash) = &check_outgoing_xml_validity($answer, $session_id);
1565 if( not defined $answer_hash ) { next; }
1567 $answer_header = @{$answer_hash->{'header'}}[0];
1568 @answer_target_l = @{$answer_hash->{'target'}};
1569 $answer_source = @{$answer_hash->{'source'}}[0];
1571 # deliver msg to all targets
1572 foreach my $answer_target ( @answer_target_l ) {
1574 # targets of msg are all gosa-si-clients in known_clients_db
1575 if( $answer_target eq "*" ) {
1576 # answer is for all clients
1577 my $sql_statement= "SELECT * FROM known_clients";
1578 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
1579 while( my ($hit_num, $hit) = each %{ $query_res } ) {
1580 my $host_name = $hit->{hostname};
1581 my $host_key = $hit->{hostkey};
1582 my $error = &send_msg_to_target($answer, $host_name, $host_key, $answer_header, $session_id);
1583 &update_jobdb_status_for_send_msgs($session_id, $answer, $error);
1584 }
1585 }
1587 # targets of msg are all gosa-si-server in known_server_db
1588 elsif( $answer_target eq "KNOWN_SERVER" ) {
1589 # answer is for all server in known_server
1590 my $sql_statement= "SELECT * FROM $known_server_tn";
1591 my $query_res = $known_server_db->select_dbentry( $sql_statement );
1592 while( my ($hit_num, $hit) = each %{ $query_res } ) {
1593 my $host_name = $hit->{hostname};
1594 my $host_key = $hit->{hostkey};
1595 $answer =~ s/<target>\S+<\/target>/<target>$host_name<\/target>/g;
1596 my $error = &send_msg_to_target($answer, $host_name, $host_key, $answer_header, $session_id);
1597 &update_jobdb_status_for_send_msgs($session_id, $answer, $error);
1598 }
1599 }
1601 # target of msg is GOsa
1602 elsif( $answer_target eq "GOSA" ) {
1603 my $session_id = ($1) if $answer =~ /<session_id>(\d+?)<\/session_id>/;
1604 my $add_on = "";
1605 if( defined $session_id ) {
1606 $add_on = ".session_id=$session_id";
1607 }
1608 my $header = ($1) if $answer =~ /<header>(\S*)<\/header>/;
1609 daemon_log("$session_id INFO: send ".$header." message to GOsa", 5);
1610 daemon_log("$session_id DEBUG: message:\n$answer", 12);
1611 # answer is for GOSA and has to returned to connected client
1612 my $gosa_answer = &encrypt_msg($answer, $GosaPackages_key);
1613 $client_answer = $gosa_answer.$add_on;
1614 }
1616 # target of msg is job queue at this host
1617 elsif( $answer_target eq "JOBDB") {
1618 $answer =~ /<header>(\S+)<\/header>/;
1619 my $header;
1620 if( defined $1 ) { $header = $1; }
1621 my $error = &send_msg_to_target($answer, $server_address, $GosaPackages_key, $header, $session_id);
1622 &update_jobdb_status_for_send_msgs($session_id, $answer, $error);
1623 }
1625 # Target of msg is a mac address
1626 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 ) {
1627 daemon_log("$session_id DEBUG: target is mac address '$answer_target', looking for host in known_clients and foreign_clients", 138);
1629 # Looking for macaddress in known_clients
1630 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress LIKE '$answer_target'";
1631 my $query_res = $known_clients_db->select_dbentry( $sql_statement );
1632 my $found_ip_flag = 0;
1633 while( my ($hit_num, $hit) = each %{ $query_res } ) {
1634 my $host_name = $hit->{hostname};
1635 my $host_key = $hit->{hostkey};
1636 $answer =~ s/$answer_target/$host_name/g;
1637 daemon_log("$session_id INFO: found host '$host_name', associated to '$answer_target'", 5);
1638 my $error = &send_msg_to_target($answer, $host_name, $host_key, $answer_header, $session_id);
1639 &update_jobdb_status_for_send_msgs($session_id, $answer, $error);
1640 $found_ip_flag++ ;
1641 }
1643 # Looking for macaddress in foreign_clients
1644 if ($found_ip_flag == 0) {
1645 my $sql = "SELECT * FROM $foreign_clients_tn WHERE macaddress LIKE '$answer_target'";
1646 my $res = $foreign_clients_db->select_dbentry($sql);
1647 while( my ($hit_num, $hit) = each %{ $res } ) {
1648 my $host_name = $hit->{hostname};
1649 my $reg_server = $hit->{regserver};
1650 daemon_log("$session_id INFO: found host '$host_name' with mac '$answer_target', registered at '$reg_server'", 5);
1652 # Fetch key for reg_server
1653 my $reg_server_key;
1654 my $sql = "SELECT * FROM $known_server_tn WHERE hostname='$reg_server'";
1655 my $res = $known_server_db->select_dbentry($sql);
1656 if (exists $res->{1}) {
1657 $reg_server_key = $res->{1}->{'hostkey'};
1658 } else {
1659 daemon_log("$session_id ERROR: cannot find hostkey for '$host_name' in '$known_server_tn'", 1);
1660 daemon_log("$session_id ERROR: unable to forward answer to correct registration server, processing is aborted!", 1);
1661 $reg_server_key = undef;
1662 }
1664 # Send answer to server where client is registered
1665 if (defined $reg_server_key) {
1666 $answer =~ s/$answer_target/$host_name/g;
1667 my $error = &send_msg_to_target($answer, $reg_server, $reg_server_key, $answer_header, $session_id);
1668 &update_jobdb_status_for_send_msgs($session_id, $answer, $error);
1669 $found_ip_flag++ ;
1670 }
1671 }
1672 }
1674 # No mac to ip matching found
1675 if( $found_ip_flag == 0) {
1676 daemon_log("$session_id WARNING: no host found in known_clients or foreign_clients with mac address '$answer_target'", 3);
1677 &reactivate_job_with_delay($session_id, $answer_target, $answer_header, 30);
1678 }
1680 # Answer is for one specific host
1681 } else {
1682 # get encrypt_key
1683 my $encrypt_key = &get_encrypt_key($answer_target);
1684 if( not defined $encrypt_key ) {
1685 # unknown target
1686 daemon_log("$session_id WARNING: unknown target '$answer_target'", 3);
1687 next;
1688 }
1689 my $error = &send_msg_to_target($answer, $answer_target, $encrypt_key, $answer_header,$session_id);
1690 &update_jobdb_status_for_send_msgs($session_id, $answer, $error);
1691 }
1692 }
1693 }
1694 }
1696 my $filter = POE::Filter::Reference->new();
1697 my %result = (
1698 status => "seems ok to me",
1699 answer => $client_answer,
1700 );
1702 my $output = $filter->put( [ \%result ] );
1703 print @$output;
1706 }
1708 sub session_start {
1709 my ($kernel) = $_[KERNEL];
1710 $global_kernel = $kernel;
1711 $kernel->yield('register_at_foreign_servers');
1712 $kernel->yield('create_fai_server_db', $fai_server_tn );
1713 $kernel->yield('create_fai_release_db', $fai_release_tn );
1714 $kernel->sig(USR1 => "sig_handler");
1715 $kernel->sig(USR2 => "recreate_packages_db");
1716 $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
1717 $kernel->delay_set('watch_for_done_jobs', $job_queue_loop_delay);
1718 $kernel->delay_set('watch_for_modified_jobs', $modified_jobs_loop_delay);
1719 $kernel->delay_set('watch_for_new_messages', $messaging_db_loop_delay);
1720 $kernel->delay_set('watch_for_delivery_messages', $messaging_db_loop_delay);
1721 $kernel->delay_set('watch_for_done_messages', $messaging_db_loop_delay);
1722 $kernel->delay_set('watch_for_old_known_clients', $job_queue_loop_delay);
1724 # Start opsi check
1725 if ($opsi_enabled eq "true") {
1726 $kernel->delay_set('watch_for_opsi_jobs', $job_queue_opsi_delay);
1727 }
1729 }
1732 sub watch_for_done_jobs {
1733 my $kernel = $_[KERNEL];
1735 my $sql_statement = "SELECT * FROM ".$job_queue_tn." WHERE ((status='done') AND (modified='0'))";
1736 my $res = $job_db->select_dbentry( $sql_statement );
1738 while( my ($number, $hit) = each %{$res} )
1739 {
1740 # Non periodical jobs can be deleted.
1741 if ($hit->{periodic} eq "none")
1742 {
1743 my $jobdb_id = $hit->{id};
1744 my $sql_statement = "DELETE FROM $job_queue_tn WHERE id=$jobdb_id";
1745 my $res = $job_db->del_dbentry($sql_statement);
1746 }
1748 # Periodical jobs should not be deleted but reactivated with new timestamp instead.
1749 else
1750 {
1751 my ($p_time, $periodic) = split("_", $hit->{periodic});
1752 my $reactivated_ts = $hit->{timestamp};
1753 my $act_ts = int(&get_time());
1754 while ($act_ts > int($reactivated_ts)) # Redo calculation to avoid multiple jobs in the past
1755 {
1756 $reactivated_ts = &calc_timestamp($reactivated_ts, "plus", $p_time, $periodic);
1757 }
1758 my $sql = "UPDATE $job_queue_tn SET status='waiting', timestamp='$reactivated_ts' WHERE id='".$hit->{id}."'";
1759 my $res = $job_db->exec_statement($sql);
1760 &daemon_log("J INFO: Update periodical job '".$hit->{headertag}."' for client '".$hit->{targettag}."'. New execution time '$reactivated_ts'.", 5);
1761 }
1762 }
1764 $kernel->delay_set('watch_for_done_jobs',$job_queue_loop_delay);
1765 }
1768 sub watch_for_opsi_jobs {
1769 my ($kernel) = $_[KERNEL];
1770 # 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
1771 # opsi install job is to parse the xml message. There is still the correct header.
1772 my $sql_statement = "SELECT * FROM ".$job_queue_tn." WHERE ((xmlmessage LIKE '%opsi_install_client</header>%') AND (status='processing') AND (siserver='localhost'))";
1773 my $res = $job_db->select_dbentry( $sql_statement );
1775 # Ask OPSI for an update of the running jobs
1776 while (my ($id, $hit) = each %$res ) {
1777 # Determine current parameters of the job
1778 my $hostId = $hit->{'plainname'};
1779 my $macaddress = $hit->{'macaddress'};
1780 my $progress = $hit->{'progress'};
1782 my $result= {};
1784 # For hosts, only return the products that are or get installed
1785 my $callobj;
1786 $callobj = {
1787 method => 'getProductStates_hash',
1788 params => [ $hostId ],
1789 id => 1,
1790 };
1792 my $hres = $opsi_client->call($opsi_url, $callobj);
1793 # TODO : move all opsi relevant statments to opsi plugin
1794 # The following 3 lines must be tested befor they can replace the rubbish above and below !!!
1795 #my ($res, $err) = &opsi_com::_getProductStates_hash(hostId=>$hostId)
1796 #if (not $err) {
1797 # my $htmp = $res->{$hostId};
1798 #
1799 if (not &check_opsi_res($hres)) {
1800 my $htmp= $hres->result->{$hostId};
1801 # Check state != not_installed or action == setup -> load and add
1802 my $products= 0;
1803 my $installed= 0;
1804 my $installing = 0;
1805 my $error= 0;
1806 my @installed_list;
1807 my @error_list;
1808 my $act_status = "none";
1809 foreach my $product (@{$htmp}){
1811 if ($product->{'installationStatus'} ne "not_installed" or
1812 $product->{'actionRequest'} eq "setup"){
1814 # Increase number of products for this host
1815 $products++;
1817 if ($product->{'installationStatus'} eq "failed"){
1818 $result->{$product->{'productId'}}= "error";
1819 unshift(@error_list, $product->{'productId'});
1820 $error++;
1821 }
1822 if ($product->{'installationStatus'} eq "installed" && $product->{'actionRequest'} eq "none"){
1823 $result->{$product->{'productId'}}= "installed";
1824 unshift(@installed_list, $product->{'productId'});
1825 $installed++;
1826 }
1827 if ($product->{'installationStatus'} eq "installing"){
1828 $result->{$product->{'productId'}}= "installing";
1829 $installing++;
1830 $act_status = "installing - ".$product->{'productId'};
1831 }
1832 }
1833 }
1835 # Estimate "rough" progress, avoid division by zero
1836 if ($products == 0) {
1837 $result->{'progress'}= 0;
1838 } else {
1839 $result->{'progress'}= int($installed * 100 / $products);
1840 }
1842 # Set updates in job queue
1843 if ((not $error) && (not $installing) && ($installed)) {
1844 $act_status = "installed - ".join(", ", @installed_list);
1845 }
1846 if ($error) {
1847 $act_status = "error - ".join(", ", @error_list);
1848 }
1849 if ($progress ne $result->{'progress'} ) {
1850 # Updating progress and result
1851 my $update_statement = "UPDATE $job_queue_tn SET modified='1', progress='".$result->{'progress'}."', result='$act_status' WHERE macaddress LIKE '$macaddress' AND siserver='localhost'";
1852 my $update_res = $job_db->update_dbentry($update_statement);
1853 }
1854 if ($progress eq 100) {
1855 # Updateing status
1856 my $done_statement = "UPDATE $job_queue_tn SET modified='1', ";
1857 if ($error) {
1858 $done_statement .= "status='error'";
1859 } else {
1860 $done_statement .= "status='done'";
1861 }
1862 $done_statement .= " WHERE macaddress LIKE '$macaddress' AND siserver='localhost'";
1863 my $done_res = $job_db->update_dbentry($done_statement);
1864 }
1867 }
1868 }
1870 $kernel->delay_set('watch_for_opsi_jobs', $job_queue_opsi_delay);
1871 }
1874 # If a job got an update or was modified anyway, send to all other si-server an update message of this jobs.
1875 sub watch_for_modified_jobs {
1876 my ($kernel,$heap) = @_[KERNEL, HEAP];
1878 my $sql_statement = "SELECT * FROM $job_queue_tn WHERE (modified='1')";
1879 my $res = $job_db->select_dbentry( $sql_statement );
1881 # if db contains no jobs which should be update, do nothing
1882 if (keys %$res != 0) {
1884 if ($job_synchronization eq "true") {
1885 # make out of the db result a gosa-si message
1886 my $update_msg = &db_res2si_msg ($res, "foreign_job_updates", "KNOWN_SERVER", "MY_LOCAL_ADDRESS");
1888 # update all other SI-server
1889 &inform_all_other_si_server($update_msg);
1890 }
1892 # set jobs all jobs to modified = 0, wait until the next modification for updates of other si-server
1893 $sql_statement = "UPDATE $job_queue_tn SET modified='0' ";
1894 $res = $job_db->update_dbentry($sql_statement);
1895 }
1897 $kernel->delay_set('watch_for_modified_jobs', $modified_jobs_loop_delay);
1898 }
1901 sub watch_for_new_jobs {
1902 if($watch_for_new_jobs_in_progress == 0) {
1903 $watch_for_new_jobs_in_progress = 1;
1904 my ($kernel,$heap) = @_[KERNEL, HEAP];
1906 # check gosa job queue for jobs with executable timestamp
1907 my $timestamp = &get_time();
1908 my $sql_statement = "SELECT * FROM $job_queue_tn WHERE siserver='localhost' AND status='waiting' AND (CAST(timestamp AS UNSIGNED)) < $timestamp ORDER BY timestamp";
1909 my $res = $job_db->exec_statement( $sql_statement );
1911 # Merge all new jobs that would do the same actions
1912 my @drops;
1913 my $hits;
1914 foreach my $hit (reverse @{$res} ) {
1915 my $macaddress= lc @{$hit}[8];
1916 my $headertag= @{$hit}[5];
1917 if(
1918 defined($hits->{$macaddress}) &&
1919 defined($hits->{$macaddress}->{$headertag}) &&
1920 defined($hits->{$macaddress}->{$headertag}[0])
1921 ) {
1922 push @drops, "DELETE FROM $job_queue_tn WHERE id = $hits->{$macaddress}->{$headertag}[0]";
1923 }
1924 $hits->{$macaddress}->{$headertag}= $hit;
1925 }
1927 # Delete new jobs with a matching job in state 'processing'
1928 foreach my $macaddress (keys %{$hits}) {
1929 foreach my $jobdb_headertag (keys %{$hits->{$macaddress}}) {
1930 my $jobdb_id = @{$hits->{$macaddress}->{$jobdb_headertag}}[0];
1931 if(defined($jobdb_id)) {
1932 my $sql_statement = "SELECT * FROM $job_queue_tn WHERE macaddress LIKE '$macaddress' AND headertag='$jobdb_headertag' AND status='processing'";
1933 my $res = $job_db->exec_statement( $sql_statement );
1934 foreach my $hit (@{$res}) {
1935 push @drops, "DELETE FROM $job_queue_tn WHERE id=$jobdb_id";
1936 }
1937 } else {
1938 daemon_log("J ERROR: Job without id exists for macaddress $macaddress!", 1);
1939 }
1940 }
1941 }
1943 # Commit deletion
1944 $job_db->exec_statementlist(\@drops);
1946 # Look for new jobs that could be executed
1947 foreach my $macaddress (keys %{$hits}) {
1949 # Look if there is an executing job
1950 my $sql_statement = "SELECT * FROM $job_queue_tn WHERE macaddress LIKE '$macaddress' AND status='processing'";
1951 my $res = $job_db->exec_statement( $sql_statement );
1953 # Skip new jobs for host if there is a processing job
1954 if(defined($res) and defined @{$res}[0]) {
1955 # Prevent race condition if there is a trigger_activate job waiting and a goto-activation job processing
1956 my $row = @{$res}[0] if (ref $res eq 'ARRAY');
1957 if(@{$row}[5] eq 'trigger_action_reinstall') {
1958 my $sql_statement_2 = "SELECT * FROM $job_queue_tn WHERE macaddress LIKE '$macaddress' AND status='waiting' AND headertag = 'trigger_activate_new'";
1959 my $res_2 = $job_db->exec_statement( $sql_statement_2 );
1960 if(defined($res_2) and defined @{$res_2}[0]) {
1961 # Set status from goto-activation to 'waiting' and update timestamp
1962 $job_db->exec_statement("UPDATE $job_queue_tn SET status='waiting', timestamp='".&calc_timestamp(&get_time(), 'plus', 30)."' WHERE macaddress LIKE '$macaddress' AND headertag = 'trigger_action_reinstall'");
1963 }
1964 }
1965 next;
1966 }
1968 foreach my $jobdb_headertag (keys %{$hits->{$macaddress}}) {
1969 my $jobdb_id = @{$hits->{$macaddress}->{$jobdb_headertag}}[0];
1970 if(defined($jobdb_id)) {
1971 my $job_msg = @{$hits->{$macaddress}->{$jobdb_headertag}}[7];
1973 daemon_log("J DEBUG: its time to execute $job_msg", 7);
1974 my $sql_statement = "SELECT * FROM known_clients WHERE macaddress LIKE '$macaddress'";
1975 my $res_hash = $known_clients_db->select_dbentry( $sql_statement );
1977 # expect macaddress is unique!!!!!!
1978 my $target = $res_hash->{1}->{hostname};
1980 # change header
1981 $job_msg =~ s/<header>job_/<header>gosa_/;
1983 # add sqlite_id
1984 $job_msg =~ s/<\/xml>$/<jobdb_id>$jobdb_id<\/jobdb_id><\/xml>/;
1986 $job_msg =~ /<header>(\S+)<\/header>/;
1987 my $header = $1 ;
1988 my $func_error = &send_msg_to_target($job_msg, $server_address, $GosaPackages_key, $header, "J");
1990 # update status in job queue to ...
1991 # ... 'processing', for jobs: 'reinstall', 'update', activate_new
1992 if (($header =~ /gosa_trigger_action_reinstall/)
1993 || ($header =~ /gosa_trigger_activate_new/)
1994 || ($header =~ /gosa_trigger_action_update/)) {
1995 my $sql_statement = "UPDATE $job_queue_tn SET status='processing' WHERE id=$jobdb_id";
1996 my $dbres = $job_db->update_dbentry($sql_statement);
1997 }
1999 # ... 'done', for all other jobs, they are no longer needed in the jobqueue
2000 else {
2001 my $sql_statement = "UPDATE $job_queue_tn SET status='done' WHERE id=$jobdb_id";
2002 my $dbres = $job_db->exec_statement($sql_statement);
2003 }
2006 # We don't want parallel processing
2007 last;
2008 }
2009 }
2010 }
2012 $watch_for_new_jobs_in_progress = 0;
2013 $kernel->delay_set('watch_for_new_jobs', $job_queue_loop_delay);
2014 }
2015 }
2018 sub watch_for_new_messages {
2019 my ($kernel,$heap) = @_[KERNEL, HEAP];
2020 my @coll_user_msg; # collection list of outgoing messages
2022 # check messaging_db for new incoming messages with executable timestamp
2023 my $timestamp = &get_time();
2024 my $sql_statement = "SELECT * FROM $messaging_tn WHERE ( (CAST(timestamp AS UNSIGNED))<$timestamp AND flag='n' AND direction='in' )";
2025 my $res = $messaging_db->exec_statement( $sql_statement );
2026 foreach my $hit (@{$res}) {
2028 # create outgoing messages
2029 my $message_to = @{$hit}[3];
2030 # translate message_to to plain login name
2031 my @message_to_l = split(/,/, $message_to);
2032 my %receiver_h;
2033 foreach my $receiver (@message_to_l) {
2034 if ($receiver =~ /^u_([\s\S]*)$/) {
2035 $receiver_h{$1} = 0;
2036 } elsif ($receiver =~ /^g_([\s\S]*)$/) {
2037 my $group_name = $1;
2038 # fetch all group members from ldap and add them to receiver hash
2039 my $ldap_handle = &get_ldap_handle();
2040 if (defined $ldap_handle) {
2041 my $mesg = $ldap_handle->search(
2042 base => $ldap_base,
2043 scope => 'sub',
2044 attrs => ['memberUid'],
2045 filter => "cn=$group_name",
2046 );
2047 if ($mesg->count) {
2048 my @entries = $mesg->entries;
2049 foreach my $entry (@entries) {
2050 my @receivers= $entry->get_value("memberUid");
2051 foreach my $receiver (@receivers) {
2052 $receiver_h{$receiver} = 0;
2053 }
2054 }
2055 }
2056 # translating errors ?
2057 if ($mesg->code) {
2058 daemon_log("M ERROR: unable to translate group '$group_name' to user list for message delivery: $mesg->error", 1);
2059 }
2060 &release_ldap_handle($ldap_handle);
2061 # ldap handle error ?
2062 } else {
2063 daemon_log("M ERROR: unable to translate group '$group_name' to user list for message delivery: no ldap handle available", 1);
2064 }
2065 } else {
2066 my $sbjct = &encode_base64(@{$hit}[1]);
2067 my $msg = &encode_base64(@{$hit}[7]);
2068 &daemon_log("M WARNING: unknown receiver '$receiver' for a user-message '$sbjct - $msg'", 3);
2069 }
2070 }
2071 my @receiver_l = keys(%receiver_h);
2073 my $message_id = @{$hit}[0];
2075 #add each outgoing msg to messaging_db
2076 my $receiver;
2077 foreach $receiver (@receiver_l) {
2078 my $sql_statement = "INSERT INTO $messaging_tn (id, subject, message_from, message_to, flag, direction, delivery_time, message, timestamp) ".
2079 "VALUES ('".
2080 $message_id."', '". # id
2081 @{$hit}[1]."', '". # subject
2082 @{$hit}[2]."', '". # message_from
2083 $receiver."', '". # message_to
2084 "none"."', '". # flag
2085 "out"."', '". # direction
2086 @{$hit}[6]."', '". # delivery_time
2087 @{$hit}[7]."', '". # message
2088 $timestamp."'". # timestamp
2089 ")";
2090 &daemon_log("M DEBUG: $sql_statement", 1);
2091 my $res = $messaging_db->exec_statement($sql_statement);
2092 &daemon_log("M INFO: message '".@{$hit}[0]."' is prepared for delivery to receiver '$receiver'", 5);
2093 }
2095 # set incoming message to flag d=deliverd
2096 $sql_statement = "UPDATE $messaging_tn SET flag='p' WHERE id='$message_id'";
2097 &daemon_log("M DEBUG: $sql_statement", 7);
2098 $res = $messaging_db->update_dbentry($sql_statement);
2099 &daemon_log("M INFO: message '$message_id' is set to flag 'p' (processed)", 5);
2100 }
2102 $kernel->delay_set('watch_for_new_messages', $messaging_db_loop_delay);
2103 return;
2104 }
2106 sub watch_for_delivery_messages {
2107 my ($kernel, $heap) = @_[KERNEL, HEAP];
2109 # select outgoing messages
2110 my $sql_statement = "SELECT * FROM $messaging_tn WHERE ( flag='p' AND direction='out' )";
2111 my $res = $messaging_db->exec_statement( $sql_statement );
2113 # build out msg for each usr
2114 foreach my $hit (@{$res}) {
2115 my $receiver = @{$hit}[3];
2116 my $msg_id = @{$hit}[0];
2117 my $subject = @{$hit}[1];
2118 my $message = @{$hit}[7];
2120 # resolve usr -> host where usr is logged in
2121 my $sql = "SELECT * FROM $login_users_tn WHERE (user='$receiver')";
2122 my $res = $login_users_db->exec_statement($sql);
2124 # receiver is logged in nowhere
2125 if (not ref(@$res[0]) eq "ARRAY") { next; }
2127 # receiver ist logged in at a client registered at local server
2128 my $send_succeed = 0;
2129 foreach my $hit (@$res) {
2130 my $receiver_host = @$hit[0];
2131 my $delivered2host = 0;
2132 &daemon_log("M DEBUG: user '$receiver' is logged in at host '$receiver_host'", 7);
2134 # Looking for host in know_clients_db
2135 my $sql = "SELECT * FROM $known_clients_tn WHERE (hostname='$receiver_host')";
2136 my $res = $known_clients_db->exec_statement($sql);
2138 # Host is known in known_clients_db
2139 if (ref(@$res[0]) eq "ARRAY") {
2140 my $receiver_key = @{@{$res}[0]}[2];
2141 my %data = ('subject' => $subject, 'message' => $message, 'usr' => $receiver);
2142 my $out_msg = &build_msg("usr_msg", $server_address, $receiver_host, \%data );
2143 my $error = &send_msg_to_target($out_msg, $receiver_host, $receiver_key, "usr_msg", 0);
2144 if ($error == 0 ) {
2145 $send_succeed++ ;
2146 $delivered2host++ ;
2147 &daemon_log("M DEBUG: send message for user '$receiver' to host '$receiver_host'", 7);
2148 } else {
2149 &daemon_log("M DEBUG: cannot send message for user '$receiver' to host '$receiver_host'", 7);
2150 }
2151 }
2153 # Message already send, do not need to do anything more, otherwise ...
2154 if ($delivered2host) { next;}
2156 # ...looking for host in foreign_clients_db
2157 $sql = "SELECT * FROM $foreign_clients_tn WHERE (hostname='$receiver_host')";
2158 $res = $foreign_clients_db->exec_statement($sql);
2160 # Host is known in foreign_clients_db
2161 if (ref(@$res[0]) eq "ARRAY") {
2162 my $registration_server = @{@{$res}[0]}[2];
2164 # Fetch encryption key for registration server
2165 my $sql = "SELECT * FROM $known_server_tn WHERE (hostname='$registration_server')";
2166 my $res = $known_server_db->exec_statement($sql);
2167 if (ref(@$res[0]) eq "ARRAY") {
2168 my $registration_server_key = @{@{$res}[0]}[3];
2169 my %data = ('subject' => $subject, 'message' => $message, 'usr' => $receiver);
2170 my $out_msg = &build_msg("usr_msg", $server_address, $receiver_host, \%data );
2171 my $error = &send_msg_to_target($out_msg, $registration_server, $registration_server_key, "usr_msg", 0);
2172 if ($error == 0 ) {
2173 $send_succeed++ ;
2174 $delivered2host++ ;
2175 &daemon_log("M DEBUG: send message for user '$receiver' to server '$registration_server'", 7);
2176 } else {
2177 &daemon_log("M ERROR: cannot send message for user '$receiver' to server '$registration_server'", 1);
2178 }
2180 } else {
2181 &daemon_log("M ERROR: host '$receiver_host' is reported to be ".
2182 "registrated at server '$registration_server', ".
2183 "but no data available in known_server_db ", 1);
2184 }
2185 }
2187 if (not $delivered2host) {
2188 &daemon_log("M ERROR: unable to send user message to host '$receiver_host'", 1);
2189 }
2190 }
2192 if ($send_succeed) {
2193 # set outgoing msg at db to deliverd
2194 my $sql = "UPDATE $messaging_tn SET flag='d' WHERE (id='$msg_id' AND direction='out' AND message_to='$receiver')";
2195 my $res = $messaging_db->exec_statement($sql);
2196 &daemon_log("M INFO: send message for user '$receiver' to logged in hosts", 5);
2197 } else {
2198 &daemon_log("M WARNING: failed to deliver message for user '$receiver'", 3);
2199 }
2200 }
2202 $kernel->delay_set('watch_for_delivery_messages', $messaging_db_loop_delay);
2203 return;
2204 }
2207 sub watch_for_done_messages {
2208 my ($kernel,$heap) = @_[KERNEL, HEAP];
2210 my $sql = "SELECT * FROM $messaging_tn WHERE (flag='p' AND direction='in')";
2211 my $res = $messaging_db->exec_statement($sql);
2213 foreach my $hit (@{$res}) {
2214 my $msg_id = @{$hit}[0];
2216 my $sql = "SELECT * FROM $messaging_tn WHERE (id='$msg_id' AND direction='out' AND (NOT flag='s'))";
2217 my $res = $messaging_db->exec_statement($sql);
2219 # not all usr msgs have been seen till now
2220 if ( ref(@$res[0]) eq "ARRAY") { next; }
2222 $sql = "DELETE FROM $messaging_tn WHERE (id='$msg_id')";
2223 $res = $messaging_db->exec_statement($sql);
2225 }
2227 $kernel->delay_set('watch_for_done_messages', $messaging_db_loop_delay);
2228 return;
2229 }
2232 sub watch_for_old_known_clients {
2233 my ($kernel,$heap) = @_[KERNEL, HEAP];
2235 my $sql_statement = "SELECT * FROM $known_clients_tn";
2236 my $res = $known_clients_db->select_dbentry( $sql_statement );
2238 my $cur_time = int(&get_time());
2240 while ( my ($hit_num, $hit) = each %$res) {
2241 my $expired_timestamp = int($hit->{'timestamp'});
2242 $expired_timestamp =~ /(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/;
2243 my $dt = DateTime->new( year => $1,
2244 month => $2,
2245 day => $3,
2246 hour => $4,
2247 minute => $5,
2248 second => $6,
2249 );
2251 $dt->add( seconds => 2 * int($hit->{'keylifetime'}) );
2252 $expired_timestamp = $dt->ymd('').$dt->hms('');
2253 if ($cur_time > $expired_timestamp) {
2254 my $hostname = $hit->{'hostname'};
2255 my $del_sql = "DELETE FROM $known_clients_tn WHERE hostname='$hostname'";
2256 my $del_res = $known_clients_db->exec_statement($del_sql);
2258 &main::daemon_log("0 INFO: timestamp '".$hit->{'timestamp'}."' of client '$hostname' is expired('$expired_timestamp'), client will be deleted from known_clients_db", 5);
2259 }
2261 }
2263 $kernel->delay_set('watch_for_old_known_clients', $job_queue_loop_delay);
2264 }
2267 sub watch_for_next_tasks {
2268 my ($kernel,$heap) = @_[KERNEL, HEAP];
2270 my $sql = "SELECT * FROM $incoming_tn";
2271 my $res = $incoming_db->select_dbentry($sql);
2273 while ( my ($hit_num, $hit) = each %$res) {
2274 my $headertag = $hit->{'headertag'};
2275 if ($headertag =~ /^answer_(\d+)/) {
2276 # do not start processing, this message is for a still running POE::Wheel
2277 next;
2278 }
2279 my $message_id = $hit->{'id'};
2280 my $session_id = $hit->{'sessionid'};
2281 &daemon_log("$session_id DEBUG: start processing for message with incoming id: '$message_id'", 11);
2283 $kernel->yield('next_task', $hit);
2285 my $sql = "DELETE FROM $incoming_tn WHERE id=$message_id";
2286 my $res = $incoming_db->exec_statement($sql);
2287 }
2288 }
2291 sub get_ldap_handle {
2292 my ($session_id) = @_;
2293 my $heap;
2295 if (not defined $session_id ) { $session_id = 0 };
2296 if ($session_id =~ /[^0-9]*/) { $session_id = 0 };
2298 my ($package, $file, $row, $subroutine, $hasArgs, $wantArray, $evalText, $isRequire) = caller(1);
2299 my $caller_text = "subroutine $subroutine";
2300 if ($subroutine eq "(eval)") {
2301 $caller_text = "eval block within file '$file' for '$evalText'";
2302 }
2303 daemon_log("$session_id DEBUG: new ldap handle for '$caller_text' required!", 42);
2305 get_handle:
2306 my $ldap_handle = Net::LDAP->new( $ldap_uri );
2307 if (not ref $ldap_handle) {
2308 daemon_log("$session_id ERROR: Connection to LDAP URI '$ldap_uri' failed! Retrying in $ldap_retry_sec seconds.", 1);
2309 sleep($ldap_retry_sec);
2310 goto get_handle;
2311 } else {
2312 daemon_log("$session_id DEBUG: Connection to LDAP URI '$ldap_uri' established.", 42);
2313 }
2315 $ldap_handle->bind($ldap_admin_dn, password => $ldap_admin_password) or &daemon_log("$session_id ERROR: Could not bind as '$ldap_admin_dn' to LDAP URI '$ldap_uri'!", 1);
2316 return $ldap_handle;
2317 }
2320 sub release_ldap_handle {
2321 my ($ldap_handle, $session_id) = @_ ;
2322 if (not defined $session_id ) { $session_id = 0 };
2324 if(ref $ldap_handle) {
2325 $ldap_handle->disconnect();
2326 }
2327 &main::daemon_log("$session_id DEBUG: Released a ldap handle!", 42);
2328 return;
2329 }
2332 sub change_fai_state {
2333 my ($st, $targets, $session_id) = @_;
2334 $session_id = 0 if not defined $session_id;
2335 # Set FAI state to localboot
2336 my %mapActions= (
2337 reboot => '',
2338 update => 'softupdate',
2339 localboot => 'localboot',
2340 reinstall => 'install',
2341 rescan => '',
2342 wake => '',
2343 memcheck => 'memcheck',
2344 sysinfo => 'sysinfo',
2345 install => 'install',
2346 );
2348 # Return if this is unknown
2349 if (!exists $mapActions{ $st }){
2350 daemon_log("$session_id ERROR: unknown action '$st', can not translate ot FAIstate", 1);
2351 return;
2352 }
2354 my $state= $mapActions{ $st };
2356 # Build search filter for hosts
2357 my $search= "(&(objectClass=GOhard)";
2358 foreach (@{$targets}){
2359 $search.= "(macAddress=$_)";
2360 }
2361 $search.= ")";
2363 # If there's any host inside of the search string, procress them
2364 if (!($search =~ /macAddress/)){
2365 daemon_log("$session_id ERROR: no macAddress found in filter statement for LDAP search: '$search'", 1);
2366 return;
2367 }
2369 my $ldap_handle = &get_ldap_handle($session_id);
2370 # Perform search for Unit Tag
2371 my $mesg = $ldap_handle->search(
2372 base => $ldap_base,
2373 scope => 'sub',
2374 attrs => ['dn', 'FAIstate', 'objectClass'],
2375 filter => "$search"
2376 );
2378 if ($mesg->count) {
2379 my @entries = $mesg->entries;
2380 if (0 == @entries) {
2381 daemon_log("$session_id ERROR: ldap search failed: ldap_base=$ldap_base, filter=$search", 1);
2382 }
2384 foreach my $entry (@entries) {
2385 # Only modify entry if it is not set to '$state'
2386 if ($entry->get_value("FAIstate") ne "$state"){
2387 daemon_log("$session_id INFO: Setting FAIstate to '$state' for ".$entry->dn, 5);
2388 my $result;
2389 my %tmp = map { $_ => 1 } $entry->get_value("objectClass");
2390 if (exists $tmp{'FAIobject'}){
2391 if ($state eq ''){
2392 $result= $ldap_handle->modify($entry->dn, changes => [ delete => [ FAIstate => [] ] ]);
2393 } else {
2394 $result= $ldap_handle->modify($entry->dn, changes => [ replace => [ FAIstate => $state ] ]);
2395 }
2396 } elsif ($state ne ''){
2397 $result= $ldap_handle->modify($entry->dn, changes => [ add => [ objectClass => 'FAIobject' ], add => [ FAIstate => $state ] ]);
2398 }
2400 # Errors?
2401 if ($result->code){
2402 daemon_log("$session_id Error: Setting FAIstate to '$state' for ".$entry->dn. "failed: ".$result->error, 1);
2403 }
2404 } else {
2405 daemon_log("$session_id DEBUG FAIstate at host '".$entry->dn."' already at state '$st'", 42);
2406 }
2407 }
2408 } else {
2409 daemon_log("$session_id ERROR: LDAP search failed: ldap_base=$ldap_base, filter=$search", 1);
2410 }
2411 &release_ldap_handle($ldap_handle, $session_id);
2413 return;
2414 }
2417 sub change_goto_state {
2418 my ($st, $targets, $session_id) = @_;
2419 $session_id = 0 if not defined $session_id;
2421 # Switch on or off?
2422 my $state= $st eq 'active' ? 'active': 'locked';
2424 my $ldap_handle = &get_ldap_handle($session_id);
2425 if( defined($ldap_handle) ) {
2427 # Build search filter for hosts
2428 my $search= "(&(objectClass=GOhard)";
2429 foreach (@{$targets}){
2430 $search.= "(macAddress=$_)";
2431 }
2432 $search.= ")";
2434 # If there's any host inside of the search string, procress them
2435 if (!($search =~ /macAddress/)){
2436 &release_ldap_handle($ldap_handle);
2437 return;
2438 }
2440 # Perform search for Unit Tag
2441 my $mesg = $ldap_handle->search(
2442 base => $ldap_base,
2443 scope => 'sub',
2444 attrs => ['dn', 'gotoMode'],
2445 filter => "$search"
2446 );
2448 if ($mesg->count) {
2449 my @entries = $mesg->entries;
2450 foreach my $entry (@entries) {
2452 # Only modify entry if it is not set to '$state'
2453 if ($entry->get_value("gotoMode") ne $state){
2455 daemon_log("$session_id INFO: Setting gotoMode to '$state' for ".$entry->dn, 5);
2456 my $result;
2457 $result= $ldap_handle->modify($entry->dn, changes => [replace => [ gotoMode => $state ] ]);
2459 # Errors?
2460 if ($result->code){
2461 &daemon_log("$session_id Error: Setting gotoMode to '$state' for ".$entry->dn. "failed: ".$result->error, 1);
2462 }
2464 }
2465 }
2466 } else {
2467 daemon_log("$session_id ERROR: LDAP search failed in function change_goto_state: ldap_base=$ldap_base, filter=$search", 1);
2468 }
2470 }
2471 &release_ldap_handle($ldap_handle, $session_id);
2472 return;
2473 }
2476 sub run_recreate_packages_db {
2477 my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
2478 my $session_id = $session->ID;
2479 &main::daemon_log("$session_id INFO: Recreating FAI Packages DB ('$fai_release_tn', '$fai_server_tn', '$packages_list_tn')", 5);
2480 $kernel->yield('create_fai_release_db', $fai_release_tn);
2481 $kernel->yield('create_fai_server_db', $fai_server_tn);
2482 return;
2483 }
2486 sub run_create_fai_server_db {
2487 my ($kernel, $session, $heap, $table_name) = @_[KERNEL, SESSION, HEAP, ARG0];
2488 my $session_id = $session->ID;
2489 my $task = POE::Wheel::Run->new(
2490 Program => sub { &create_fai_server_db($table_name,$kernel, undef, $session_id) },
2491 StdoutEvent => "session_run_result",
2492 StderrEvent => "session_run_debug",
2493 CloseEvent => "session_run_done",
2494 );
2496 $heap->{task}->{ $task->ID } = $task;
2497 return;
2498 }
2501 sub create_fai_server_db {
2502 my ($table_name, $kernel, $dont_create_packages_list, $session_id) = @_;
2503 my $result;
2505 if (not defined $session_id) { $session_id = 0; }
2506 my $ldap_handle = &get_ldap_handle($session_id);
2507 if(defined($ldap_handle)) {
2508 daemon_log("$session_id INFO: create_fai_server_db: start", 5);
2509 my $mesg= $ldap_handle->search(
2510 base => $ldap_base,
2511 scope => 'sub',
2512 attrs => ['FAIrepository', 'gosaUnitTag'],
2513 filter => "(&(FAIrepository=*)(objectClass=FAIrepositoryServer))",
2514 );
2515 if($mesg->{'resultCode'} == 0 &&
2516 $mesg->count != 0) {
2517 foreach my $entry (@{$mesg->{entries}}) {
2518 if($entry->exists('FAIrepository')) {
2519 # Add an entry for each Repository configured for server
2520 foreach my $repo(@{$entry->get_value('FAIrepository', asref => 1)}) {
2521 my($tmp_url,$tmp_server,$tmp_release,$tmp_sections) = split(/\|/, $repo);
2522 my $tmp_tag= $entry->get_value('gosaUnitTag') || "";
2523 $result= $fai_server_db->add_dbentry( {
2524 table => $table_name,
2525 primkey => ['server', 'fai_release', 'tag'],
2526 server => $tmp_url,
2527 fai_release => $tmp_release,
2528 sections => $tmp_sections,
2529 tag => (length($tmp_tag)>0)?$tmp_tag:"",
2530 } );
2531 }
2532 }
2533 }
2534 }
2535 daemon_log("$session_id INFO: create_fai_server_db: finished", 5);
2536 &release_ldap_handle($ldap_handle);
2538 # TODO: Find a way to post the 'create_packages_list_db' event
2539 if(not defined($dont_create_packages_list)) {
2540 &create_packages_list_db(undef, $session_id);
2541 }
2542 }
2544 return $result;
2545 }
2548 sub run_create_fai_release_db {
2549 my ($kernel, $session, $heap, $table_name) = @_[KERNEL, SESSION, HEAP, ARG0];
2550 my $session_id = $session->ID;
2551 my $task = POE::Wheel::Run->new(
2552 Program => sub { &create_fai_release_db($table_name, $session_id) },
2553 StdoutEvent => "session_run_result",
2554 StderrEvent => "session_run_debug",
2555 CloseEvent => "session_run_done",
2556 );
2558 $heap->{task}->{ $task->ID } = $task;
2559 return;
2560 }
2563 sub create_fai_release_db {
2564 my ($table_name, $session_id) = @_;
2565 my $result;
2567 # used for logging
2568 if (not defined $session_id) { $session_id = 0; }
2570 my $ldap_handle = &get_ldap_handle($session_id);
2571 if(defined($ldap_handle)) {
2572 daemon_log("$session_id INFO: create_fai_release_db: start",5);
2573 my $mesg= $ldap_handle->search(
2574 base => $ldap_base,
2575 scope => 'sub',
2576 attrs => [],
2577 filter => "(&(objectClass=organizationalUnit)(ou=fai))",
2578 );
2579 if(($mesg->code == 0) && ($mesg->count != 0))
2580 {
2581 daemon_log("$session_id DEBUG: create_fai_release_db: count " . $mesg->count,138);
2583 # Walk through all possible FAI container ou's
2584 my @sql_list;
2585 my $timestamp= &get_time();
2586 foreach my $ou (@{$mesg->{entries}}) {
2587 my $tmp_classes= resolve_fai_classes($ou->dn, $ldap_handle, $session_id);
2588 if(defined($tmp_classes) && ref($tmp_classes) eq 'HASH') {
2589 my @tmp_array=get_fai_release_entries($tmp_classes);
2590 if(@tmp_array) {
2591 foreach my $entry (@tmp_array) {
2592 if(defined($entry) && ref($entry) eq 'HASH') {
2593 my $sql=
2594 "INSERT INTO $table_name "
2595 ."(timestamp, fai_release, class, type, state) VALUES ("
2596 .$timestamp.","
2597 ."'".$entry->{'release'}."',"
2598 ."'".$entry->{'class'}."',"
2599 ."'".$entry->{'type'}."',"
2600 ."'".$entry->{'state'}."')";
2601 push @sql_list, $sql;
2602 }
2603 }
2604 }
2605 }
2606 }
2608 daemon_log("$session_id DEBUG: create_fai_release_db: Inserting ".scalar @sql_list." entries to DB",138);
2609 &release_ldap_handle($ldap_handle);
2610 if(@sql_list) {
2611 unshift @sql_list, "VACUUM";
2612 unshift @sql_list, "DELETE FROM $table_name";
2613 $fai_release_db->exec_statementlist(\@sql_list);
2614 }
2615 daemon_log("$session_id DEBUG: create_fai_release_db: Done with inserting",138);
2616 } else {
2617 daemon_log("$session_id INFO: create_fai_release_db: error: " . $mesg->code, 5);
2618 }
2619 daemon_log("$session_id INFO: create_fai_release_db: finished",5);
2620 }
2621 return $result;
2622 }
2624 sub get_fai_types {
2625 my $tmp_classes = shift || return undef;
2626 my @result;
2628 foreach my $type(keys %{$tmp_classes}) {
2629 if(defined($tmp_classes->{$type}[0]) && (!($tmp_classes->{$type}[0] =~ /^.*?removed.*?$/))) {
2630 my $entry = {
2631 type => $type,
2632 state => $tmp_classes->{$type}[0],
2633 };
2634 push @result, $entry;
2635 }
2636 }
2638 return @result;
2639 }
2641 sub get_fai_state {
2642 my $result = "";
2643 my $tmp_classes = shift || return $result;
2645 foreach my $type(keys %{$tmp_classes}) {
2646 if(defined($tmp_classes->{$type}[0])) {
2647 $result = $tmp_classes->{$type}[0];
2649 # State is equal for all types in class
2650 last;
2651 }
2652 }
2654 return $result;
2655 }
2657 sub resolve_fai_classes {
2658 my ($fai_base, $ldap_handle, $session_id) = @_;
2659 if (not defined $session_id) { $session_id = 0; }
2660 my $result;
2661 my @possible_fai_classes= ("FAIscript", "FAIhook", "FAIpartitionTable", "FAItemplate", "FAIvariable", "FAIprofile", "FAIpackageList");
2662 my $fai_filter= "(|(&(objectClass=FAIclass)(|(objectClass=".join(")(objectClass=", @possible_fai_classes).")))(objectClass=FAIbranch))";
2663 my $fai_classes;
2665 daemon_log("$session_id DEBUG: Searching for FAI entries in base $fai_base", 138);
2666 my $mesg= $ldap_handle->search(
2667 base => $fai_base,
2668 scope => 'sub',
2669 attrs => ['cn','objectClass','FAIstate'],
2670 filter => $fai_filter,
2671 );
2672 daemon_log("$session_id DEBUG: Found ".$mesg->count()." FAI entries", 138);
2674 if($mesg->{'resultCode'} == 0 &&
2675 $mesg->count != 0) {
2676 foreach my $entry (@{$mesg->{entries}}) {
2677 if($entry->exists('cn')) {
2678 my $tmp_dn= $entry->dn();
2679 $tmp_dn= substr( $tmp_dn, 0, length($tmp_dn)
2680 - length($fai_base) - 1 );
2682 # Skip classname and ou dn parts for class
2683 my $tmp_release = ($1) if $tmp_dn =~ /^[^,]+,[^,]+,(.*?)$/;
2685 # Skip classes without releases
2686 if((!defined($tmp_release)) || length($tmp_release)==0) {
2687 next;
2688 }
2690 my $tmp_cn= $entry->get_value('cn');
2691 my $tmp_state= $entry->get_value('FAIstate');
2693 my $tmp_type;
2694 # Get FAI type
2695 for my $oclass(@{$entry->get_value('objectClass', asref => 1)}) {
2696 if(grep $_ eq $oclass, @possible_fai_classes) {
2697 $tmp_type= $oclass;
2698 last;
2699 }
2700 }
2702 if($tmp_release =~ /^.*?,.*?$/ && (!($tmp_release =~ /^.*?\\,.*?$/))) {
2703 # A Subrelease
2704 my @sub_releases = split(/,/, $tmp_release);
2706 # Walk through subreleases and build hash tree
2707 my $hash;
2708 while(my $tmp_sub_release = pop @sub_releases) {
2709 $hash .= "\{'$tmp_sub_release'\}->";
2710 }
2711 eval('push @{$fai_classes->'.$hash.'{$tmp_cn}->{$tmp_type}}, (defined($tmp_state) && length($tmp_state)>0)?$tmp_state:"";');
2712 } else {
2713 # A branch, no subrelease
2714 push @{$fai_classes->{$tmp_release}->{$tmp_cn}->{$tmp_type}}, (defined($tmp_state) && length($tmp_state)>0)?$tmp_state:"";
2715 }
2716 } elsif (!$entry->exists('cn')) {
2717 my $tmp_dn= $entry->dn();
2718 $tmp_dn= substr( $tmp_dn, 0, length($tmp_dn)
2719 - length($fai_base) - 1 );
2720 my $tmp_release = ($1) if $tmp_dn =~ /^(.*?)$/;
2722 # Skip classes without releases
2723 if((!defined($tmp_release)) || length($tmp_release)==0) {
2724 next;
2725 }
2727 if($tmp_release =~ /^.*?,.*?$/ && (!($tmp_release =~ /^.*?\\,.*?$/))) {
2728 # A Subrelease
2729 my @sub_releases= split(/,/, $tmp_release);
2731 # Walk through subreleases and build hash tree
2732 my $hash;
2733 while(my $tmp_sub_release = pop @sub_releases) {
2734 $hash .= "\{'$tmp_sub_release'\}->";
2735 }
2736 # Remove the last two characters
2737 chop($hash);
2738 chop($hash);
2740 eval('$fai_classes->'.$hash.'= {}');
2741 } else {
2742 # A branch, no subrelease
2743 if(!exists($fai_classes->{$tmp_release})) {
2744 $fai_classes->{$tmp_release} = {};
2745 }
2746 }
2747 }
2748 }
2750 # The hash is complete, now we can honor the copy-on-write based missing entries
2751 foreach my $release (keys %$fai_classes) {
2752 $result->{$release}= deep_copy(apply_fai_inheritance($fai_classes->{$release}));
2753 }
2754 }
2755 return $result;
2756 }
2758 sub apply_fai_inheritance {
2759 my $fai_classes = shift || return {};
2760 my $tmp_classes;
2762 # Get the classes from the branch
2763 foreach my $class (keys %{$fai_classes}) {
2764 # Skip subreleases
2765 if($class =~ /^ou=.*$/) {
2766 next;
2767 } else {
2768 $tmp_classes->{$class}= deep_copy($fai_classes->{$class});
2769 }
2770 }
2772 # Apply to each subrelease
2773 foreach my $subrelease (keys %{$fai_classes}) {
2774 if($subrelease =~ /ou=/) {
2775 foreach my $tmp_class (keys %{$tmp_classes}) {
2776 if(!exists($fai_classes->{$subrelease}->{$tmp_class})) {
2777 $fai_classes->{$subrelease}->{$tmp_class} =
2778 deep_copy($tmp_classes->{$tmp_class});
2779 } else {
2780 foreach my $type (keys %{$tmp_classes->{$tmp_class}}) {
2781 if(!exists($fai_classes->{$subrelease}->{$tmp_class}->{$type})) {
2782 $fai_classes->{$subrelease}->{$tmp_class}->{$type}=
2783 deep_copy($tmp_classes->{$tmp_class}->{$type});
2784 }
2785 }
2786 }
2787 }
2788 }
2789 }
2791 # Find subreleases in deeper levels
2792 foreach my $subrelease (keys %{$fai_classes}) {
2793 if($subrelease =~ /ou=/) {
2794 foreach my $subsubrelease (keys %{$fai_classes->{$subrelease}}) {
2795 if($subsubrelease =~ /ou=/) {
2796 apply_fai_inheritance($fai_classes->{$subrelease});
2797 }
2798 }
2799 }
2800 }
2802 return $fai_classes;
2803 }
2805 sub get_fai_release_entries {
2806 my $tmp_classes = shift || return;
2807 my $parent = shift || "";
2808 my @result = shift || ();
2810 foreach my $entry (keys %{$tmp_classes}) {
2811 if(defined($entry)) {
2812 if($entry =~ /^ou=.*$/) {
2813 my $release_name = $entry;
2814 $release_name =~ s/ou=//g;
2815 if(length($parent)>0) {
2816 $release_name = $parent."/".$release_name;
2817 }
2818 my @bufentries = get_fai_release_entries($tmp_classes->{$entry}, $release_name, @result);
2819 foreach my $bufentry(@bufentries) {
2820 push @result, $bufentry;
2821 }
2822 } else {
2823 my @types = get_fai_types($tmp_classes->{$entry});
2824 foreach my $type (@types) {
2825 push @result,
2826 {
2827 'class' => $entry,
2828 'type' => $type->{'type'},
2829 'release' => $parent,
2830 'state' => $type->{'state'},
2831 };
2832 }
2833 }
2834 }
2835 }
2837 return @result;
2838 }
2840 sub deep_copy {
2841 my $this = shift;
2842 if (not ref $this) {
2843 $this;
2844 } elsif (ref $this eq "ARRAY") {
2845 [map deep_copy($_), @$this];
2846 } elsif (ref $this eq "HASH") {
2847 +{map { $_ => deep_copy($this->{$_}) } keys %$this};
2848 } else { die "what type is $_?" }
2849 }
2852 sub session_run_result {
2853 my ($kernel, $heap, $client_answer) = @_[KERNEL, HEAP, ARG0];
2854 $kernel->sig(CHLD => "child_reap");
2855 }
2857 sub session_run_debug {
2858 my $result = $_[ARG0];
2859 print STDERR "$result\n";
2860 }
2862 sub session_run_done {
2863 my ( $kernel, $heap, $task_id ) = @_[ KERNEL, HEAP, ARG0 ];
2864 delete $heap->{task}->{$task_id};
2865 if (exists $heap->{ldap_handle}->{$task_id}) {
2866 &release_ldap_handle($heap->{ldap_handle}->{$task_id});
2867 }
2868 delete $heap->{ldap_handle}->{$task_id};
2869 }
2872 sub create_sources_list {
2873 my $session_id = shift || 0;
2874 my $result="/tmp/gosa_si_tmp_sources_list";
2876 # Remove old file
2877 if(stat($result)) {
2878 unlink($result);
2879 &main::daemon_log("$session_id DEBUG: remove an old version of '$result'", 7);
2880 }
2882 open(my $fh, ">", "$result");
2883 if (not defined $fh) {
2884 &main::daemon_log("$session_id DEBUG: cannot open '$result' for writing", 7);
2885 return undef;
2886 }
2887 if(defined($main::ldap_server_dn) and length($main::ldap_server_dn) > 0) {
2888 my $ldap_handle = &get_ldap_handle($session_id);
2889 my $mesg=$ldap_handle->search(
2890 base => $main::ldap_server_dn,
2891 scope => 'base',
2892 attrs => 'FAIrepository',
2893 filter => 'objectClass=FAIrepositoryServer'
2894 );
2895 if($mesg->count) {
2896 foreach my $entry(@{$mesg->{'entries'}}) {
2897 foreach my $value(@{$entry->get_value('FAIrepository', asref => 1)}) {
2898 my ($server, $tag, $release, $sections)= split /\|/, $value;
2899 my $line = "deb $server $release";
2900 $sections =~ s/,/ /g;
2901 $line.= " $sections";
2902 print $fh $line."\n";
2903 }
2904 }
2905 }
2906 &release_ldap_handle($ldap_handle);
2907 } else {
2908 if (defined $main::ldap_server_dn){
2909 &main::daemon_log("$session_id ERROR: something wrong with ldap_server_dn '$main::ldap_server_dn', abort create_sources_list", 1);
2910 } else {
2911 &main::daemon_log("$session_id ERROR: no ldap_server_dn found, abort create_sources_list", 1);
2912 }
2913 }
2914 close($fh);
2916 return $result;
2917 }
2920 sub run_create_packages_list_db {
2921 my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
2922 my $session_id = $session->ID;
2923 my $task = POE::Wheel::Run->new(
2924 Priority => +20,
2925 Program => sub {&create_packages_list_db(undef, $session_id)},
2926 StdoutEvent => "session_run_result",
2927 StderrEvent => "session_run_debug",
2928 CloseEvent => "session_run_done",
2929 );
2930 $heap->{task}->{ $task->ID } = $task;
2931 }
2934 sub create_packages_list_db {
2935 my ($sources_file, $session_id) = @_;
2937 # it should not be possible to trigger a recreation of packages_list_db
2938 # while packages_list_db is under construction, so set flag packages_list_under_construction
2939 # which is tested befor recreation can be started
2940 if (-r $packages_list_under_construction) {
2941 daemon_log("$session_id WARNING: packages_list_db is right now under construction, please wait until this process is finished", 3);
2942 return;
2943 } else {
2944 daemon_log("$session_id INFO: create_packages_list_db: start", 5);
2945 # set packages_list_under_construction to true
2946 system("touch $packages_list_under_construction");
2947 @packages_list_statements=();
2948 }
2950 if (not defined $session_id) { $session_id = 0; }
2952 if (not defined $sources_file) {
2953 &main::daemon_log("$session_id INFO: no sources_file given for creating packages list so trigger creation of it", 5);
2954 $sources_file = &create_sources_list($session_id);
2955 }
2957 if (not defined $sources_file) {
2958 &main::daemon_log("$session_id ERROR: no sources_file given under '$sources_file', skip create_packages_list_db", 1);
2959 unlink($packages_list_under_construction);
2960 return;
2961 }
2963 my $line;
2965 open(my $CONFIG, "<", "$sources_file") or do {
2966 daemon_log( "$session_id ERROR: create_packages_list_db: Failed to open '$sources_file'", 1);
2967 unlink($packages_list_under_construction);
2968 return;
2969 };
2971 # Read lines
2972 while ($line = <$CONFIG>){
2973 # Unify
2974 chop($line);
2975 $line =~ s/^\s+//;
2976 $line =~ s/^\s+/ /;
2978 # Strip comments
2979 $line =~ s/#.*$//g;
2981 # Skip empty lines
2982 if ($line =~ /^\s*$/){
2983 next;
2984 }
2986 # Interpret deb line
2987 if ($line =~ /^deb [^\s]+\s[^\s]+\s[^\s]+/){
2988 my( $baseurl, $dist, $sections ) = ($line =~ /^deb\s([^\s]+)\s+([^\s]+)\s+(.*)$/);
2989 my $section;
2990 foreach $section (split(' ', $sections)){
2991 &parse_package_info( $baseurl, $dist, $section, $session_id );
2992 }
2993 }
2994 else {
2995 daemon_log("$session_id ERROR: cannot parse line '$line'", 1);
2996 }
2997 }
2999 close ($CONFIG);
3001 if(keys(%repo_dirs)) {
3002 find(\&cleanup_and_extract, keys( %repo_dirs ));
3003 &main::strip_packages_list_statements();
3004 $packages_list_db->exec_statementlist(\@packages_list_statements);
3005 }
3006 unlink($packages_list_under_construction);
3007 daemon_log("$session_id INFO: create_packages_list_db: finished", 5);
3008 return;
3009 }
3011 # This function should do some intensive task to minimize the db-traffic
3012 sub strip_packages_list_statements {
3013 my @existing_entries= @{$packages_list_db->exec_statement("SELECT * FROM $main::packages_list_tn")};
3014 my @new_statement_list=();
3015 my $hash;
3016 my $insert_hash;
3017 my $update_hash;
3018 my $delete_hash;
3019 my $known_packages_hash;
3020 my $local_timestamp=get_time();
3022 foreach my $existing_entry (@existing_entries) {
3023 $hash->{@{$existing_entry}[0]}->{@{$existing_entry}[1]}->{@{$existing_entry}[2]}= $existing_entry;
3024 }
3026 foreach my $statement (@packages_list_statements) {
3027 if($statement =~ /^INSERT/i) {
3028 # Assign the values from the insert statement
3029 my ($distribution,$package,$version,$section,$description,$template,$timestamp) = ($1,$2,$3,$4,$5,$6,$7) if $statement =~
3030 /^INSERT\s+?INTO\s+?$main::packages_list_tn\s+?VALUES\s*?\('(.*?)',\s*?'(.*?)',\s*?'(.*?)',\s*?'(.*?)',\s*?'(.*?)',\s*?'(.*?)',\s*?'(.*?)'\s*?\)$/si;
3031 if(exists($hash->{$distribution}->{$package}->{$version})) {
3032 # If section or description has changed, update the DB
3033 if(
3034 (! (@{$hash->{$distribution}->{$package}->{$version}}[3] eq $section)) or
3035 (! (@{$hash->{$distribution}->{$package}->{$version}}[4] eq $description))
3036 ) {
3037 @{$update_hash->{$distribution}->{$package}->{$version}} = ($distribution,$package,$version,$section,$description,undef);
3038 } else {
3039 # package is already present in database. cache this knowledge for later use
3040 @{$known_packages_hash->{$distribution}->{$package}->{$version}} = ($distribution,$package,$version,$section,$description,$template);
3041 }
3042 } else {
3043 # Insert a non-existing entry to db
3044 @{$insert_hash->{$distribution}->{$package}->{$version}} = ($distribution,$package,$version,$section,$description,$template);
3045 }
3046 } elsif ($statement =~ /^UPDATE/i) {
3047 my ($template,$package,$version) = ($1,$2,$3) if $statement =~
3048 /^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;
3049 foreach my $distribution (keys %{$hash}) {
3050 if(exists($insert_hash->{$distribution}->{$package}->{$version})) {
3051 # update the insertion hash to execute only one query per package (insert instead insert+update)
3052 @{$insert_hash->{$distribution}->{$package}->{$version}}[5]= $template;
3053 } elsif(exists($hash->{$distribution}->{$package}->{$version})) {
3054 if( ! (@{$hash->{$distribution}->{$package}->{$version}}[5] eq $template)) {
3055 my $section;
3056 my $description;
3057 if(defined(@{$update_hash->{$distribution}->{$package}->{$version}}[3]) and
3058 length(@{$update_hash->{$distribution}->{$package}->{$version}}[3]) > 0 ) {
3059 $section= @{$update_hash->{$distribution}->{$package}->{$version}}[3];
3060 }
3061 if(defined(@{$update_hash->{$distribution}->{$package}->{$version}}[4])) {
3062 $description= @{$update_hash->{$distribution}->{$package}->{$version}}[4];
3063 }
3064 @{$update_hash->{$distribution}->{$package}->{$version}} = ($distribution,$package,$version,$section,$description,$template);
3065 }
3066 }
3067 }
3068 }
3069 }
3071 # Check for orphaned entries
3072 foreach my $existing_entry (@existing_entries) {
3073 my $distribution= @{$existing_entry}[0];
3074 my $package= @{$existing_entry}[1];
3075 my $version= @{$existing_entry}[2];
3076 my $section= @{$existing_entry}[3];
3078 if(
3079 exists($insert_hash->{$distribution}->{$package}->{$version}) ||
3080 exists($update_hash->{$distribution}->{$package}->{$version}) ||
3081 exists($known_packages_hash->{$distribution}->{$package}->{$version})
3082 ) {
3083 next;
3084 } else {
3085 # Insert entry to delete hash
3086 @{$delete_hash->{$distribution}->{$package}->{$version}} = ($distribution,$package,$version,$section);
3087 }
3088 }
3090 # unroll the insert hash
3091 foreach my $distribution (keys %{$insert_hash}) {
3092 foreach my $package (keys %{$insert_hash->{$distribution}}) {
3093 foreach my $version (keys %{$insert_hash->{$distribution}->{$package}}) {
3094 push @new_statement_list, "INSERT INTO $main::packages_list_tn VALUES ('$distribution','$package','$version',"
3095 ."'@{$insert_hash->{$distribution}->{$package}->{$version}}[3]',"
3096 ."'@{$insert_hash->{$distribution}->{$package}->{$version}}[4]',"
3097 ."'@{$insert_hash->{$distribution}->{$package}->{$version}}[5]',"
3098 ."'$local_timestamp')";
3099 }
3100 }
3101 }
3103 # unroll the update hash
3104 foreach my $distribution (keys %{$update_hash}) {
3105 foreach my $package (keys %{$update_hash->{$distribution}}) {
3106 foreach my $version (keys %{$update_hash->{$distribution}->{$package}}) {
3107 my $set = "";
3108 if(defined(@{$update_hash->{$distribution}->{$package}->{$version}}[3])) {
3109 $set .= "section = '@{$update_hash->{$distribution}->{$package}->{$version}}[3]', ";
3110 }
3111 if(defined(@{$update_hash->{$distribution}->{$package}->{$version}}[4])) {
3112 $set .= "description = '@{$update_hash->{$distribution}->{$package}->{$version}}[4]', ";
3113 }
3114 if(defined(@{$update_hash->{$distribution}->{$package}->{$version}}[5])) {
3115 $set .= "template = '@{$update_hash->{$distribution}->{$package}->{$version}}[5]', ";
3116 }
3117 if(defined($set) and length($set) > 0) {
3118 $set .= "timestamp = '$local_timestamp'";
3119 } else {
3120 next;
3121 }
3122 push @new_statement_list,
3123 "UPDATE $main::packages_list_tn SET $set WHERE"
3124 ." distribution = '$distribution'"
3125 ." AND package = '$package'"
3126 ." AND version = '$version'";
3127 }
3128 }
3129 }
3131 # unroll the delete hash
3132 foreach my $distribution (keys %{$delete_hash}) {
3133 foreach my $package (keys %{$delete_hash->{$distribution}}) {
3134 foreach my $version (keys %{$delete_hash->{$distribution}->{$package}}) {
3135 my $section = @{$delete_hash->{$distribution}->{$package}->{$version}}[3];
3136 push @new_statement_list, "DELETE FROM $main::packages_list_tn WHERE distribution='$distribution' AND package='$package' AND version='$version' AND section='$section'";
3137 }
3138 }
3139 }
3141 unshift(@new_statement_list, "VACUUM");
3143 @packages_list_statements = @new_statement_list;
3144 }
3147 sub parse_package_info {
3148 my ($baseurl, $dist, $section, $session_id)= @_;
3149 my ($package);
3150 if (not defined $session_id) { $session_id = 0; }
3151 my ($path) = ($baseurl =~ m%://[^/]*(.*)$%);
3152 $repo_dirs{ "${repo_path}/pool" } = 1;
3154 foreach $package ("Packages.gz"){
3155 daemon_log("$session_id DEBUG: create_packages_list: fetch $baseurl, $dist, $section", 266);
3156 get_package( "$baseurl/dists/$dist/$section/binary-$arch/$package", "$outdir/$dist/$section", $session_id );
3157 parse_package( "$outdir/$dist/$section", $dist, $path, $session_id );
3158 }
3160 }
3163 sub get_package {
3164 my ($url, $dest, $session_id)= @_;
3165 if (not defined $session_id) { $session_id = 0; }
3167 my $tpath = dirname($dest);
3168 -d "$tpath" || mkpath "$tpath";
3170 # This is ugly, but I've no time to take a look at "how it works in perl"
3171 if(0 == system("wget '$url' -O '$dest' 2>/dev/null") ) {
3172 system("gunzip -cd '$dest' > '$dest.in'");
3173 daemon_log("$session_id DEBUG: run command: gunzip -cd '$dest' > '$dest.in'", 266);
3174 unlink($dest);
3175 daemon_log("$session_id DEBUG: delete file '$dest'", 266);
3176 } else {
3177 daemon_log("$session_id ERROR: create_packages_list_db: get_packages: fetching '$url' into '$dest' failed!", 1);
3178 }
3179 return 0;
3180 }
3183 sub parse_package {
3184 my ($path, $dist, $srv_path, $session_id)= @_;
3185 if (not defined $session_id) { $session_id = 0;}
3186 my ($package, $version, $section, $description);
3187 my $timestamp = &get_time();
3189 if(not stat("$path.in")) {
3190 daemon_log("$session_id ERROR: create_packages_list: parse_package: file '$path.in' is not readable",1);
3191 return;
3192 }
3194 open(my $PACKAGES, "<", "$path.in");
3195 if(not defined($PACKAGES)) {
3196 daemon_log("$session_id ERROR: create_packages_list_db: parse_package: cannot open '$path.in'",1);
3197 return;
3198 }
3200 # Read lines
3201 while (<$PACKAGES>){
3202 my $line = $_;
3203 # Unify
3204 chop($line);
3206 # Use empty lines as a trigger
3207 if ($line =~ /^\s*$/){
3208 my $sql = "INSERT INTO packages_list VALUES ('$dist', '$package', '$version', '$section', '$description', '', '$timestamp')";
3209 push(@packages_list_statements, $sql);
3210 $package = "none";
3211 $version = "none";
3212 $section = "none";
3213 $description = "none";
3214 next;
3215 }
3217 # Trigger for package name
3218 if ($line =~ /^Package:\s/){
3219 ($package)= ($line =~ /^Package: (.*)$/);
3220 next;
3221 }
3223 # Trigger for version
3224 if ($line =~ /^Version:\s/){
3225 ($version)= ($line =~ /^Version: (.*)$/);
3226 next;
3227 }
3229 # Trigger for description
3230 if ($line =~ /^Description:\s/){
3231 ($description)= &encode_base64(($line =~ /^Description: (.*)$/));
3232 next;
3233 }
3235 # Trigger for section
3236 if ($line =~ /^Section:\s/){
3237 ($section)= ($line =~ /^Section: (.*)$/);
3238 next;
3239 }
3241 # Trigger for filename
3242 if ($line =~ /^Filename:\s/){
3243 my ($filename) = ($line =~ /^Filename: (.*)$/);
3244 store_fileinfo( $package, $filename, $dist, $srv_path, $version, $repo_path );
3245 next;
3246 }
3247 }
3249 close( $PACKAGES );
3250 unlink( "$path.in" );
3251 }
3254 sub store_fileinfo {
3255 my( $package, $file, $dist, $path, $vers, $srvdir) = @_;
3257 my %fileinfo = (
3258 'package' => $package,
3259 'dist' => $dist,
3260 'version' => $vers,
3261 );
3263 $repo_files{ "${srvdir}/$file" } = \%fileinfo;
3264 }
3267 sub cleanup_and_extract {
3268 my $fileinfo = $repo_files{ $File::Find::name };
3270 if( defined $fileinfo ) {
3271 my $dir = "$outdir/$fileinfo->{ 'dist' }/debconf.d";
3272 my $sql;
3273 my $package = $fileinfo->{ 'package' };
3274 my $newver = $fileinfo->{ 'version' };
3276 mkpath($dir);
3277 system( "dpkg -e '$File::Find::name' '$dir/DEBIAN'" );
3279 if( -f "$dir/DEBIAN/templates" ) {
3281 daemon_log("0 DEBUG: Found debconf templates in '$package' - $newver", 266);
3283 my $tmpl= ""; {
3284 local $/=undef;
3285 open(my $FILE, "$dir/DEBIAN/templates");
3286 $tmpl = &encode_base64(<$FILE>);
3287 close($FILE);
3288 }
3289 rmtree("$dir/DEBIAN/templates");
3291 $sql= "update $main::packages_list_tn set template = '$tmpl' where package = '$package' and version = '$newver';";
3292 push @packages_list_statements, $sql;
3293 }
3294 }
3296 return;
3297 }
3300 sub prepare_server_registration
3301 {
3302 # Add foreign server from cfg file
3303 my @foreign_server_list;
3304 if ($foreign_server_string ne "") {
3305 my @cfg_foreign_server_list = split(",", $foreign_server_string);
3306 foreach my $foreign_server (@cfg_foreign_server_list) {
3307 push(@foreign_server_list, $foreign_server);
3308 }
3310 daemon_log("0 INFO: found foreign server in config file: ".join(", ", @foreign_server_list), 5);
3311 }
3313 # Perform a DNS lookup for server registration if flag is true
3314 if ($dns_lookup eq "true") {
3315 # Add foreign server from dns
3316 my @tmp_servers;
3317 if (not $server_domain) {
3318 # Try our DNS Searchlist
3319 for my $domain(get_dns_domains()) {
3320 chomp($domain);
3321 my ($tmp_domains, $error_string) = &get_server_addresses($domain);
3322 if(@$tmp_domains) {
3323 for my $tmp_server(@$tmp_domains) {
3324 push @tmp_servers, $tmp_server;
3325 }
3326 }
3327 }
3328 if(@tmp_servers && length(@tmp_servers)==0) {
3329 daemon_log("0 WARNING: no foreign gosa-si-server found in DNS for domain '$server_domain'", 3);
3330 }
3331 } else {
3332 @tmp_servers = &get_server_addresses($server_domain);
3333 if( 0 == @tmp_servers ) {
3334 daemon_log("0 WARNING: no foreign gosa-si-server found in DNS for domain '$server_domain'", 3);
3335 }
3336 }
3338 daemon_log("0 INFO: found foreign server via DNS ".join(", ", @tmp_servers), 5);
3340 foreach my $server (@tmp_servers) {
3341 unshift(@foreign_server_list, $server);
3342 }
3343 } else {
3344 daemon_log("0 INFO: DNS lookup for server registration is disabled", 5);
3345 }
3347 # eliminate duplicate entries
3348 @foreign_server_list = &del_doubles(@foreign_server_list);
3349 my $all_foreign_server = join(", ", @foreign_server_list);
3350 daemon_log("0 INFO: found foreign server in config file and DNS: '$all_foreign_server'", 5);
3352 # add all found foreign servers to known_server
3353 my $cur_timestamp = &get_time();
3354 foreach my $foreign_server (@foreign_server_list) {
3356 # do not add myself to known_server_db
3357 if (&is_local($foreign_server)) { next; }
3358 ######################################
3360 my $res = $known_server_db->add_dbentry( {table=>$known_server_tn,
3361 primkey=>['hostname'],
3362 hostname=>$foreign_server,
3363 macaddress=>"",
3364 status=>'not_yet_registered',
3365 hostkey=>"none",
3366 loaded_modules => "none",
3367 timestamp=>$cur_timestamp,
3368 update_time=>'19700101000000',
3369 } );
3370 }
3371 }
3373 sub register_at_foreign_servers {
3374 my ($kernel) = $_[KERNEL];
3376 # Update status and update-time of all si-server with expired update_time and
3377 # block them for race conditional registration processes of other si-servers.
3378 my $act_time = &get_time();
3379 my $block_statement = "UPDATE $known_server_tn SET status='new_server',update_time='19700101000000' WHERE (CAST(update_time AS UNSIGNED))<$act_time ";
3380 my $block_res = $known_server_db->exec_statement($block_statement);
3382 # Fetch all si-server from db where update_time is younger than act_time
3383 my $fetch_statement = "SELECT * FROM $known_server_tn WHERE update_time='19700101000000'";
3384 my $fetch_res = $known_server_db->exec_statement($fetch_statement);
3386 # Detect already connected clients. Will be added to registration msg later.
3387 my $client_sql = "SELECT * FROM $known_clients_tn";
3388 my $client_res = $known_clients_db->exec_statement($client_sql);
3390 # Send registration messag to all fetched si-server
3391 foreach my $hit (@$fetch_res) {
3392 my $hostname = @$hit[0];
3393 my $hostkey = &create_passwd;
3395 # Add already connected clients to registration message
3396 my $myhash = &create_xml_hash('new_server', $server_address, $hostname);
3397 &add_content2xml_hash($myhash, 'key', $hostkey);
3398 map(&add_content2xml_hash($myhash, 'client', @{$_}[0].",".@{$_}[4]), @$client_res);
3400 # Add locally loaded gosa-si modules to registration message
3401 my $loaded_modules = {};
3402 while (my ($package, $pck_info) = each %$known_modules) {
3403 next if ((!defined(@$pck_info[2])) || (!(ref (@$pck_info[2]) eq 'HASH')));
3404 foreach my $act_module (keys(%{@$pck_info[2]})) {
3405 $loaded_modules->{$act_module} = "";
3406 }
3407 }
3408 map(&add_content2xml_hash($myhash, "loaded_modules", $_), keys(%$loaded_modules));
3410 # Add macaddress to registration message
3411 my ($host_ip, $host_port) = split(/:/, $hostname);
3412 my $local_ip = &get_local_ip_for_remote_ip($host_ip);
3413 my $network_interface= &get_interface_for_ip($local_ip);
3414 my $host_mac = &get_mac_for_interface($network_interface);
3415 &add_content2xml_hash($myhash, 'macaddress', $host_mac);
3417 # Build registration message and send it
3418 my $foreign_server_msg = &create_xml_string($myhash);
3419 my $error = &send_msg_to_target($foreign_server_msg, $hostname, $ServerPackages_key, "new_server", 0);
3420 }
3423 # After n sec perform a check of all server registration processes
3424 $kernel->delay_set("control_server_registration", 2);
3426 return;
3427 }
3430 sub control_server_registration {
3431 my ($kernel) = $_[KERNEL];
3433 # Check if all registration processes succeed or not
3434 my $select_statement = "SELECT * FROM $known_server_tn WHERE status='new_server'";
3435 my $select_res = $known_server_db->exec_statement($select_statement);
3437 # If at least one registration process failed, maybe in case of a race condition
3438 # with a foreign registration process
3439 if (@$select_res > 0)
3440 {
3441 # Release block statement 'new_server' to make the server accessible
3442 # for foreign registration processes
3443 my $update_statement = "UPDATE $known_server_tn SET status='waiting' WHERE status='new_server'";
3444 my $update_res = $known_server_db->exec_statement($update_statement);
3446 # Set a random delay to avoid the registration race condition
3447 my $new_foreign_servers_register_delay = int(rand(4))+1;
3448 $kernel->delay_set("register_at_foreign_servers", $new_foreign_servers_register_delay);
3449 }
3450 # If all registration processes succeed
3451 else
3452 {
3453 $kernel->delay_set("register_at_foreign_servers", $foreign_servers_register_delay);
3454 }
3456 return;
3457 }
3460 #==== MAIN = main ==============================================================
3461 # parse commandline options
3462 Getopt::Long::Configure( "bundling" );
3463 GetOptions("h|help" => \&usage,
3464 "c|config=s" => \$cfg_file,
3465 "f|foreground" => \$foreground,
3466 "v|verbose+" => \$verbose,
3467 "no-arp+" => \$no_arp,
3468 "d=s" => \$debug_parts,
3469 ) or &usage("", 1);
3471 # read and set config parameters
3472 &check_cmdline_param ;
3473 &read_configfile($cfg_file, %cfg_defaults);
3474 &check_pid;
3476 $SIG{CHLD} = 'IGNORE';
3478 # forward error messages to logfile
3479 if( ! $foreground ) {
3480 open( STDIN, '+>/dev/null' );
3481 open( STDOUT, '+>&STDIN' );
3482 open( STDERR, '+>&STDIN' );
3483 }
3485 # Just fork, if we are not in foreground mode
3486 if( ! $foreground ) {
3487 chdir '/' or die "Can't chdir to /: $!";
3488 $pid = fork;
3489 setsid or die "Can't start a new session: $!";
3490 umask 0;
3491 } else {
3492 $pid = $$;
3493 }
3495 # Do something useful - put our PID into the pid_file
3496 if( 0 != $pid ) {
3497 open( my $LOCK_FILE, ">", "$pid_file" );
3498 print $LOCK_FILE "$pid\n";
3499 close( $LOCK_FILE );
3500 if( !$foreground ) {
3501 exit( 0 )
3502 };
3503 }
3505 # parse head url and revision from svn
3506 my $server_status_hash = { 'developmental'=>'revision', 'stable'=>'release'};
3507 $server_version =~ /^\$HeadURL: (\S+) \$:\$Rev: (\d+) \$$/;
3508 $server_headURL = defined $1 ? $1 : 'unknown' ;
3509 $server_revision = defined $2 ? $2 : 'unknown' ;
3510 if ($server_headURL =~ /\/tag\// ||
3511 $server_headURL =~ /\/branches\// ) {
3512 $server_status = "stable";
3513 } else {
3514 $server_status = "developmental" ;
3515 }
3516 # Prepare log file and set permissions
3517 $root_uid = getpwnam('root');
3518 $adm_gid = getgrnam('adm');
3519 open(my $FH, ">>", "$log_file");
3520 close($FH);
3521 chmod(0440, $log_file);
3522 chown($root_uid, $adm_gid, $log_file);
3523 chown($root_uid, $adm_gid, "/var/lib/gosa-si");
3525 daemon_log(" ", 1);
3526 daemon_log("$0 started!", 1);
3527 daemon_log("status: $server_status", 1);
3528 daemon_log($server_status_hash->{$server_status}.": $server_revision", 1);
3530 # Buildup data bases
3531 {
3532 no strict "refs";
3534 if ($db_module eq "DBmysql") {
3536 daemon_log("0 INFO: importing database module '$db_module'", 1);
3538 # connect to incoming_db
3539 $incoming_db = ("GOSA::".$db_module)->new($main::mysql_database, $main::mysql_host, $main::mysql_username, $main::mysql_password);
3541 # connect to gosa-si job queue
3542 $job_db = ("GOSA::".$db_module)->new($main::mysql_database, $main::mysql_host, $main::mysql_username, $main::mysql_password);
3544 # connect to known_clients_db
3545 $known_clients_db = ("GOSA::".$db_module)->new($main::mysql_database, $main::mysql_host, $main::mysql_username, $main::mysql_password);
3547 # connect to foreign_clients_db
3548 $foreign_clients_db = ("GOSA::".$db_module)->new($main::mysql_database, $main::mysql_host, $main::mysql_username, $main::mysql_password);
3550 # connect to known_server_db
3551 $known_server_db = ("GOSA::".$db_module)->new($main::mysql_database, $main::mysql_host, $main::mysql_username, $main::mysql_password);
3553 # connect to login_usr_db
3554 $login_users_db = ("GOSA::".$db_module)->new($main::mysql_database, $main::mysql_host, $main::mysql_username, $main::mysql_password);
3556 # connect to fai_server_db
3557 $fai_server_db = ("GOSA::".$db_module)->new($main::mysql_database, $main::mysql_host, $main::mysql_username, $main::mysql_password);
3559 # connect to fai_release_db
3560 $fai_release_db = ("GOSA::".$db_module)->new($main::mysql_database, $main::mysql_host, $main::mysql_username, $main::mysql_password);
3562 # connect to packages_list_db
3563 $packages_list_db = ("GOSA::".$db_module)->new($main::mysql_database, $main::mysql_host, $main::mysql_username, $main::mysql_password);
3565 # connect to messaging_db
3566 $messaging_db = ("GOSA::".$db_module)->new($main::mysql_database, $main::mysql_host, $main::mysql_username, $main::mysql_password);
3568 } elsif ($db_module eq "DBsqlite") {
3570 daemon_log("0 INFO: importing database module '$db_module'", 1);
3572 # connect to incoming_db
3573 unlink($incoming_file_name);
3574 $incoming_db = GOSA::DBsqlite->new($incoming_file_name);
3575 chmod(0640, $incoming_file_name);
3576 chown($root_uid, $adm_gid, $incoming_file_name);
3578 # connect to gosa-si job queue
3579 $job_db = GOSA::DBsqlite->new($job_queue_file_name);
3580 chmod(0640, $job_queue_file_name);
3581 chown($root_uid, $adm_gid, $job_queue_file_name);
3583 # connect to known_clients_db
3584 #unlink($known_clients_file_name);
3585 $known_clients_db = GOSA::DBsqlite->new($known_clients_file_name);
3586 chmod(0640, $known_clients_file_name);
3587 chown($root_uid, $adm_gid, $known_clients_file_name);
3589 # connect to foreign_clients_db
3590 #unlink($foreign_clients_file_name);
3591 $foreign_clients_db = GOSA::DBsqlite->new($foreign_clients_file_name);
3592 chmod(0640, $foreign_clients_file_name);
3593 chown($root_uid, $adm_gid, $foreign_clients_file_name);
3595 # connect to known_server_db
3596 unlink($known_server_file_name); # do not delete, gosa-si-server should be forced to check config file and dns at each start
3597 $known_server_db = GOSA::DBsqlite->new($known_server_file_name);
3598 chmod(0640, $known_server_file_name);
3599 chown($root_uid, $adm_gid, $known_server_file_name);
3601 # connect to login_usr_db
3602 #unlink($login_users_file_name);
3603 $login_users_db = GOSA::DBsqlite->new($login_users_file_name);
3604 chmod(0640, $login_users_file_name);
3605 chown($root_uid, $adm_gid, $login_users_file_name);
3607 # connect to fai_server_db
3608 unlink($fai_server_file_name);
3609 $fai_server_db = GOSA::DBsqlite->new($fai_server_file_name);
3610 chmod(0640, $fai_server_file_name);
3611 chown($root_uid, $adm_gid, $fai_server_file_name);
3613 # connect to fai_release_db
3614 unlink($fai_release_file_name);
3615 $fai_release_db = GOSA::DBsqlite->new($fai_release_file_name);
3616 chmod(0640, $fai_release_file_name);
3617 chown($root_uid, $adm_gid, $fai_release_file_name);
3619 # connect to packages_list_db
3620 unlink($packages_list_under_construction);
3621 $packages_list_db = GOSA::DBsqlite->new($packages_list_file_name);
3622 chmod(0640, $packages_list_file_name);
3623 chown($root_uid, $adm_gid, $packages_list_file_name);
3625 # connect to messaging_db
3626 #unlink($messaging_file_name);
3627 $messaging_db = GOSA::DBsqlite->new($messaging_file_name);
3628 chmod(0640, $messaging_file_name);
3629 chown($root_uid, $adm_gid, $messaging_file_name);
3630 }
3631 }
3633 # Creating tables
3635 daemon_log("0 INFO: creating tables in database with '$db_module'", 1);
3637 $messaging_db->create_table($messaging_tn, \@messaging_col_names);
3638 $packages_list_db->create_table($packages_list_tn, \@packages_list_col_names);
3639 $fai_release_db->create_table($fai_release_tn, \@fai_release_col_names);
3640 $fai_server_db->create_table($fai_server_tn, \@fai_server_col_names);
3641 $login_users_db->create_table($login_users_tn, \@login_users_col_names);
3642 $known_server_db->create_table($known_server_tn, \@known_server_col_names);
3643 $foreign_clients_db->create_table($foreign_clients_tn, \@foreign_clients_col_names);
3644 $known_clients_db->create_table($known_clients_tn, \@known_clients_col_names);
3645 $incoming_db->create_table($incoming_tn, \@incoming_col_names);
3646 $job_db->create_table($job_queue_tn, \@job_queue_col_names);
3648 # create xml object used for en/decrypting
3649 $xml = new XML::Simple();
3651 # Import all modules
3652 &import_modules;
3654 # Check wether all modules are gosa-si valid passwd check
3655 &password_check;
3657 # Check DNS and config file for server registration
3658 if ($serverPackages_enabled eq "true") { &prepare_server_registration; }
3660 # Create functions hash
3661 while (my ($module, @mod_info) = each %$known_modules)
3662 {
3663 while (my ($plugin, $functions) = each %{$mod_info[0][2]})
3664 {
3665 while (my ($function, $nothing) = each %$functions )
3666 {
3667 $known_functions->{$function} = $nothing;
3668 }
3669 }
3670 }
3672 # Prepare for using Opsi
3673 if ($opsi_enabled eq "true") {
3674 use JSON::RPC::Client;
3675 use XML::Quote qw(:all);
3676 $opsi_url= "https://".$opsi_admin.":".$opsi_password."@".$opsi_server.":4447/rpc";
3677 $opsi_client = new JSON::RPC::Client;
3678 }
3681 POE::Component::Server::TCP->new(
3682 Alias => "TCP_SERVER",
3683 Port => $server_port,
3684 ClientInput => sub {
3685 my ($kernel, $input, $heap, $session) = @_[KERNEL, ARG0, HEAP, SESSION];
3686 my $session_id = $session->ID;
3687 if ($input =~ /;([\d\.]+):([\d]+)$/)
3688 {
3689 # Messages from other servers should be blocked if config option is set
3690 if (($2 eq $server_port) && ($serverPackages_enabled eq "false"))
3691 {
3692 return;
3693 }
3694 &daemon_log("$session_id DEBUG: incoming message from '$1:$2'", 11);
3695 }
3696 else
3697 {
3698 my $remote_ip = $heap->{'remote_ip'};
3699 &daemon_log("$session_id DEBUG: incoming message from '$remote_ip'", 11);
3700 }
3701 push(@msgs_to_decrypt, $input);
3702 $kernel->yield("msg_to_decrypt");
3703 },
3704 InlineStates => {
3705 msg_to_decrypt => \&msg_to_decrypt,
3706 watch_for_next_tasks => \&watch_for_next_tasks,
3707 next_task => \&next_task,
3708 task_result => \&handle_task_result,
3709 task_done => \&handle_task_done,
3710 task_debug => \&handle_task_debug,
3711 child_reap => sub { "Do nothing special. I'm just a comment, but i'm necessary!" },
3712 }
3713 );
3715 daemon_log("0 INFO: start socket for incoming xml messages at port '$server_port' ", 1);
3717 # create session for repeatedly checking the job queue for jobs
3718 POE::Session->create(
3719 inline_states => {
3720 _start => \&session_start,
3721 register_at_foreign_servers => \®ister_at_foreign_servers,
3722 control_server_registration => \&control_server_registration,
3723 sig_handler => \&sig_handler,
3724 next_task => \&next_task,
3725 task_result => \&handle_task_result,
3726 task_done => \&handle_task_done,
3727 task_debug => \&handle_task_debug,
3728 watch_for_new_messages => \&watch_for_new_messages,
3729 watch_for_delivery_messages => \&watch_for_delivery_messages,
3730 watch_for_done_messages => \&watch_for_done_messages,
3731 watch_for_new_jobs => \&watch_for_new_jobs,
3732 watch_for_modified_jobs => \&watch_for_modified_jobs,
3733 watch_for_done_jobs => \&watch_for_done_jobs,
3734 watch_for_opsi_jobs => \&watch_for_opsi_jobs,
3735 watch_for_old_known_clients => \&watch_for_old_known_clients,
3736 create_packages_list_db => \&run_create_packages_list_db,
3737 create_fai_server_db => \&run_create_fai_server_db,
3738 create_fai_release_db => \&run_create_fai_release_db,
3739 recreate_packages_db => \&run_recreate_packages_db,
3740 session_run_result => \&session_run_result,
3741 session_run_debug => \&session_run_debug,
3742 session_run_done => \&session_run_done,
3743 child_reap => sub { "Do nothing special. I'm just a comment, but i'm necessary!" },
3744 }
3745 );
3748 POE::Kernel->run();
3749 exit;