summaryrefslogtreecommitdiffstats
path: root/lib/exilog_sql.pm
blob: e1dd3cd1a6b4b3a7e4cfbc444aa2ff7503ef2d5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
#!/usr/bin/perl
#
# This file is part of the exilog suite.
#
# http://duncanthrax.net/exilog/
#
# (c) Tom Kistner 2004
#
# See LICENSE for licensing information.
#

package exilog_sql;
use strict;
use DBI;
use exilog_config;
use exilog_util;

use Data::Dumper;

BEGIN {
  use Exporter;
  use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);

  # set the version for version checking
  $VERSION     = 0.1;
  @ISA         = qw(Exporter);
  @EXPORT      = qw(
                      &reconnect
                      &sql_select
                      &sql_delete
                      &sql_optimize
                      &sql_count
                      &sql_update_heartbeat
                      &sql_queue_add
                      &sql_queue_update
                      &sql_queue_delete
                      &sql_queue_set_action
                      &sql_queue_clear_action
                      &write_message
                   );

  %EXPORT_TAGS = ();

  # your exported package globals go here,
  # as well as any optionally exported functions
  @EXPORT_OK   = qw();
}


# open DB connection
my $dbh = DBI->connect($config->{sql}->{DBI}, $config->{sql}->{user}, $config->{sql}->{pass});
unless (defined($dbh) && $dbh) {
  print STDERR "[exilog_sql] Can't open exilog database.\n";
  exit(255);
};

sub reconnect {
  my $conditional = shift || 0;
  if ($conditional) {
    return 1 if ($dbh->ping);
  };
  eval {
    $dbh->disconnect() if (defined($dbh));
  };
  $dbh = 0;
  $dbh = DBI->connect($config->{sql}->{DBI}, $config->{sql}->{user}, $config->{sql}->{pass});
  unless (defined($dbh) && $dbh) {
    print STDERR "[exilog_sql] Can't open exilog database.\n";
    return 0;
  };
  return 1;
};


# --------------------------------------------------------------------------
# Generic Stubs, these are just frontends that call the backend-specific
# SQL subroutines for each database type.
sub write_message {
  no strict "refs";
  return &{ "_".$config->{sql}->{type}."_write_message" }(@_);
};

sub sql_select {
  no strict "refs";
  return &{ "_".$config->{sql}->{type}."_sql_select" }(@_);
};

sub sql_delete {
  no strict "refs";
  return &{ "_".$config->{sql}->{type}."_sql_delete" }(@_);
};

sub sql_optimize {
  no strict "refs";
  return &{ "_".$config->{sql}->{type}."_sql_optimize" }(@_);
};

sub sql_update_heartbeat {
  no strict "refs";
  return &{ "_".$config->{sql}->{type}."_sql_update_heartbeat" }(@_);
};

sub sql_queue_add {
  no strict "refs";
  return &{ "_".$config->{sql}->{type}."_sql_queue_add" }(@_);
};

sub sql_queue_update {
  no strict "refs";
  return &{ "_".$config->{sql}->{type}."_sql_queue_update" }(@_);
};

sub sql_queue_delete {
  no strict "refs";
  return &{ "_".$config->{sql}->{type}."_sql_queue_delete" }(@_);
};

sub sql_queue_set_action {
  no strict "refs";
  return &{ "_".$config->{sql}->{type}."_sql_queue_set_action" }(@_);
};

sub sql_queue_clear_action {
  no strict "refs";
  return &{ "_".$config->{sql}->{type}."_sql_queue_clear_action" }(@_);
};

sub sql_count {
  no strict "refs";
  return &{ "_".$config->{sql}->{type}."_sql_count" }(@_);
};
# --------------------------------------------------------------------------


# --------------------------------------------------------------------------
# PostgreSQL functions
sub _pgsql_sql_count {
  my $where = shift;
  my $criteria = shift || {};

  my $sql = "SELECT ".
            "COUNT(*) ".
            "FROM ".$where.
            ((scalar keys %{ $criteria } ) ? " "._build_WHERE($criteria) : "" );

  my $sh = $dbh->prepare($sql);
  $sh->execute;
  my $tmp = $sh->fetchrow_arrayref();
  return @{$tmp}[0];
};

