File: pgsql.c

package info (click to toggle)
bandwidthd 2.0.1+cvs20090917-10
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 1,204 kB
  • sloc: sh: 3,008; ansic: 2,746; php: 1,263; yacc: 216; makefile: 162; lex: 36; sql: 27
file content (740 lines) | stat: -rw-r--r-- 24,502 bytes parent folder | download | duplicates (5)
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
#include "bandwidthd.h"
#include <setjmp.h>

extern struct config config;
extern unsigned int IpCount;
extern struct Broadcast *Broadcasts;
extern time_t ProgramStart;

jmp_buf pgsqljmp;

#ifdef HAVE_LIBPQ

#include "postgresql/libpq-fe.h"

#define MAX_PARAM_SIZE 200

// Check that tables exist and create them if not
PGconn *pgsqlCheckTables(PGconn *conn)
	{
	PGresult   *res;
	
    res = PQexec(conn, "select tablename from pg_tables where tablename='sensors';");

    if (PQresultStatus(res) != PGRES_TUPLES_OK)
        {
        syslog(LOG_ERR, "Postresql Select failed: %s", PQerrorMessage(conn));
        PQclear(res);
        PQfinish(conn);
        return(NULL);
        }

    if (PQntuples(res) != 1)
		{
		PQclear(res);
		res = PQexec(conn,  "CREATE TABLE bd_rx_log (sensor_id int, ip inet, timestamp timestamp with time zone DEFAULT now(), sample_duration int, packet_count int, total int, icmp int, udp int, tcp int, ftp int, http int, mail int, p2p int); create index bd_rx_log_sensor_id_ip_timestamp_idx on bd_rx_log (sensor_id, ip, timestamp); create index bd_rx_log_sensor_id_timestamp_idx on bd_rx_log(sensor_id, timestamp);");
        if (PQresultStatus(res) != PGRES_COMMAND_OK)
            {
            syslog(LOG_ERR, "Postresql create table bd_rx_log failed: %s", PQerrorMessage(conn));
            PQclear(res);
            PQfinish(conn);
            return(NULL);
            }
        PQclear(res);
		
		res = PQexec(conn, "CREATE TABLE bd_tx_log (sensor_id int, ip inet, timestamp timestamp with time zone DEFAULT now(), sample_duration int, packet_count int, total int, icmp int, udp int, tcp int, ftp int, http int, mail int, p2p int); create index bd_tx_log_sensor_id_ip_timestamp_idx on bd_tx_log (sensor_id, ip, timestamp); create index bd_tx_log_sensor_id_timestamp_idx on bd_tx_log(sensor_id, timestamp);");
        if (PQresultStatus(res) != PGRES_COMMAND_OK)
            {
            syslog(LOG_ERR, "Postresql create table bd_tx_log failed: %s", PQerrorMessage(conn));
            PQclear(res);
            PQfinish(conn);
            return(NULL);
            }
        PQclear(res);

		res = PQexec(conn, "CREATE TABLE bd_rx_total_log (sensor_id int, ip inet, timestamp timestamp with time zone DEFAULT now(), sample_duration int, packet_count int, total int, icmp int, udp int, tcp int, ftp int, http int, mail int, p2p int); create index bd_rx_total_log_sensor_id_timestamp_ip_idx on bd_rx_total_log (sensor_id, timestamp);");
        if (PQresultStatus(res) != PGRES_COMMAND_OK)
            {
            syslog(LOG_ERR, "Postresql create table bd_rx_total_log failed: %s", PQerrorMessage(conn));
            PQclear(res);
            PQfinish(conn);
            return(NULL);
            }
        PQclear(res);

		res = PQexec(conn, "CREATE TABLE bd_tx_total_log (sensor_id int, ip inet, timestamp timestamp with time zone DEFAULT now(), sample_duration int, packet_count int, total int, icmp int, udp int, tcp int, ftp int, http int, mail int, p2p int); create index bd_tx_total_log_sensor_id_timestamp_ip_idx on bd_tx_total_log (sensor_id, timestamp);");
        if (PQresultStatus(res) != PGRES_COMMAND_OK)
            {
            syslog(LOG_ERR, "Postresql create table bd_tx_total_log failed: %s", PQerrorMessage(conn));
            PQclear(res);
            PQfinish(conn);
            return(NULL);
            }
        PQclear(res);

		res = PQexec(conn, "CREATE TABLE sensors ( sensor_id serial PRIMARY KEY, sensor_name varchar, location int, build int default 0, uptime interval, reboots int default 0, interface varchar, description varchar, management_url varchar, last_connection timestamp with time zone );");
        if (PQresultStatus(res) != PGRES_COMMAND_OK)
            {
            syslog(LOG_ERR, "Postresql create table sensors failed: %s", PQerrorMessage(conn));
            PQclear(res);
            PQfinish(conn);
            return(NULL);
            }
        PQclear(res);

		res = PQexec(conn, "CREATE TABLE links (id1 int, id2 int, plot boolean default TRUE, last_update timestamp with time zone);");
        if (PQresultStatus(res) != PGRES_COMMAND_OK)
            {
            syslog(LOG_ERR, "Postresql create table links failed: %s", PQerrorMessage(conn));
            PQclear(res);
            PQfinish(conn);
            return(NULL);
            }
        PQclear(res);
		return(conn);
		}
	else
		{		
		PQclear(res);

		// Patch database to include mail column if it doesn't alread exist
	    res = PQexec(conn, "SELECT table_name, column_name from information_schema.columns where table_name = 'bd_rx_log' and column_name = 'mail';");

    	if (PQresultStatus(res) != PGRES_TUPLES_OK)
        	{
	        syslog(LOG_ERR, "Postresql Select failed: %s", PQerrorMessage(conn));
    	    PQclear(res);
        	PQfinish(conn);
	        return(NULL);
    	    }

	    if (PQntuples(res) != 1)
			{
			PQclear(res);

			res = PQexec(conn,  "alter table bd_rx_log add column mail int;");
    	    if (PQresultStatus(res) != PGRES_COMMAND_OK)
        	    {
            	syslog(LOG_ERR, "Add column failed: %s", PQerrorMessage(conn));
	            PQclear(res);
    	        PQfinish(conn);
        	    return(NULL);
	            }
    	    PQclear(res);

			res = PQexec(conn,  "alter table bd_tx_log add column mail int;");
    	    if (PQresultStatus(res) != PGRES_COMMAND_OK)
        	    {
            	syslog(LOG_ERR, "Add column failed: %s", PQerrorMessage(conn));
	            PQclear(res);
    	        PQfinish(conn);
        	    return(NULL);
	            }
    	    PQclear(res);

			res = PQexec(conn,  "alter table bd_rx_total_log add column mail int;");
    	    if (PQresultStatus(res) != PGRES_COMMAND_OK)
        	    {
            	syslog(LOG_ERR, "Add column failed: %s", PQerrorMessage(conn));
	            PQclear(res);
    	        PQfinish(conn);
        	    return(NULL);
	            }
    	    PQclear(res);

			res = PQexec(conn,  "alter table bd_tx_total_log add column mail int;");
    	    if (PQresultStatus(res) != PGRES_COMMAND_OK)
        	    {
            	syslog(LOG_ERR, "Add column failed: %s", PQerrorMessage(conn));
	            PQclear(res);
    	        PQfinish(conn);
        	    return(NULL);
	            }
    	    PQclear(res);
			}
		else
			{
			PQclear(res);
			}

		return(conn);
		}
	}

