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