Cleaned up some leftovers
[gnucomo.git] / src / gcm_daemon / gcm_daemon.php
1 #!/usr/bin/php
2 <?PHP
3 /**********************************************************************************
4 **  (c) Copyright 2002, Brenno J.S.A.A.F. de Winter, De Winter Information Solutions
5 ** This is free software; you can redistribute it and/or modify it under the
6 ** terms of the GNU General Public License, see the file COPYING.
7 ***********************************************************************************/
8
9
10 /*
11    NAME          : gcm_daemon
12    AUTHOR        : Brenno J.S.A.A.F. de Winter
13                    De Winter Information Solutions
14    COPYRIGHT     : 2002 - De Winter Information Solutions,
15                    Brenno J.S.A.A.F. de Winter
16
17    * DATES *
18    First        : November 8th 2002
19    Gnucomo-0.0.3: December 6th 2002
20    Gnucomo-0.0.8: September 4th 2003
21
22  $Log: gcm_daemon.php,v $
23  Revision 1.24  2007-11-17 09:34:07  arjen
24  Cleaned up some leftovers
25
26  Revision 1.23  2007/11/03 10:31:12  arjen
27  Added the class definition for a filesystem parameter.
28  New issue type: 'property out of range'.
29
30  Revision 1.22  2007/10/23 11:23:52  arjen
31  Record the date when adding the number of abuses for an IP address
32  in the abuse list.
33
34  Revision 1.21  2007/01/11 13:47:41  arjen
35  Log_adv and derived tables removed.
36  Create notifications from log entries with pattern matching.
37
38  Revision 1.20  2005/06/04 07:15:16  arjen
39  Added pattern check on log entries with the service_pattern table.
40
41  Revision 1.19  2004/01/10 20:04:12  arjen
42  Send email about open notifications to an object's users.
43
44  Revision 1.18  2003/12/03 08:07:21  arjen
45  Changed the type of log_adv_daemon_email.delay and log_adv_daemon_email.xdelay
46  from time to interval. These delays can be more than 24 hours.
47
48  Revision 1.17  2003/10/29 09:58:29  arjen
49  Create separate notifications for different objects in service_check().
50
51  Revision 1.16  2003/09/03 12:48:48  arjen
52  Check the log table against the servies running on an object and
53  create notifications if a service is not supposed to be available
54  or is not known at all.
55
56  Revision 1.15  2003/09/02 12:48:09  arjen
57  BUGFIX: Secondary indices on log_notification were unique.
58  Additional information in the 'usr' table: 'display_name' and 'email'.
59  Added new issues and services.
60
61  Revision 1.14  2003/09/01 06:51:07  arjen
62  Accept command argument '-c config' to use an alternate
63  gnucomo configuration.
64
65  Revision 1.13  2003/08/14 10:22:42  arjen
66  Disabled DEBUG output
67
68  Revision 1.12  2003/08/05 07:46:37  arjen
69  BUGFIX: Print an error message if a parameter does not have
70  any history.
71
72  Revision 1.11  2003/07/09 07:25:02  arjen
73  Gcm_daemon gathers statistics on parameters, notifications, etc. for all objects.
74
75  Revision 1.10  2003/03/29 08:33:58  arjen
76  In phpclasses/db.class.php: Added the database connection string as
77  an argument to the function copy_db_class.
78  Fixed the PHP member function db::db_connect(). The Postgres connection
79  string is now passed as an argument to that function.
80
81  Revision 1.9  2003/02/21 08:37:59  arjen
82  Added new table to the database: log_adv_daemon_email.
83
84
85 */
86
87 // $Id: gcm_daemon.php,v 1.24 2007-11-17 09:34:07 arjen Exp $
88
89 ini_set('include_path', '.:./classes:../phpclasses');
90 ini_set('html_errors', 'false');
91
92 define("BATCHSIZE", 10000);
93
94 //Tell the log that we're up.
95 define_syslog_variables();
96
97 require_once "gnucomo_config.php";
98 require_once "db.class.php";
99 require_once "gnucomo.process_log.php";
100
101 // Set the standard variables //
102
103 $purge_date     ="";            // Purge log entries until this date. Default: no purging
104 $project_name   = "gnucomo";    // name of the entire project
105 $app_name       = "gcm_daemon"; // name of the application running
106 $developrelease = "FALSE";      // Indicates if special debug settings are needed
107 $db_version     = 53;           // The db_version indicates what the level of
108                                 // the database should be. If the database is
109                                 // old an update will be generated.
110 $gcmd_version   = 5;            // This value indicates the active version of
111                                 // the gcm_daemon, which is saved in the database.
112                                 // Log records that were not recognized before
113                                 // will now be recognized. The version doesn't
114                                 // mean anything in the overall gnucomo project.
115
116 //Avoid time-limit issues
117 set_time_limit(0);
118
119 //  Scan the command arguments
120
121 for ($argi = 1; $argi < $argc; $argi++)
122 {
123    switch ($argv[$argi])
124    {
125    case "-c":
126       $argi++;
127       $project_name = $argv[$argi];
128       break;
129
130    case "-p":
131       $argi++;
132       $purge_date = $argv[$argi];
133       break;
134
135    default:
136       echo "Usage: gcm_daemon [-c configname] [-p purgedate]\n";
137       exit();
138       break;
139    }
140 }
141
142 // Read the database settings //
143 $class_settings = new gnucomo_config();
144 if (!$class_settings->read($project_name))
145 {
146    echo "Can not read Gnucomo configuration file for $project_name.\n";
147    exit();
148 }
149
150 openlog("gnucomo", LOG_PID, LOG_DAEMON);
151 syslog(LOG_INFO, "gcm_daemon started");
152
153 //Open an connection to the database
154 $dbms_type = $class_settings->find_parameter("database", "type");
155 $dbms_host = $class_settings->find_parameter("database", "host");
156 $dbms_name = $class_settings->find_parameter("database", "name");
157 $dbms_user = $class_settings->find_parameter("gcm_daemon", "user");
158 $dbms_password = $class_settings->find_parameter("gcm_daemon", "password");
159
160 db_select($dbms_type);
161 $dbms = new db();
162 $dbms->db_host = $dbms_host;
163 $dbms->db_name = $dbms_name;
164 $dbms->db_user = $dbms_user;
165 $dbms->db_password = $dbms_password;
166 $dbms->db_connect($class_settings->database());
167
168 if ($dbms->have_db_connection() == "FALSE")
169 {
170    exit ("Database connection failed.");
171 }
172 else
173 {
174    // The database connection has been made.
175    $dbms_working = copy_db_class($dbms, $class_settings->database());
176 }
177
178 // Verify if the database is up-to-date by checking the versionnumber
179
180 $local_sql = "SELECT setting_value FROM db_value WHERE setting = 'db_version' ";
181 $dbms->query($local_sql);
182
183 if ($dbms->fetch_row() == "TRUE")
184 {
185   $active_version = $dbms->db_result_row[0];
186
187   // Update the database to the most recent version.
188
189   if ($active_version < $db_version)
190   {
191      include ("gnucomo_db_version.php");
192   }
193 }
194 else
195 {
196   syslog (LOG_INFO, "Couldn't initialize database version. Is this a gnucomo database?");
197   die ("Couldn't initialize database version.\n");
198 }
199
200 // The gcm_daemon version is maintained in the database to enable
201 // automatic update actions.
202
203 $local_sql = "SELECT setting_value FROM db_value
204               WHERE setting = 'gcm_daemon_version'";
205 $dbms->query($local_sql);
206
207 if ($dbms->fetch_row() == "TRUE")
208 {
209    if ($dbms->db_result_row[0] < $gcmd_version)
210    {
211
212       //Update de gcm_daemon version in the database
213       $local_sql = "UPDATE db_value SET setting_value = '".$gcmd_version;
214       $local_sql .= "' WHERE setting = 'gcm_daemon_version'";
215       $dbms->query($local_sql);
216
217    }
218
219 }
220
221 // Now we loop the tasks that we have to do.
222
223
224 do
225 {
226
227    if ($purge_date != "")
228    {
229       purge_old_logs($purge_date);
230    }
231
232    echo "Processing logs...\n";
233    process_log ();
234    service_check();
235    find_notifications();
236    //mail_notifications();
237
238    //  Gather the statistics for each object
239
240    $obj_result = $dbms->query("SELECT objectid FROM object");
241    for ($obj = 0; $obj < $dbms->num_rows($obj_result); $obj++)
242    {
243       $object = $dbms->fetch_object($obj_result, $obj);
244       echo "Gathering statistics for object " . $object->objectid . "\n";
245       GatherStatistics($object->objectid);
246    }
247
248    $keep_running = false;
249
250 } while ($keep_running == true);
251
252 //Tell the log that we're ending our efforts in a nice way
253
254 syslog (LOG_INFO, "gcm_daemon ended nicely");
255
256 function purge_old_logs($purge_date)
257 {
258    global $dbms;
259
260    /*
261     *   Make a temporary table with the logids of the old log entries
262     *   We don't want to repeat a selection on the large log table itself.
263     */
264
265    echo "Purging log entries before $purge_date\n";
266
267    $dbms->query("CREATE TABLE gcm_deamon_old_log AS SELECT logid FROM log WHERE timestamp < '$purge_date'");
268    $dbms->query("SELECT logid FROM gcm_deamon_old_log");
269    echo $dbms->num_rows() . " log entries found.\n";
270    $r = $dbms->query("select notificationid from log_notification where logid in
271                          (select logid from gcm_deamon_old_log) group by notificationid");
272    echo "Notifications that may be affected:\n";
273    $notifications = array();
274    for ($i=0; $i < $dbms->num_rows(); $i++)
275    {
276       $notif = $dbms->fetch_object($r, $i);
277       $notifications[] = $notif->notificationid;
278       echo $notif->notificationid . "\n";
279    }
280    $dbms->query("delete from log_notification where logid in
281                          (select logid from gcm_deamon_old_log)");
282
283    //  Clean up any notifications that have no more logs left
284    foreach ($notifications as $notif)
285    {
286       $c = $dbms->fetch_object($dbms->query("select count(*) from log_notification where notificationid=$notif"), 0);
287       echo "Notification $notif has " . $c->count . " log entries left.\n";
288       if ($c->count == 0)
289       {
290          echo "Cleaning up notification $notif.\n";
291          $dbms->query("delete from action_user where notificationid=$notif");
292          $dbms->query("delete from notification where notificationid=$notif");
293       }
294    }
295
296    $dbms->query("delete from log where logid in
297                          (select logid from gcm_deamon_old_log)");
298
299    $dbms->query("drop table gcm_deamon_old_log");
300 }
301
302
303 function process_log ()
304 {
305
306  /* This function will walk through the log-records that haven't been processed
307   * first a snapshot will be created of a the non-processed records.
308   * sequentially each record will dealt with. By doing that changes will be made
309   * in several log_adv_xxx tables
310   * INPUT  : NONE
311   * OUTPUT : NONE
312   */
313
314   global $dbms;
315   global $dbms_working;
316   global $class_settings;
317
318   $last_log = 0;
319
320   // Find records in log that still have to be processed.
321
322   $local_sql = "SELECT setting_value FROM db_value WHERE setting = 'log_processing'";
323   $dbms->query($local_sql);
324
325   if ($dbms->fetch_row() == "TRUE")
326   {
327      $last_log = $dbms->db_result_row[0];
328   }
329
330   echo "Last processed logid = $last_log \n";
331
332   //Query the log-table
333   $log_limit = $last_log + BATCHSIZE;
334   $local_sql = "SELECT * FROM log WHERE logid > CAST(".$last_log." AS BIGINT)
335                 AND logid <= $log_limit ORDER BY logid";
336   $dbms->query($local_sql);
337
338   //Update the log-statistics in the object-table
339   $local_statistics_db = copy_db_class($dbms, $class_settings->database());
340   $local_findobject_db = copy_db_class($dbms, $class_settings->database());
341
342   //Make totals
343   $local_upper_row = $dbms->num_rows() + $last_log + 1;
344   $local_sql = "SELECT COUNT(logid), objectid from log WHERE logid > CAST(". $last_log .
345       " AS BIGINT) AND logid < CAST (" . $local_upper_row . " AS BIGINT) GROUP BY objectid";
346   $local_statistics_db->query ($local_sql);
347
348   // Loop the objects
349   for ($i = 1; $i <= $local_statistics_db->num_rows(); $i++)
350   {
351       $local_object_row = $local_statistics_db->fetch_row();
352
353       $local_sql = "UPDATE object SET log_count = log_count + " .
354           $local_statistics_db->db_result_row[0] . " WHERE objectid = '" .
355           $local_statistics_db->db_result_row[1] . "'";
356
357       $local_findobject_db->query($local_sql);
358   }
359
360   $local_counter = 0;
361
362   if ($dbms->num_rows() > 0)
363   {
364
365     //Create a database connection for changes in the database.
366     $dbms_changes = copy_db_class($dbms, $class_settings->database());
367     if ($dbms_changes->have_db_connection() == 'TRUE')
368     {
369
370        $local_sql               = 0 ;
371        $local_sql_statistics    = "";
372        $local_object_os         = "";
373        $local_object_os_version = "";
374
375 /*
376        while ($local_counter < $dbms->num_rows())
377        {
378
379          $local_return_row = $dbms->fetch_row();
380          if ($local_return_row == 'TRUE')
381          {
382             // Work on active rows
383             $local_log_id = $dbms->db_result_row[0];
384
385             $local_sql_findobject = "SELECT os, os_version FROM object
386                                 WHERE objectid = '".$dbms->db_result_row[1]."'";
387             $local_findobject_db->query($local_sql_findobject);
388             $local_findobject_result = $local_findobject_db->fetch_row();
389             if ($local_findobject_result == 'TRUE')
390             {
391
392                 // Now work on the OS again
393                 $local_object_os = $local_findobject_db->db_result_row[0];
394                 if  ($local_object_os == "")
395                 {
396                     $local_object_os = "Linux";
397                     $local_object_os_version = "Unknown assuming Linux";
398                 }
399                 else
400                 {
401                   $local_object_os_version = $local_findobject_db->db_result_row[1];
402                 }
403              }
404
405             switch (strtolower($local_object_os))
406             {
407             case "linux":
408                 $local_process_return = linux_log ();
409                 break;
410             default:
411                 syslog (LOG_INFO, "Couldn't find suitable OS for processing the logline");
412                 break;
413             }
414
415             if ($local_process_return != 'TRUE')
416             {
417               $local_process_return = 'FALSE';
418             }
419
420          }
421          else
422          {
423
424            break;
425
426          }
427          $local_counter++;
428        }
429 */
430
431        //  Check for spam and other abuses.
432
433        // abuse_check($last_log);
434
435        match_log_patterns($last_log);
436
437        // Register that the logrecords have been processed.
438        $local_upper_row--;
439        $local_sql = "UPDATE db_value SET setting_value = '"
440                    . $local_upper_row ."' where setting = 'log_processing'";
441        $dbms->query($local_sql);
442
443
444        // Update the statistics for the object-table
445
446
447      }
448      else
449      {
450        syslog (LOG_INFO, "Couldn't clone database connection.");
451        die ("Couldn't reconnect to the database.\n");
452      }
453   }
454
455 }
456
457 /*
458  *   Update a single statistic for some object.
459  *   If it does not yet exist, it will be created.
460  */
461
462 function UpdateStatistic($objectid, $name, $value)
463 {
464    global $dbms;
465
466    $result = $dbms->query("SELECT objectid FROM object_statistics WHERE
467              objectid='$objectid' AND statname='$name'");
468    if ($dbms->num_rows() == 0)
469    {
470       $dbms->query("INSERT INTO object_statistics VALUES
471                     ('$objectid', '$name', '$value')");
472    }
473    else
474    {
475       $dbms->query("UPDATE object_statistics SET statvalue='$value' WHERE
476            statname='$name' AND objectid='$objectid'");
477    }
478 }
479
480 /*
481  *   Gather the statistics for a single object ($objectid).
482  *   We count the number of parameters, removed parameters, notifications
483  *   closed notifications and log entries. The totals of these are
484  *   maintained in a separate table: object_statistics.
485  */
486
487 function GatherStatistics($objectid)
488 {
489    global $dbms;
490
491    //  Gather statistics on parameters
492
493    $r = $dbms->query("SELECT paramid FROM parameter WHERE objectid=CAST('"
494                         . $objectid . "' AS BIGINT)");
495    $nr_parameters = $dbms->num_rows($r);
496
497    $removed_parameters = 0;
498    for ($p = 0; $p < $nr_parameters; $p++)
499    {
500       $param = pg_fetch_object($r, $p);
501       $qry ="select change_nature from history where paramid= CAST('";
502       $qry .= $param->paramid . "' AS BIGINT) order by modified desc";
503       $rhist = $dbms->query($qry);
504       if ($dbms->num_rows($rhist) == 0)
505       {
506          echo "ERROR: No history for parameter id " . $param->paramid . "\n";
507       }
508       else
509       {
510          $hist = $dbms->fetch_object($rhist, 0);
511          if ($hist->change_nature == "REMOVED")
512          {
513             $removed_parameters++;
514          }
515       }
516    }
517
518    UpdateStatistic($objectid, 'parameters', $nr_parameters);
519    UpdateStatistic($objectid, 'removed_parameters', $removed_parameters);
520
521    //  Gather statistics on notifications
522
523    $r = $dbms->query("SELECT count(notificationid) FROM notification WHERE
524                        objectid = CAST('" . $objectid . "' AS BIGINT)");
525    $cnt = $dbms->fetch_object($r, 0);
526    UpdateStatistic($objectid, 'notifications', $cnt->count);
527
528    $r = $dbms->query("SELECT count(notificationid) FROM notification WHERE
529                        objectid = CAST('" . $objectid . "' AS BIGINT) AND statuscode ='cls'");
530    $cnt = $dbms->fetch_object($r, 0);
531    UpdateStatistic($objectid, 'closed_notifications', $cnt->count);
532
533    //  Gather statistics on log entries
534
535    $r = $dbms->query("SELECT count(logid) FROM log WHERE
536                        objectid = CAST('" . $objectid . "' AS BIGINT)");
537    $cnt = $dbms->fetch_object($r, 0);
538    UpdateStatistic($objectid, 'logs', $cnt->count);
539 }
540
541 //  Check for spam and other abuses in the log_adv tables.
542
543 function abuse_check($logstart)
544 {
545 return;   //  This function is obsolete
546    global  $dbms;
547
548   // notification: 'abuses exceeded'.
549
550    $noqueue_res = $dbms->query("select logid, source_ip from log_adv_daemon_email
551                                 where event='NOQUEUE' and logid > " . $logstart);
552    echo "NOQUEUE abuses:\n\n";
553    for ($row = 0; $row < $dbms->num_rows($noqueue_res); $row++)
554    {
555       $noqueue = $dbms->fetch_object($noqueue_res, $row);
556       if ($noqueue->source_ip != '')
557       {
558          $obj = $dbms->fetch_object(
559                        $dbms->query("SELECT objectid FROM log WHERE logid = '" . $noqueue->logid . "'"),0);
560          record_abuse(0, $obj->objectid, $noqueue->source_ip, 2);
561
562          // TODO: Create notification
563       }
564    } 
565    $dbms->Free($noqueue_res);
566
567    $noqueue_res = $dbms->query("select logid, source_ip, relay from log_adv_daemon_email
568                                 where event='SPAM' and logid > " . $logstart);
569    echo "SPAM abuses:\n\n";
570    for ($row = 0; $row < $dbms->num_rows($noqueue_res); $row++)
571    {
572       $noqueue = $dbms->fetch_object($noqueue_res, $row);
573       $source = $noqueue->source_ip;
574       if ($source == '')
575       {
576          $source = $noqueue->relay;
577       }
578       if ($source != '')
579       {
580          $obj = $dbms->fetch_object(
581                        $dbms->query("SELECT objectid FROM log WHERE logid = '" . $noqueue->logid . "'"),0);
582          record_abuse(0, $obj->objectid, $source, 1);
583
584          // TODO: Create notification
585       }
586    } 
587    $dbms->Free($noqueue_res);
588
589    echo "HTTP abuses:\n\n";
590    $abuse_res = $dbms->query("select logid, objectid, rawdata from log
591                               where servicecode='httpd' and logid > " . $logstart);
592    for ($row = 0; $row < $dbms->num_rows($abuse_res); $row++)
593    {
594       $source = '';
595       $abuse = $dbms->fetch_object($abuse_res, $row);
596       if (ereg("\[error\] \[client ([0-9.]+)\] request failed: URI too long", $abuse->rawdata, $parts))
597       {
598          echo $abuse->rawdata . "\n";
599          echo "Abuse on object " . $abuse->objectid . " from IP address " . $parts[1] . "\n";
600          $source = $parts[1];
601       }
602       if (ereg("\[error\] \[client ([0-9.]+)\] File does not exist: .+/MSADC",
603                $abuse->rawdata, $parts))
604       {
605          echo $abuse->rawdata . "\n";
606          echo "Abuse on object " . $abuse->objectid . " from IP address " . $parts[1] . "\n";
607          $source = $parts[1];
608       }
609       if ($source != '')
610       {
611          record_abuse(0, $abuse->objectid, $source, 2);
612
613          // TODO: Create notification
614       }
615    }
616    $dbms->Free($abuse_res);
617 }
618
619 function match_log_patterns($logstart)
620 {
621    global  $dbms;
622
623    $notifications = array();
624
625    $log_limit = $logstart + BATCHSIZE;
626    $noqueue_res = $dbms->query("select logid, objectid, servicecode, rawdata from log
627                               where logid > $logstart and logid <= $log_limit
628                               order by logid");
629    for ($row = 0; $row < $dbms->num_rows($noqueue_res); $row++)
630    {
631       $logentry = $dbms->fetch_object($noqueue_res, $row);
632       //echo "\n----------\n" . $logentry->rawdata . "\n----------\n";
633       $service = $logentry->servicecode;
634       $pattern_res = $dbms->query("select * from service_pattern where service='$service'
635                                               OR service='ANY' order by rank");
636
637       $match_found = false;
638       for ($patnr = 0; !$match_found && $patnr < $dbms->num_rows($pattern_res); $patnr++)
639       {
640          $srv_pat = $dbms->fetch_object($pattern_res, $patnr);
641          //echo "  Checking with pattern " . $srv_pat->pattern . "\n";
642          if (ereg($srv_pat->pattern, $logentry->rawdata, $matches))
643          {
644             //  Scan the argument for '$n' expressions and expand
645
646             $srv_pat->argument = expand_arguments($srv_pat->argument, $matches);
647             //echo "   " . $srv_pat->pattern . " matches.\n";
648             //echo "   Matched string: " . $matches[0] . "\n";
649             //echo "   Action = " . $srv_pat->action . "(" . $srv_pat->argument . ")\n\n";
650             $match_found = true;
651
652             switch ($srv_pat->action)
653             {
654             case "ignore":
655                break;
656
657             case "notify":
658                $notif = $srv_pat->argument;
659                if (!isset($notifications[$logentry->objectid][$notif]))
660                {
661                   //echo "Creating notification $notif for object " . $logentry->objectid . ".\n";
662                   $remark = "Notification generated from Gnucomo pattern match.";
663                   $notifications[$logentry->objectid][$notif] =
664                          $dbms->new_notification($logentry->objectid, $notif, $remark);
665                }
666                if (isset($notifications[$logentry->objectid][$notif]))
667                {
668                   //echo "Notification $notif for object " . $logentry->objectid . " already created.\n";
669                   $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
670                   $insertion .= $notifications[$logentry->objectid][$notif] . "', '";
671                   $insertion .= $logentry->logid . "')";
672                   $dbms->query($insertion);
673                }
674                break;
675
676             case "abuse":
677                if (record_abuse($logentry->logid, $logentry->objectid, $srv_pat->argument, 1) >= 32)
678                {
679                   $source_ip = $srv_pat->argument;
680                   $notif = 'abuses exceeded';
681                   if (!isset($notifications[$logentry->objectid][$notif][$source_ip]))
682                   {
683                      echo "Creating notification $notif for object " . $logentry->objectid . ".\n";
684                      $remark = "Abuses from IP address $source_ip exceeded the limit.";
685                      $notifid = $dbms->new_notification($logentry->objectid, $notif, $remark);
686                      $notifications[$logentry->objectid][$notif][$source_ip] = $notifid;
687
688                      //  Add log entries from previously detected abuses
689
690                      echo " Add log entries from previously detected abuses";
691                      $abuses = $dbms->query("SELECT logid FROM log_abuse WHERE objectid = '" .
692                                     $logentry->objectid . "' AND source = '$source_ip'");
693                      for ($abusenr = 0; $abusenr < $dbms->num_rows($abuses); $abusenr++)
694                      {
695                         $log_abuse = $dbms->fetch_object($abuses, $abusenr);
696                         if ($log_abuse->logid != $logentry->logid)
697                         {
698                            $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
699                            $insertion .= $notifid . "', '";
700                            $insertion .= $log_abuse->logid . "')";
701                            $dbms->query($insertion);
702                         }
703                      }
704                   }
705                   if (isset($notifications[$logentry->objectid][$notif][$source_ip]))
706                   {
707                      echo "Notification $notif for object " . $logentry->objectid . " already created.\n";
708                      $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
709                      $insertion .= $notifications[$logentry->objectid][$notif][$source_ip] . "', '";
710                      $insertion .= $logentry->logid . "')";
711                      $dbms->query($insertion);
712                   }
713                }
714                break;
715             case "forgive":
716                record_abuse($logentry->logid, $logentry->objectid, $srv_pat->argument, -4);
717                break;
718             default:
719                echo "Error: unrecognized action in service pattern: " . $srv_pat->action . "\n";
720                break;
721             }
722          }
723          else
724          {
725             // echo "   " . $srv_pat->pattern . " does not match.\n";
726          }
727       }
728
729    }
730 }
731
732 /*
733  *  Some IP address abused us. Record the event.
734  *  Return the number of abuse points recorded so far for the address
735  */
736
737 function record_abuse($logid, $objectid, $sourceip, $points)
738 {
739    global  $dbms;
740
741    $abuse_points = $points;
742
743    $ipaddress = gethostbyname($sourceip);
744    //echo " IP address for $sourceip is $ipaddress.\n";
745    $sourceip = $ipaddress;
746
747    $abres = $dbms->query("SELECT * FROM object_abuse WHERE objectid='$objectid' AND source='$sourceip'");
748
749    if (pg_numrows($abres) == 0 && $points > 0)
750    {
751       //echo "$sourceip is new.\n";
752       $dbms->query("INSERT INTO object_abuse VALUES ('$objectid', '$sourceip', '$points', '', NOW())");
753       $dbms->query("INSERT INTO log_abuse VALUES ('$logid', '$objectid', '$sourceip')");
754    }
755    else if (pg_numrows($abres) != 0)
756    {
757       $abuse = $dbms->fetch_object($abres, 0);
758       if ($abuse->status == '' || $abuse->status == 'dropped')
759       {
760          $abuse_points = $abuse->nr_abuses + $points;
761          if ($abuse_points < 0)
762          {
763             $abuse_points = 0;
764          }
765          //echo $sourceip . " will get " . $abuse_points . " abuse points, ";
766          //echo "Status was " . $abuse->status . "\n";
767          $dbms->query("UPDATE object_abuse SET nr_abuses='$abuse_points'" .
768                      ", last_change=NOW() WHERE objectid='$objectid' AND source='$sourceip'");
769
770          if ($points > 0)
771          {
772             $dbms->query("INSERT INTO log_abuse VALUES ('$logid', '$objectid', '$sourceip')");
773          }
774          if ($abuse_points >= 32)
775          {
776             //echo "      BLOCK IP adrress $sourceip on the firewall.\n";
777             $dbms->query("UPDATE object_abuse SET status='dropped'" .
778                      " WHERE objectid='$objectid' AND source='$sourceip'");
779          }
780       }
781    }
782
783    return $abuse_points;
784 }
785
786
787 /*
788  *   Service_check - Check the log entries if there are any unknown
789  *   services.
790  */
791
792 function service_check()
793 {
794    global  $dbms;
795
796    $unknown_notification = array();
797    $unused_notification  = array();
798    $last_log             = 0;
799
800    //  How far did we get last time ?
801
802    $lastlogres = $dbms->query("SELECT setting_value FROM db_value
803                                WHERE setting = 'log_servicecheck'");
804
805    if ($dbms->num_rows($lastlogres) == 1)
806    {
807      $last_log = $dbms->Field($lastlogres, 0, 'setting_value');
808    }
809    else
810    {
811       $dbms->query("INSERT INTO db_value (setting, setting_value)
812                             VALUES ('log_servicecheck', '0')");
813    }
814
815    echo "Running service check from log id $last_log.\n";
816    // Query the log-table
817
818    $log_limit = $last_log + BATCHSIZE;
819    $qry = "SELECT logid, objectid, servicecode FROM log
820            WHERE logid > CAST(".$last_log." AS BIGINT) AND logid <= $log_limit
821            ORDER BY logid";
822    $log_res = $dbms->query($qry);
823    //$log_res = $dbms->query("SELECT logid, objectid, servicecode,rawdata FROM log");
824
825    for ($log_row = 0; $log_row < $dbms->num_rows($log_res); $log_row++)
826    {
827       $log_entry = $dbms->fetch_object($log_res, $log_row);
828       $last_log  = $log_entry->logid;
829
830       //   Check if the service is used on the object.
831
832       $qry = "SELECT * FROM object_service WHERE objectid='";
833       $qry .= $log_entry->objectid . "' AND servicecode='";
834       $qry .= $log_entry->servicecode . "'";
835
836       $os_res = $dbms->query($qry);
837       if ($dbms->num_rows($os_res) == 0)
838       {
839          //   Service is not found for the object, check if the service
840          //   exists at all.
841
842          $qry = "SELECT * FROM service WHERE servicecode='";
843          $qry .= $log_entry->servicecode . "'";
844
845          if ($dbms->num_rows($dbms->query($qry)) == 0)
846          {
847             if (!isset($unknown_notification[$log_entry->objectid]))
848             {
849                $remark = "One or more log entries from a service that is not in the database";
850                $unknown_notification[$log_entry->objectid] =
851                          $dbms->new_notification($log_entry->objectid, 'service unknown', $remark);
852             }
853             if (isset($unknown_notification[$log_entry->objectid]))
854             {
855                $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
856                $insertion .= $unknown_notification[$log_entry->objectid] . "', '";
857                $insertion .= $log_entry->logid . "')";
858                $dbms->query($insertion);
859             }
860          }
861          else
862          {
863             if (!isset($unused_notification[$log_entry->objectid]))
864             {
865                $remark = "One or more log entries from a service not running on this object";
866                $unused_notification[$log_entry->objectid] =
867                          $dbms->new_notification($log_entry->objectid, 'service not used', $remark);
868             }
869             if (isset($unused_notification[$log_entry->objectid]))
870             {
871                $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
872                $insertion .= $unused_notification[$log_entry->objectid] . "', '";
873                $insertion .= $log_entry->logid . "')";
874                $dbms->query($insertion);
875             }
876          }
877       }
878    }
879
880    $qry = "UPDATE db_value SET setting_value = '"
881                    . $last_log . "' WHERE setting = 'log_servicecheck'";
882    $dbms->query($qry);
883 }
884
885 function find_notifications ()
886 {
887
888 /*
889  *  Do something with notification checks.
890  *
891  * INPUT  : NONE
892  * OUTPUT : NONE
893  */
894
895    global $dbms;
896
897    // Find checks that have to be executed.
898    $local_sql = "select * from notification_check where
899                     age(last_execution) > time_between_executions";
900    $dbms->query($local_sql);
901
902    for ($i=0; $i<$dbms->num_rows(); $i++)
903    {
904       // A check has been found that has to be executed
905       $dbms->fetch_row();
906    }
907 }
908
909 /*
910  *  find open notifications and send an email to the object's users.
911  */
912
913 function mail_notifications ()
914 {
915    global $dbms;
916
917    $notifres = $dbms->query("SELECT notificationid, objectid, type_of_issueid FROM notification
918                                WHERE statuscode != 'cls'");
919
920    for ($notifrow = 0; $notifrow < pg_numrows($notifres); $notifrow++)
921    {
922       $notification = pg_fetch_object($notifres, $notifrow);
923
924       $issue = pg_fetch_object($dbms->query("SELECT description FROM type_of_issue
925                                              WHERE type_of_issueid='" . $notification->type_of_issueid . "'"), 0);
926       echo "Mailing Notification for object id " . $notification->objectid . "\n";
927       $object = pg_fetch_object($dbms->query("SELECT objectname FROM object
928                                               WHERE objectid='" . $notification->objectid ."'"), 0);
929
930       $users = $dbms->query("SELECT username FROM object_user WHERE objectid='" . $notification->objectid . "'");
931
932       for ($userrow = 0; $userrow < pg_numrows($users); $userrow++)
933       {
934          $objusr = pg_fetch_object($users, $userrow);
935          $usr = pg_fetch_object($dbms->query("SELECT email FROM usr
936                                               WHERE username='" . $objusr->username . "'"), 0);
937
938          $message = "Notification " . $notification->notificationid . ": " . $issue->description;
939          $message .= "  for object " . $object->objectname . "\n";
940
941          mail($usr->email, "GnuCoMo Notification", $message);
942       }
943    }
944 }
945
946 /*
947  *   The 'command' may contain positional parameters such as '$1' and '$3',
948  *   just like the shell. These parameters are replaced by content from
949  *   the 'args' array.
950  */
951
952 function expand_arguments($command, $args)
953 {
954    while (ereg('\$([0-9]+)', $command, $match))
955    {
956       $index = $match[1];
957       if ($index >= count($args))
958       {
959          echo "Error: Argument $index not found for $command.\n";
960          $command = ereg_replace('\$' . $index, "", $command);
961       }
962       else
963       {
964          $command = ereg_replace('\$' . $index, $args[$index], $command);
965       }
966    }
967    return $command;
968 }
969
970 ?>
971