PGconn *pgsqlInit(void)
	{
	PGconn *conn = NULL;

	conn = PQconnectdb(config.db_connect_string);

    /* Check to see that the backend connection was successfully made */
   	if (PQstatus(conn) != CONNECTION_OK)
       	{
       	syslog(LOG_ERR, "Connection to database '%s' failed: %s", config.db_connect_string, PQerrorMessage(conn));
   	    PQfinish(conn);
        return(NULL);
   	    }



	return(conn);
	}

PGconn *pgsqlDetermineSensorID(PGconn *conn, char *sensor_id, char *sensor_name, char *interface)
	{
	const char *paramValues[3];
	char Values[2][MAX_PARAM_SIZE];
	PGresult   *res;

	paramValues[0] = Values[0];
	paramValues[1] = Values[1];

	strncpy(Values[0], sensor_name, MAX_PARAM_SIZE);
	strncpy(Values[1], interface, MAX_PARAM_SIZE);
	res = PQexecParams(conn, "select sensor_id from sensors where sensor_name = $1 and interface = $2;",
		2,       /* number of params */
        NULL,    /* let the backend deduce param type */
   	    paramValues,
        NULL,    /* don't need param lengths since text */
       	NULL,    /* default to all text params */
        0);      /* ask for binary results */
		
	if (PQresultStatus(res) != PGRES_TUPLES_OK)
   		{
       	syslog(LOG_ERR, "Postresql SELECT failed: %s", PQerrorMessage(conn));
   	    PQclear(res);
    	PQfinish(conn);
   		return(NULL);
        }

	if (PQntuples(res))
		{
		strncpy(sensor_id, PQgetvalue(res, 0, 0), MAX_PARAM_SIZE);
		PQclear(res);
		return(conn);
		}
	else
		{
		sensor_id[0] = '\0';
		return(conn);
		}
	}		

