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