# Postgres has no REPLACE command so the best thing to do is
# check to see if there exists any heartbeat record before
# attempting to UPDATE one. If it's not there, lets INSERT one.
sub _pgsql_sql_update_heartbeat {
  my $now = time();
  my $existing_beat = $dbh->do("SELECT timestamp from heartbeats WHERE server = '". $config->{agent}->{server} ."'");

  if ($existing_beat != '1') {
      $dbh->do("INSERT INTO heartbeats(timestamp, server) VALUES('". $now ."', '". $config->{agent}->{server} ."')");
     }
      else
     {
      $dbh->do("UPDATE heartbeats SET timestamp = '". $now ."' WHERE server = '". $config->{agent}->{server} ."'");
     }
};

sub _pgsql_sql_queue_delete {
  my $spool_path = shift;

  $dbh->do("DELETE FROM queue WHERE spool_path=".$dbh->quote($spool_path));
};

sub _pgsql_sql_queue_update {
  my $hdr = shift;

  return unless (ref($hdr) eq 'HASH');

  my $server = $hdr->{server};
  my $message_id = $hdr->{message_id};
  delete $hdr->{server};
  delete $hdr->{message_id};

  # PostgreSQL is case sensitive by default. Nice feature,
  # but it complicates our life tremendously.
  # Since we want to keep indexes working, the columns in
  # this list are lowercased before they are inserted. Sigh.
  my @lowercase = ( 'mailfrom', 'recipients_delivered', 'recipients_pending' );
  foreach my $col (@lowercase) {
    $hdr->{$col} = lc($hdr->{$col}) if (edt($hdr,$col));
  };

  my @tmp;
  foreach my $item (keys %{ $hdr }) {
    push @tmp, $item.'='.$dbh->quote($hdr->{$item});
  };

  $dbh->do("UPDATE queue SET ".join(",",@tmp).
           " WHERE message_id=".$dbh->quote($message_id).
           " AND server=".$dbh->quote($server));
};

sub _pgsql_sql_queue_add {
  my $hdr = shift;

  return unless (ref($hdr) eq 'HASH');

  # PostgreSQL is case sensitive by default. Nice feature,
  # but it complicates our life tremendously.
  # Since we want to keep indexes working, the columns in
  # this list are lowercased before they are inserted. Sigh.
  my @lowercase = ( 'mailfrom', 'recipients_delivered', 'recipients_pending' );
  foreach my $col (@lowercase) {
    $hdr->{$col} = lc($hdr->{$col}) if (edt($hdr,$col));
  };

  my @fields = sort {$a cmp $b} keys(%{$hdr});
  my @vals = ();
  foreach (@fields) {
    push @vals, $dbh->quote($hdr->{$_});
  };

  $dbh->do("INSERT INTO queue (".join(',',@fields).") VALUES(".join(',',@vals).")");
};

sub _pgsql_sql_queue_set_action {
  my $server = shift;
  my $message_id = shift;
  my $action = shift;

  $dbh->do("UPDATE queue SET action=".$dbh->quote($action).
           " WHERE server=".$dbh->quote($server).
           " AND message_id=".$dbh->quote($message_id));
};

sub _pgsql_sql_queue_clear_action {
  my $server = shift;
  my $message_id = shift;

  $dbh->do("UPDATE queue SET action=NULL WHERE server=".$dbh->quote($server).
           " AND message_id=".$dbh->quote($message_id));
};

sub _pgsql_sql_optimize {
  return 1; #postgres doesn't need to do anything as long as autovaccum is on
};

sub _pgsql_sql_delete {
  my $where = shift || "nothing";
  my $criteria = shift || {};

  my $sql = "DELETE FROM ".$where.
            ((scalar keys %{ $criteria } ) ? " "._build_WHERE($criteria) : "" );

  my $sh = $dbh->prepare($sql);
  my $num = $sh->execute;
  $sh->finish;

  return (($num eq '0E0') ? 0 : $num);
};

sub _pgsql_sql_select {
  my $where = shift;
  my @what = @{ (shift || [ "*" ]) };
  my $criteria = shift || {};
  my $order_by = shift || "";
  my $order_direction = shift || "DESC";
  my $limit_min = shift;
  my $limit_max = shift;
  my $distinct = shift;

  my $sql = "SELECT ".
            (defined($distinct) ? "DISTINCT " : "").
            join(", ", @what).
            " FROM ".$where.
            ((scalar keys %{ $criteria } ) ? " "._build_WHERE($criteria) : "" ).
            ($order_by ? " ORDER BY ".$order_by." ".$order_direction : "").
            (defined($limit_min) ? " LIMIT ".$limit_min : "").
            (defined($limit_max) ? ",".$limit_max : "");

  return _fetch_multirow($where, $sql);
};