PGconn *pgsqlCreateSensorID(PGconn *conn, char *sensor_id)
	{
    const char *paramValues[3];
    char Values[3][MAX_PARAM_SIZE];
    PGresult   *res;
                                                                                                                             
    paramValues[0] = Values[0];
    paramValues[1] = Values[1];
    paramValues[2] = Values[2];

    res = PQexec(conn, "select nextval('sensors_sensor_id_seq'::Text);");
   	if (PQresultStatus(res) != PGRES_TUPLES_OK)
	   	{
        syslog(LOG_ERR, "Postresql select failed: %s", PQerrorMessage(conn));
    	PQclear(res);
	    PQfinish(conn);
    	return(NULL);
	    }

	strncpy(sensor_id, PQgetvalue(res, 0, 0), MAX_PARAM_SIZE);
    PQclear(res);

    strncpy(Values[0], config.sensor_name, MAX_PARAM_SIZE);
    strncpy(Values[1], config.dev, MAX_PARAM_SIZE);
	strncpy(Values[2], sensor_id, MAX_PARAM_SIZE);
	// Insert new sensor id
	res = PQexecParams(conn, "insert into sensors (sensor_name, interface, sensor_id) VALUES ($1, $2, $3);",
		3,       /* number of parameters */
   	    NULL,    /* let the backend deduce param type */
        paramValues,
   	   	NULL,    /* don't need param lengths since text */
		NULL,    /* default to all text params */
       	0);      /* ask for binary results */

   	if (PQresultStatus(res) != PGRES_COMMAND_OK)
    	{
       	syslog(LOG_ERR, "Postresql INSERT failed: %s", PQerrorMessage(conn));
        PQclear(res);
   	   	PQfinish(conn);
        return(NULL);
	    }
	else
		{
		PQclear(res);
		return(conn);
		}
	}

