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