sub _pgsql_write_message {
  my $server = shift || 'default';
  my $h = shift;
  my $rc = 0;

  # PostgreSQL is case sensitive by default. Nice feature,
  # but it complicates our life tremendously.
  # Since we want to keep indexes working, the columns in
  # this list are lowercased before they are inserted. Sigh.
  my @lowercase = ( 'mailfrom', 'rcpt', 'rcpt_final', 'host_dns', 'host_helo', 'host_rdns' );
  foreach my $col (@lowercase) {
    $h->{data}->{$col} = lc($h->{data}->{$col}) if (edt($h->{data},$col));
  };

  # Special case: we only need to UPDATE the 'completed' field
  # in the messages table.
  if ( ($h->{table} eq 'messages') && (exists($h->{data}->{completed})) ) {
    my $rc = $dbh->do("UPDATE messages SET completed=".$dbh->quote($h->{data}->{completed}).
                      " WHERE message_id=".$dbh->quote($h->{data}->{message_id}).
                      " AND server=".$dbh->quote($server));
    if (defined($rc)) {
      return 1;
    }
    else {
      # error
      return 0;
    };
  }
  else {
    my @fields = sort {$a cmp $b} keys(%{$h->{data}});
    my @vals = ( $dbh->quote($server) );
    foreach (@fields) {
      push @vals, $dbh->quote(substr($h->{data}->{$_},0,255));
    };
    unshift @fields, 'server';

    my $sql = "INSERT INTO ".$h->{table}.' ("'.join('","',@fields).'") VALUES('.join(',',@vals).")";
    my $rc = $dbh->do($sql);

    if (defined($rc)) {
      return 1;
    }
    else {
      return 2 if ($dbh->errstr =~ /duplicate/i);
      print STDERR "SQL Error (code ".$dbh->err.") on '$h->{table}' with query: $sql\n";
      return 0;
    };
  };
};


# --------------------------------------------------------------------------
# MySQL functions
sub _mysql_sql_count {
  my $where = shift;
  my $criteria = shift || {};

  my $sql = "SELECT ".
            "COUNT(*) ".
            "FROM ".$where.
            ((scalar keys %{ $criteria } ) ? " "._build_WHERE($criteria) : "" );

  my $sh = $dbh->prepare($sql);
  $sh->execute;
  my $tmp = $sh->fetchrow_arrayref();
  return @{$tmp}[0];
};

sub _mysql_sql_update_heartbeat {
  my $now = time();

  $dbh->do("REPLACE heartbeats SET server='". $config->{agent}->{server} ."', timestamp='". $now ."'");
};

sub _mysql_sql_queue_delete {
  my $spool_path = shift;

  $dbh->do("DELETE FROM queue WHERE spool_path=".$dbh->quote($spool_path));
};

sub _mysql_sql_queue_update {
  my $hdr = shift;

  return unless (ref($hdr) eq 'HASH');

  my $server = $hdr->{server};
  my $message_id = $hdr->{message_id};
  delete $hdr->{server};
  delete $hdr->{message_id};

  my @tmp;
  foreach my $item (keys %{ $hdr }) {
    push @tmp, $item.'='.$dbh->quote($hdr->{$item});
  };

  $dbh->do("UPDATE queue SET ".join(",",@tmp).
           " WHERE message_id=".$dbh->quote($message_id).
           " AND server=".$dbh->quote($server));
};

sub _mysql_sql_queue_add {
  my $hdr = shift;

  return unless (ref($hdr) eq 'HASH');

  my @fields = sort {$a cmp $b} keys(%{$hdr});
  my @vals = ();
  foreach (@fields) {
    push @vals, $dbh->quote($hdr->{$_});
  };

  $dbh->do("INSERT INTO queue (".join(',',@fields).") VALUES(".join(',',@vals).")");
};

sub _mysql_sql_queue_set_action {
  my $server = shift;
  my $message_id = shift;
  my $action = shift;

  $dbh->do("UPDATE queue SET action=".$dbh->quote($action).
           " WHERE server=".$dbh->quote($server).
           " AND message_id=".$dbh->quote($message_id));
};

sub _mysql_sql_queue_clear_action {
  my $server = shift;
  my $message_id = shift;
  
  $dbh->do("UPDATE queue SET action=NULL WHERE server=".$dbh->quote($server).
           " AND message_id=".$dbh->quote($message_id));
};


sub _mysql_sql_optimize {
  my $where = shift || "nothing";

  my $sql = "OPTIMIZE TABLE ".$where;
  my $sh = $dbh->prepare($sql);
  $sh->execute;
  $sh->finish;

  return 1;
};