PGconn *pgsqlUpdateLinkStatus(PGconn *conn, char *sensor_id)
	{
	struct Broadcast *bc;
	unsigned long diff;
    const char *paramValues[3];
    char Values[3][MAX_PARAM_SIZE];
    PGresult   *res;
                        
    paramValues[0] = Values[0];
    paramValues[1] = Values[1];
    paramValues[2] = Values[2];

	for (bc = Broadcasts; bc; bc = bc->next)
		{
		strncpy(Values[0], sensor_id, MAX_PARAM_SIZE);
	    // Determine numeric sensor ID of other sensor
    	if (!(conn = pgsqlDetermineSensorID(conn, Values[1], bc->sensor_name, bc->interface)))
        	return(NULL);		
		
		if (!Values[1][0])
			{
			syslog(LOG_ERR, "Sensor '%s - %s' does not exist in database, skiping link update", bc->sensor_name, bc->interface);
			continue;
			}

		diff = time(NULL) - bc->received;
		snprintf(Values[2], MAX_PARAM_SIZE, "%lu", diff);
		res = PQexecParams(conn, "update links set last_update = now()-($3*interval '1 second') where (id1 = $1 and id2 = $2) or (id1 = $2 and id2 = $1);",
				3,       /* number of parameters */
       		    NULL,    /* let the backend deduce param type */
        		paramValues,
  	    		NULL,    /* don't need param lengths since text */
       			NULL,    /* default to all text params */
           		0);      /* ask for binary results */

	   	if (PQresultStatus(res) != PGRES_COMMAND_OK)
    		{
       		syslog(LOG_ERR, "Postresql Update of links table failed: %s", PQerrorMessage(conn));
        	PQclear(res);
   	   		PQfinish(conn);
        	return(NULL);
	    	}
		
		// There may be duplicate rows
		if (atol(PQcmdTuples(res)) > 0) 
			{
			PQclear(res); // Sucess, allow loop to fall through
			}
		else
			{
			PQclear(res);
			
			// Link doesn't exist so we must add it
			diff = time(NULL) - bc->received;
			snprintf(Values[2], MAX_PARAM_SIZE, "%lu", diff);
			res = PQexecParams(conn, "insert into links (id1, id2, last_update) values ($1, $2, now()-($3*interval '1 second'));",
					3,       /* number of parameters */
       		    	NULL,    /* let the backend deduce param type */
        			paramValues,
  	    			NULL,    /* don't need param lengths since text */
       				NULL,    /* default to all text params */
           			0);      /* ask for binary results */

		   	if (PQresultStatus(res) != PGRES_COMMAND_OK)
    			{
       			syslog(LOG_ERR, "Postresql Insert into links table failed: %s", PQerrorMessage(conn));
        		PQclear(res);
   	   			PQfinish(conn);
        		return(NULL);
	    		}
			PQclear(res);
			}
		}
	return(conn);
	}

PGconn *pgsqlUpdateSensorStatus(PGconn *conn, char *sensor_id)
	{
	const char *paramValues[5];
	char Values[5][MAX_PARAM_SIZE];
	PGresult   *res;

	paramValues[0] = Values[0];
	paramValues[1] = Values[1];
	paramValues[2] = Values[2];
	paramValues[3] = Values[3];
	paramValues[4] = Values[4];

    strncpy(Values[0], sensor_id, MAX_PARAM_SIZE);
	strncpy(Values[1], config.description, MAX_PARAM_SIZE);	
	strncpy(Values[2], config.management_url, MAX_PARAM_SIZE);	
	snprintf(Values[3], MAX_PARAM_SIZE, "%u", BUILD);
	snprintf(Values[4], MAX_PARAM_SIZE, "%lu", time(NULL)-ProgramStart);	
	res = PQexecParams(conn, "update sensors set description = $2, management_url = $3, last_connection = now(), build = $4, uptime = $5*interval '1 second' where sensor_id = $1;",
			5,       /* number of parameters */
       	    NULL,    /* let the backend deduce param type */
        	paramValues,
  	    	NULL,    /* don't need param lengths since text */
       		NULL,    /* default to all text params */
           	0);      /* ask for binary results */
		
	if (PQresultStatus(res) != PGRES_COMMAND_OK)
   		{
   		syslog(LOG_ERR, "Postresql UPDATE description and management_url failed: %s", PQerrorMessage(conn));
    	PQclear(res);
    	PQfinish(conn);
		return(NULL);
       	}
	else
		{
		PQclear(res);
		return(conn);
		}
  	}

