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