sub _mysql_sql_delete {
  my $where = shift || "nothing";
  my $criteria = shift || {};

  my $sql = "DELETE FROM ".$where.
            ((scalar keys %{ $criteria } ) ? " "._build_WHERE($criteria) : "" );

  my $sh = $dbh->prepare($sql);
  my $num = $sh->execute;
  $sh->finish;

  return (($num eq '0E0') ? 0 : $num);
};

sub _mysql_sql_select {
  my $where = shift;
  my @what = @{ (shift || [ "*" ]) };
  my $criteria = shift || {};
  my $order_by = shift || "";
  my $order_direction = shift || "DESC";
  my $limit_min = shift;
  my $limit_max = shift;
  my $distinct = shift;

  my $sql = "SELECT ".
            (defined($distinct) ? "DISTINCT " : "").
            join(", ", @what).
            " FROM ".$where.
            ((scalar keys %{ $criteria } ) ? " "._build_WHERE($criteria) : "" ).
            ($order_by ? " ORDER BY ".$order_by." ".$order_direction : "").
            (defined($limit_min) ? " LIMIT ".$limit_min : "").
            (defined($limit_max) ? ",".$limit_max : "");

  return _fetch_multirow($where, $sql);
};

sub _mysql_write_message {
  my $server = shift || 'default';
  my $h = shift;
  my $rc = 0;

  # Special case: we only need to UPDATE the 'completed' field
  # in the messages table.
  if ( ($h->{table} eq 'messages') && (exists($h->{data}->{completed})) ) {
    my $rc = $dbh->do("UPDATE messages SET completed=".$dbh->quote($h->{data}->{completed}).
                      " WHERE message_id=".$dbh->quote($h->{data}->{message_id}).
                      " AND server=".$dbh->quote($server));
    if (defined($rc)) {
      return 1;
    }
    else {
      # error
      return 0;
    };
  }
  else {
    my @fields = sort {$a cmp $b} keys(%{$h->{data}});
    my @vals = ( $dbh->quote($server) );
    foreach (@fields) {
      push @vals, $dbh->quote(substr($h->{data}->{$_},0,255));
    };
    unshift @fields, 'server';

    my $sql = "INSERT INTO ".$h->{table}." (".join(',',@fields).") VALUES(".join(',',@vals).")";
    my $rc = $dbh->do($sql);

    if (defined($rc)) {
      return 1;
    }
    else {
      # error 1062 means "Duplicate key".
      return 2 if ($dbh->err == 1062);
      print STDERR "SQL Error (code ".$dbh->err.") on '$h->{table}' with query: $sql\n";
      return 0;
    };
  };
};


# --------------------------------------------------------------------------
# misc subroutines used across several DB types
sub _fetch_multirow {
  my $table = shift;
  my $sql = shift;
  my $limit = shift || 0;

  my $a = [];
  my $sh = $dbh->prepare($sql);
  $sh->execute;
  while (my $tmp = $sh->fetchrow_hashref) {
    push @{ $a }, $tmp;
    $limit--;
    last if ($limit == 0);
  };
  $sh->finish;

  return $a;
};

sub _build_WHERE {
  my $criteria = shift || {};

  my @set = ();
  foreach my $col (keys %{ $criteria }) {
    next unless(defined($criteria->{$col}));

    if ( ($col eq "timestamp") ||
         ($col eq "completed") ||
         ($col eq "frozen") ||
         ($col eq "size") ) {
      # integer column
      my ($min,$max) = split / /,$criteria->{$col};

      if (defined($min)) {
        # greater than X
        push @set, $col." > ".$min;
      }
      if (defined($max)) {
        # smaller than X
        push @set, $col." < ".$max;
      }
    }
    elsif (ref($criteria->{$col}) eq 'ARRAY') {
      # array ref, use exact string match with OR
      my $str = "( ";
      foreach my $entry (@{ $criteria->{$col} }) {
        $str .= " ".$col." = ".$dbh->quote($entry)." OR";
      };
      chop($str);chop($str);
      $str .= " )";

      push @set, $str;
    }
    else {
      # string column
      if (($criteria->{$col} =~ /\%/) || ($criteria->{$col} =~ /\_/)) {
        # use ILIKE for PGSQL
        if ($config->{sql}->{type} eq 'pgsql') {
          push @set, $col." ILIKE ".$dbh->quote($criteria->{$col});
        }
        else {
          push @set, $col." LIKE ".$dbh->quote($criteria->{$col});
        };
      }
      else {
        push @set, $col." = ".$dbh->quote($criteria->{$col});
      };
    };
  };

  return " WHERE ".join(" AND ", @set);
};


1;