PGconn *pgsqlIncReboots(PGconn *conn, char *sensor_id)
	{
	const char *paramValues[1];
	char Values[1][MAX_PARAM_SIZE];
	PGresult   *res;

	paramValues[0] = Values[0];

    strncpy(Values[0], sensor_id, MAX_PARAM_SIZE);
	res = PQexecParams(conn, "update sensors set reboots = reboots+1 where sensor_id = $1;",
			1,       /* number of parameters */
       	    NULL,    /* let the backend deduce param type */
        	paramValues,
  	    	NULL,    /* don't need param lengths since text */
       		NULL,    /* default to all text params */
           	0);      /* ask for binary results */
		
	if (PQresultStatus(res) != PGRES_COMMAND_OK)
   		{
   		syslog(LOG_ERR, "Postresql UPDATE reboots failed: %s", PQerrorMessage(conn));
    	PQclear(res);
    	PQfinish(conn);
		return(NULL);
       	}
	else
		{
		PQclear(res);
		return(conn);
		}
  	}
#endif

static void pgsqllngjmp(int signal)
	{
	longjmp(pgsqljmp, 1);	
	}

void pgsqlStoreIPData(struct IPData IncData[], struct extensions *extension_data)
	{
#ifdef HAVE_LIBPQ
	static char sensor_id[MAX_PARAM_SIZE] = { '\0' };
	static pid_t child = 0;

	struct IPData *IPData;
	unsigned int Counter;
	struct Statistics *Stats;
    PGresult   *res;
	PGconn *conn = NULL;
	char now[MAX_PARAM_SIZE];
	// This is higher than Values below for the extensions code
	const char *paramValues[22];
	char *sql1; 
	char *sql2;
	char Values[13][MAX_PARAM_SIZE];

	if (!config.output_database == DB_PGSQL)
		return;

	// Start of actual work
	paramValues[0] = Values[0];
	paramValues[1] = Values[1];
	paramValues[2] = Values[2];
	paramValues[3] = Values[3];	
	paramValues[4] = Values[4];
	paramValues[5] = Values[5];
	paramValues[6] = Values[6];
	paramValues[7] = Values[7];
	paramValues[8] = Values[8];
	paramValues[9] = Values[9];
	paramValues[10] = Values[10];
	paramValues[11] = Values[11];
	paramValues[12] = Values[12];

	// ************ Inititialize the db if it's not already

	// Do initialization in main thread in order to prevent doing sensor_id work repeatedly
	if (!sensor_id[0])	// Determine numeric sensor ID
		{
		/* I don't know how safe interupting pgsql's calls to the database 
		are, and since we're working in the main process here I picked a higher interval
		soas to interupt less frequently.  If I don't do this, the whole process gets locked up
		when the database is unreachable so it can only help. */
		alarm(config.interval*5);
		signal(SIGALRM, pgsqllngjmp);

		if (setjmp(pgsqljmp))
			{
			syslog(LOG_ERR, "Timeout when working with database");
			return;
			}
	
		syslog(LOG_INFO, "Initializing database info");
		conn = pgsqlInit();

		if (!conn)
			{
			syslog(LOG_ERR, "Could not connect to database");
			alarm(0);
			return;
			}

		if (!(conn = pgsqlCheckTables(conn))) // Create tables if neccisary
			{
			syslog(LOG_ERR, "Failed to check or create database tables");
			alarm(0);
			return;
			}

		if (!(conn = pgsqlDetermineSensorID(conn, sensor_id, config.sensor_name, config.dev)))
			{
			syslog(LOG_ERR, "Failed to determine sensor_id");
			alarm(0);
			return;
			}

		if (!sensor_id[0]) // Create a new sensor ID
			if (!(conn = pgsqlCreateSensorID(conn, sensor_id)))
				{
				syslog(LOG_ERR, "Failed to create new sensor_id");
				alarm(0);
				return;
				}

		pgsqlIncReboots(conn, sensor_id);
		
		PQfinish(conn);
		conn = NULL;

		syslog(LOG_INFO, "Sensor ID: %s", sensor_id);
		alarm(0);
		}


	// If we have a valid child see if he has exited
	if (child > 0)
		{
		if (waitpid(child, NULL, WNOHANG) == 0)
			{
			syslog(LOG_ERR, "Logging child still active: No response or slow database? Killing child.");
			kill(child, SIGKILL);
			waitpid(child, NULL, 0);
			}
		}

	// Fork to allow bandwidthd to operate un-interupted
	if ((child = fork()))
		return;

	conn = pgsqlInit();

	if (!conn)
		{
		syslog(LOG_ERR, "Could not connect to database");
		_exit(2);
		}

	// Update sensor state
	if (!(conn = pgsqlUpdateSensorStatus(conn, sensor_id)))
		{
		syslog(LOG_ERR, "Could not update sensor status");
		_exit(2);
		}

	// Update link state
	if (!(conn = pgsqlUpdateLinkStatus(conn, sensor_id)))
		{
		syslog(LOG_ERR, "Count not update link status");
		_exit(2);
		}

	// Determine Now
	res = PQexecParams(conn, "select now();",
		0,       /* number of params */
        NULL,    /* let the backend deduce param type */
   	    NULL,
        NULL,    /* don't need param lengths since text */
       	NULL,    /* default to all text params */
        0);      /* ask for binary results */
		
	if (PQresultStatus(res) != PGRES_TUPLES_OK)
   		{
       	syslog(LOG_ERR, "Postresql SELECT failed: %s", PQerrorMessage(conn));
   	    PQclear(res);
    	PQfinish(conn);
   		_exit(2);
        }

	strncpy(now, PQgetvalue(res, 0, 0), MAX_PARAM_SIZE);
	PQclear(res);

	// Begin transaction

	// **** Perform inserts
	strncpy(Values[0], sensor_id, MAX_PARAM_SIZE);
	strncpy(Values[1], now, MAX_PARAM_SIZE);
	snprintf(Values[2], MAX_PARAM_SIZE, "%llu", config.interval);
	for (Counter=0; Counter < IpCount; Counter++)
		{
        IPData = &IncData[Counter];

		if (IPData->ip == 0)
			{
			// This optimization allows us to quickly draw totals graphs for a sensor
			sql1 = "INSERT INTO bd_tx_total_log (sensor_id, timestamp, sample_duration, ip, packet_count,total, icmp, udp, tcp, ftp, http, mail, p2p) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13);";
			sql2 = "INSERT INTO bd_rx_total_log (sensor_id, timestamp, sample_duration, ip, packet_count,total, icmp, udp, tcp, ftp, http, mail, p2p) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13);";
			}
		else
			{
			sql1 = "INSERT INTO bd_tx_log (sensor_id, timestamp, sample_duration, ip, packet_count, total, icmp, udp, tcp, ftp, http, mail, p2p) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13);";
			sql2 = "INSERT INTO bd_rx_log (sensor_id, timestamp, sample_duration, ip, packet_count, total, icmp, udp, tcp, ftp, http, mail, p2p) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13);"; 
			}

        HostIp2CharIp(IPData->ip, Values[3]);

		Stats = &(IPData->Send);
		if (Stats->total > 512) // Don't log empty sets
			{
			// Log data in kilobytes
			snprintf(Values[4], MAX_PARAM_SIZE, "%llu", Stats->packet_count);
			snprintf(Values[5], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->total)/1024.0) + 0.5));
			snprintf(Values[6], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->icmp)/1024.0) + 0.5));
			snprintf(Values[7], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->udp)/1024.0) + 0.5));
			snprintf(Values[8], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->tcp)/1024.0) + 0.5));
			snprintf(Values[9], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->ftp)/1024.0) + 0.5));
			snprintf(Values[10], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->http)/1024.0) + 0.5));
			snprintf(Values[11], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->mail)/1024.0) + 0.5));
			snprintf(Values[12], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->p2p)/1024.0) + 0.5));

			res = PQexecParams(conn, sql1,
				13,       
	            NULL,    /* let the backend deduce param type */
    	        paramValues,
        	    NULL,    /* don't need param lengths since text */
            	NULL,    /* default to all text params */
	            1);      /* ask for binary results */

    		if (PQresultStatus(res) != PGRES_COMMAND_OK)
        		{
	        	syslog(LOG_ERR, "Postresql INSERT failed: %s", PQerrorMessage(conn));
	    	    PQclear(res);
    	    	PQfinish(conn);
	    	    conn = NULL;
        		_exit(2);
		        }
			PQclear(res);
			}
		Stats = &(IPData->Receive);
		if (Stats->total > 512) // Don't log empty sets
			{
			snprintf(Values[4], MAX_PARAM_SIZE, "%llu", Stats->packet_count);
			snprintf(Values[5], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->total)/1024.0) + 0.5));
			snprintf(Values[6], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->icmp)/1024.0) + 0.5));
			snprintf(Values[7], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->udp)/1024.0) + 0.5));
			snprintf(Values[8], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->tcp)/1024.0) + 0.5));
			snprintf(Values[9], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->ftp)/1024.0) + 0.5));
			snprintf(Values[10], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->http)/1024.0) + 0.5));
			snprintf(Values[11], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->mail)/1024.0) + 0.5));
			snprintf(Values[12], MAX_PARAM_SIZE, "%llu", (long long unsigned int)((((double)Stats->p2p)/1024.0) + 0.5));

			res = PQexecParams(conn, sql2,
				13,       
            	NULL,    /* let the backend deduce param type */
	            paramValues,
    	        NULL,    /* don't need param lengths since text */
        	    NULL,    /* default to all text params */
            	1);      /* ask for binary results */

	    	if (PQresultStatus(res) != PGRES_COMMAND_OK)
    	    	{
	    	    syslog(LOG_ERR, "Postresql INSERT failed: %s", PQerrorMessage(conn));
    	    	PQclear(res);
	        	PQfinish(conn);
		        conn = NULL;
        		_exit(2);
	        	}
			PQclear(res);
			}		
		}

	// Insert extension data
	if (extension_data)
		{
		char *sql;
		char *ptr;
		int len, Counter;
		int fields;
		struct extensions *extptr;

		// Allocate SQL buffer;
		for(extptr = extension_data, len=200, fields=0; extptr; extptr = extptr->next)
			{
			len += strlen(extptr->name)+6;
			fields++;
			}

		if (fields > 20)
			{
			fields = 20;
			syslog(LOG_ERR, "pgsql: This module limited to 20 extension fields");
			}

		sql = malloc(len);
		if (!sql)
			{
			syslog(LOG_ERR, "Could not allocate RAM for extension SQL statement. Size: %d", len);
			PQfinish(conn);
			conn = NULL;
			_exit(2);
			}

		// Write SQL statement
		ptr = sql;
		ptr += sprintf(ptr, "INSERT INTO extension_log (sensor_id, timestamp, "); 
		for(extptr = extension_data, Counter=0; Counter < fields; extptr = extptr->next, Counter++)
			{
			ptr += sprintf(ptr, "%s, ", extptr->name);			
			paramValues[Counter+2] = extptr->value;
			}
		ptr -= 2;
	
		ptr += sprintf(ptr, ") VALUES ($1, $2, ");

		for(extptr = extension_data, Counter=0; Counter < fields; extptr = extptr->next, Counter++)
			ptr += sprintf(ptr, "$%d, ", Counter+3);			
		ptr -= 2;

		ptr += sprintf(ptr, ");");

		res = PQexecParams(conn, sql,
			fields+2,       
            NULL,    /* let the backend deduce param type */
	        paramValues,
    	    NULL,    /* don't need param lengths since text */
        	NULL,    /* default to all text params */
            1);      /* ask for binary results */

	    if (PQresultStatus(res) != PGRES_COMMAND_OK)
    	   	{
	        syslog(LOG_ERR, "Postresql INSERT failed: %s", PQerrorMessage(conn));
    	   	PQclear(res);
	       	PQfinish(conn);
		    conn = NULL;
        	_exit(2);
	       	}
		PQclear(res);
		free(sql);
		}

	PQfinish(conn);
	_exit(0);
#else
	syslog(LOG_ERR, "Postgresql logging selected but postgresql support is not compiled into binary.  Please check the documentation in README, distributed with this software.");
#endif
	}