aboutsummaryrefslogtreecommitdiff
path: root/src/db.c
blob: 0c817a3ec30db0815338a56adc77a51a10964af5 (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
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
/***************************************************************
 * DB.C - Datatabase routines for NDO2DB daemon
 *
 * Copyright (c) 2005-2007 Ethan Galstad 
 *
 * Last Modified: 10-18-2007
 *
 **************************************************************/

/* include our project's header files */
#include "../include/config.h"
#include "../include/common.h"
#include "../include/io.h"
#include "../include/utils.h"
#include "../include/protoapi.h"
#include "../include/ndo2db.h"
#include "../include/dbhandlers.h"
#include "../include/db.h"

extern int errno;

extern ndo2db_dbconfig ndo2db_db_settings;
extern time_t ndo2db_db_last_checkin_time;

char *ndo2db_db_rawtablenames[NDO2DB_MAX_DBTABLES]={
	"instances",
	"conninfo",
	"objects",
	"objecttypes",
	"logentries",
	"systemcommands",
	"eventhandlers",
	"servicechecks",
	"hostchecks",
	"programstatus",
	"externalcommands",
	"servicestatus",
	"hoststatus",
	"processevents",
	"timedevents",
	"timedeventqueue",
	"flappinghistory",
	"commenthistory",
	"comments",
	"notifications",
	"contactnotifications",
	"contact_notif_methods",
	"acknowledgements",
	"statehistory",
	"downtimehistory",
	"scheduleddowntime",
	"configfiles",
	"configfilevariables",
	"runtimevariables",
	"contactstatus",
	"customvariablestatus",
	"",
	"",
	"",
	"",
	"",
	"",
	"",
	"",
	"",
	"commands",
	"timeperiods",
	"timeperiod_timeranges",
	"contactgroups",
	"contactgroup_members",
	"hostgroups",
	"hostgroup_members",
	"servicegroups",
	"servicegroup_members",
	"hostescalations",
	"hostescalation_contacts",
	"serviceescalations",
	"srvcescal_contacts",
	"hostdependencies",
	"servicedependencies",
	"contacts",
	"contact_addresses",
	"contact_notifcmds",
	"hosts",
	"host_parenthosts",
	"host_contacts",
	"services",
	"service_contacts",
	"customvariables",
	"host_contactgroups",
	"service_contactgroups",
	"hostescal_contactgroups",
	"srvcescal_contactgroups"
        };


char *ndo2db_db_tablenames[NDO2DB_MAX_DBTABLES];

/*
#define DEBUG_NDO2DB_QUERIES 1
*/

/****************************************************************************/
/* CONNECTION FUNCTIONS                                                     */
/****************************************************************************/

/* initialize database structures */
int ndo2db_db_init(ndo2db_idi *idi){
	register int x;

	if(idi==NULL)
		return NDO_ERROR;

	/* initialize db server type */
	idi->dbinfo.server_type=ndo2db_db_settings.server_type;

	/* initialize table names */
	for(x=0;x<NDO2DB_MAX_DBTABLES;x++){
		if((ndo2db_db_tablenames[x]=(char *)malloc(strlen(ndo2db_db_rawtablenames[x])+((ndo2db_db_settings.dbprefix==NULL)?0:strlen(ndo2db_db_settings.dbprefix))+1))==NULL)
			return NDO_ERROR;
		sprintf(ndo2db_db_tablenames[x],"%s%s",(ndo2db_db_settings.dbprefix==NULL)?"":ndo2db_db_settings.dbprefix,ndo2db_db_rawtablenames[x]);
	        }

	/* initialize other variables */
	idi->dbinfo.connected=NDO_FALSE;
	idi->dbinfo.error=NDO_FALSE;
	idi->dbinfo.instance_id=0L;
	idi->dbinfo.conninfo_id=0L;
	idi->dbinfo.latest_program_status_time=(time_t)0L;
	idi->dbinfo.latest_host_status_time=(time_t)0L;
	idi->dbinfo.latest_service_status_time=(time_t)0L;
	idi->dbinfo.latest_queued_event_time=(time_t)0L;
	idi->dbinfo.latest_realtime_data_time=(time_t)0L;
	idi->dbinfo.latest_comment_time=(time_t)0L;
	idi->dbinfo.clean_event_queue=NDO_FALSE;
	idi->dbinfo.last_notification_id=0L;
	idi->dbinfo.last_contact_notification_id=0L;
	idi->dbinfo.max_timedevents_age=ndo2db_db_settings.max_timedevents_age;
	idi->dbinfo.max_systemcommands_age=ndo2db_db_settings.max_systemcommands_age;
	idi->dbinfo.max_servicechecks_age=ndo2db_db_settings.max_servicechecks_age;
	idi->dbinfo.max_hostchecks_age=ndo2db_db_settings.max_hostchecks_age;
	idi->dbinfo.max_eventhandlers_age=ndo2db_db_settings.max_eventhandlers_age;
	idi->dbinfo.last_table_trim_time=(time_t)0L;
	idi->dbinfo.last_logentry_time=(time_t)0L;
	idi->dbinfo.last_logentry_data=NULL;
	idi->dbinfo.object_hashlist=NULL;

	/* initialize db structures, etc. */
	switch(idi->dbinfo.server_type){
	case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
		if(!mysql_init(&idi->dbinfo.mysql_conn)){
			syslog(LOG_USER|LOG_INFO,"Error: mysql_init() failed\n");
			return NDO_ERROR;
	                }
#endif
		break;
	case NDO2DB_DBSERVER_PGSQL:
#ifdef USE_PGSQL
		idi->dbinfo.pgsql_conn=NULL;
		idi->dbinfo.pgsql_result=NULL;
#endif
		break;
	case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
		if(!ora_oci_init()){
			syslog(LOG_USER|LOG_INFO,"Error: ora_oci_init() failed\n");
			return NDO_ERROR;
		}
#endif
		break;
	default:
		break;
	        }

	return NDO_OK;
        }


/* clean up database structures */
int ndo2db_db_deinit(ndo2db_idi *idi){
	register int x;

	if(idi==NULL)
		return NDO_ERROR;

	/* free table names */
	for(x=0;x<NDO2DB_MAX_DBTABLES;x++){
		if(ndo2db_db_tablenames[x])
			free(ndo2db_db_tablenames[x]);
		ndo2db_db_tablenames[x]=NULL;
	        }

	/* free cached object ids */
	ndo2db_free_cached_object_ids(idi);

	return NDO_OK;
        }


/* connects to the database server */
int ndo2db_db_connect(ndo2db_idi *idi){
	char connect_string[NDO2DB_INPUT_BUFFER];
	int result=NDO_OK;

	if(idi==NULL)
		return NDO_ERROR;

	/* we're already connected... */
	if(idi->dbinfo.connected==NDO_TRUE)
		return NDO_OK;

	switch(idi->dbinfo.server_type){
	case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
		if(!mysql_real_connect(&idi->dbinfo.mysql_conn,ndo2db_db_settings.host,ndo2db_db_settings.username,ndo2db_db_settings.password,ndo2db_db_settings.dbname,ndo2db_db_settings.port,NULL,0)){

			mysql_close(&idi->dbinfo.mysql_conn);
			syslog(LOG_USER|LOG_INFO,"Error: Could not connect to MySQL database: %s",mysql_error(&idi->dbinfo.mysql_conn));
			result=NDO_ERROR;
			idi->disconnect_client=NDO_TRUE;
		        }
		else{
			idi->dbinfo.connected=NDO_TRUE;
			syslog(LOG_USER|LOG_INFO,"Successfully connected to MySQL database");
		        }
#endif
		break;
	case NDO2DB_DBSERVER_PGSQL:
#ifdef USE_PGSQL
		snprintf(connect_string,sizeof(connect_string)-1,"host='%s' port=%d dbname='%s' user='%s' password='%s'",ndo2db_db_settings.host,ndo2db_db_settings.port,ndo2db_db_settings.dbname,ndo2db_db_settings.username,ndo2db_db_settings.password);
		connect_string[sizeof(connect_string)-1]='\x0';
		idi->dbinfo.pgsql_conn=PQconnectdb(connect_string);

		if(PQstatus(idi->dbinfo.pgsql_conn)==CONNECTION_BAD){
			PQfinish(idi->dbinfo.pgsql_conn);
			syslog(LOG_USER|LOG_INFO,"Error: Could not connect to PostgreSQL database: %s",PQerrorMessage(idi->dbinfo.pgsql_conn));
			result=NDO_ERROR;
			idi->disconnect_client=NDO_TRUE;
		        }
		else{
			idi->dbinfo.connected=NDO_TRUE;
			syslog(LOG_USER|LOG_INFO,"Successfully connect to PostgreSQL database");
		        }
#endif
		break;
	case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
		if(!ora_oci_connect(ndo2db_db_settings.username,ndo2db_db_settings.password,ndo2db_db_settings.dbname)){
			syslog(LOG_USER|LOG_INFO,"Error: Could not connect to Oracle database: ora_oci_connect(\"%s\", \"%s\", \"%s\") %s",ndo2db_db_settings.username,ndo2db_db_settings.password,ndo2db_db_settings.dbname,ora_oci_error());
			result=NDO_ERROR;
			idi->disconnect_client=NDO_TRUE;
		}
		else{
			idi->dbinfo.connected=NDO_TRUE;
			syslog(LOG_USER|LOG_INFO,"Successfully connected to Oracle database");
		}

		break;
#endif
	default:
		break;
	        }

	return result;
        }


/* disconnects from the database server */
int ndo2db_db_disconnect(ndo2db_idi *idi){

	if(idi==NULL)
		return NDO_ERROR;

	/* we're not connected... */
	if(idi->dbinfo.connected==NDO_FALSE)
		return NDO_OK;

	switch(idi->dbinfo.server_type){
	case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
		/* close the connection to the database server */		
		mysql_close(&idi->dbinfo.mysql_conn);
		syslog(LOG_USER|LOG_INFO,"Successfully disconnected from MySQL database");
#endif
		break;
	case NDO2DB_DBSERVER_PGSQL:
#ifdef USE_PGSQL
		/* close database connection and cleanup */
		if(PQstatus(idi->dbinfo.pgsql_conn)!=CONNECTION_BAD)
			PQfinish(idi->dbinfo.pgsql_conn);
		syslog(LOG_USER|LOG_INFO,"Successfully disconnected from PostgreSQL database");
#endif
		break;
	case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
		/* close database connection and cleanup */
		if (!ora_oci_disconnect()) {
			syslog(LOG_USER|LOG_INFO,"Successfully disconnected from Oracle database");
		} else {
			syslog(LOG_USER|LOG_INFO,"Failed to disconnect from Oracle database");
		}
#endif
		break;
	default:
		break;
	        }

	return NDO_OK;
        }


/* post-connect routines */
int ndo2db_db_hello(ndo2db_idi *idi){
	char *buf=NULL;
	char *ts=NULL;
	int result=NDO_OK;
	int have_instance=NDO_FALSE;
	time_t current_time;

	/* make sure we have an instance name */
	if(idi->instance_name==NULL)
		idi->instance_name=strdup("default");

	/* get existing instance */
	if(asprintf(&buf,"SELECT id FROM %s WHERE instance_name='%s'",ndo2db_db_tablenames[NDO2DB_DBTABLE_INSTANCES],idi->instance_name)==-1)
		buf=NULL;
	if((result=ndo2db_db_query(idi,buf))==NDO_OK){
		switch(idi->dbinfo.server_type){
		case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
			idi->dbinfo.mysql_result=mysql_store_result(&idi->dbinfo.mysql_conn);
			if((idi->dbinfo.mysql_row=mysql_fetch_row(idi->dbinfo.mysql_result))!=NULL){
				ndo2db_convert_string_to_unsignedlong(idi->dbinfo.mysql_row[0],&idi->dbinfo.instance_id);
				have_instance=NDO_TRUE;
		                }
			mysql_free_result(idi->dbinfo.mysql_result);
			idi->dbinfo.mysql_result=NULL;
#endif
			break;
		case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
			idi->dbinfo.oracle_result=ora_oci_store_result();
			if((idi->dbinfo.oracle_row=ora_oci_fetch_row(idi->dbinfo.oracle_result))!=NULL){
				idi->dbinfo.instance_id = *(unsigned long *)idi->dbinfo.oracle_row[0];
				have_instance=NDO_TRUE;
			}
			ora_oci_free_result(idi->dbinfo.oracle_result);
			idi->dbinfo.oracle_result=NULL;
#endif
			break;
		default:
			break;
		        }
	        }
	free(buf);

	/* insert new instance if necessary */
	if(have_instance==NDO_FALSE){
/* XXX: reinstate: "INSERT INTO %s SET instance_name='%s'" */
		if(asprintf(&buf,"INSERT INTO %s (instance_name) VALUES ('%s')",ndo2db_db_tablenames[NDO2DB_DBTABLE_INSTANCES],idi->instance_name)==-1)
			buf=NULL;
		if((result=ndo2db_db_query(idi,buf))==NDO_OK){
			switch(idi->dbinfo.server_type){
			case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
				idi->dbinfo.instance_id=mysql_insert_id(&idi->dbinfo.mysql_conn);
#endif
				break;
			case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
				idi->dbinfo.instance_id=ora_oci_insert_id();
#endif
				break;
			default:
				break;
			        }
	                }
		free(buf);
	        }
	
	ts=ndo2db_db_timet_to_sql(idi,idi->data_start_time);

	/* record initial connection information */
	if(asprintf(&buf,"INSERT INTO %s (instance_id, connect_time, last_checkin_time, bytes_processed, lines_processed, entries_processed, agent_name, agent_version, disposition, connect_source, connect_type, data_start_time) VALUES ('%lu', SYSDATE, SYSDATE, '0', '0', '0', '%s', '%s', '%s', '%s', '%s',%s)"
		    ,ndo2db_db_tablenames[NDO2DB_DBTABLE_CONNINFO]
		    ,idi->dbinfo.instance_id
		    ,idi->agent_name
		    ,idi->agent_version
		    ,idi->disposition
		    ,idi->connect_source
		    ,idi->connect_type
		    ,ts
		   )==-1)
		buf=NULL;
	if((result=ndo2db_db_query(idi,buf))==NDO_OK){
		switch(idi->dbinfo.server_type){
		case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
			idi->dbinfo.conninfo_id=mysql_insert_id(&idi->dbinfo.mysql_conn);
#endif
			break;
		case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
			idi->dbinfo.conninfo_id=ora_oci_insert_id();
#endif
			break;
		default:
			break;
		        }
	        }
	free(buf);
	free(ts);

	/* get cached object ids... */
	ndo2db_get_cached_object_ids(idi);

	/* get latest times from various tables... */
	ndo2db_db_get_latest_data_time(idi,ndo2db_db_tablenames[NDO2DB_DBTABLE_PROGRAMSTATUS],"status_update_time",(unsigned long *)&idi->dbinfo.latest_program_status_time);
	ndo2db_db_get_latest_data_time(idi,ndo2db_db_tablenames[NDO2DB_DBTABLE_HOSTSTATUS],"status_update_time",(unsigned long *)&idi->dbinfo.latest_host_status_time);
	ndo2db_db_get_latest_data_time(idi,ndo2db_db_tablenames[NDO2DB_DBTABLE_SERVICESTATUS],"status_update_time",(unsigned long *)&idi->dbinfo.latest_service_status_time);
	ndo2db_db_get_latest_data_time(idi,ndo2db_db_tablenames[NDO2DB_DBTABLE_CONTACTSTATUS],"status_update_time",(unsigned long *)&idi->dbinfo.latest_contact_status_time);
	ndo2db_db_get_latest_data_time(idi,ndo2db_db_tablenames[NDO2DB_DBTABLE_TIMEDEVENTQUEUE],"queued_time",(unsigned long *)&idi->dbinfo.latest_queued_event_time);
	ndo2db_db_get_latest_data_time(idi,ndo2db_db_tablenames[NDO2DB_DBTABLE_COMMENTS],"entry_time",(unsigned long *)&idi->dbinfo.latest_comment_time);

	/* calculate time of latest realtime data */
	idi->dbinfo.latest_realtime_data_time=(time_t)0L;
	if(idi->dbinfo.latest_program_status_time>idi->dbinfo.latest_realtime_data_time)
		idi->dbinfo.latest_realtime_data_time=idi->dbinfo.latest_program_status_time;
	if(idi->dbinfo.latest_host_status_time>idi->dbinfo.latest_realtime_data_time)
		idi->dbinfo.latest_realtime_data_time=idi->dbinfo.latest_host_status_time;
	if(idi->dbinfo.latest_service_status_time>idi->dbinfo.latest_realtime_data_time)
		idi->dbinfo.latest_realtime_data_time=idi->dbinfo.latest_service_status_time;
	if(idi->dbinfo.latest_contact_status_time>idi->dbinfo.latest_realtime_data_time)
		idi->dbinfo.latest_realtime_data_time=idi->dbinfo.latest_contact_status_time;
	if(idi->dbinfo.latest_queued_event_time>idi->dbinfo.latest_realtime_data_time)
		idi->dbinfo.latest_realtime_data_time=idi->dbinfo.latest_queued_event_time;

	/* get current time */
	/* make sure latest time stamp isn't in the future - this will cause problems if a backwards system time change occurs */
	time(&current_time);
	if(idi->dbinfo.latest_realtime_data_time>current_time)
		idi->dbinfo.latest_realtime_data_time=current_time;

	/* set flags to clean event queue, etc. */
	idi->dbinfo.clean_event_queue=NDO_TRUE;

	/* set misc data */
	idi->dbinfo.last_notification_id=0L;
	idi->dbinfo.last_contact_notification_id=0L;

	return result;
        }


/* pre-disconnect routines */
int ndo2db_db_goodbye(ndo2db_idi *idi){
	int result=NDO_OK;
	char *buf=NULL;
	char *ts=NULL;

	ts=ndo2db_db_timet_to_sql(idi,idi->data_end_time);

	/* record last connection information */
	if(asprintf(&buf,"UPDATE %s SET disconnect_time=SYSDATE, last_checkin_time=SYSDATE, data_end_time=%s, bytes_processed='%lu', lines_processed='%lu', entries_processed='%lu' WHERE id='%lu'"
		    ,ndo2db_db_tablenames[NDO2DB_DBTABLE_CONNINFO]
		    ,ts
		    ,idi->bytes_processed
		    ,idi->lines_processed
		    ,idi->entries_processed
		    ,idi->dbinfo.conninfo_id
		   )==-1)
		buf=NULL;
	result=ndo2db_db_query(idi,buf);
	free(buf);

	free(ts);

	return result;
        }


/* checking routines */
int ndo2db_db_checkin(ndo2db_idi *idi){
	int result=NDO_OK;
	char *buf=NULL;

	/* record last connection information */
	if(asprintf(&buf,"UPDATE %s SET last_checkin_time=SYSDATE, bytes_processed='%lu', lines_processed='%lu', entries_processed='%lu' WHERE id='%lu'"
		    ,ndo2db_db_tablenames[NDO2DB_DBTABLE_CONNINFO]
		    ,idi->bytes_processed
		    ,idi->lines_processed
		    ,idi->entries_processed
		    ,idi->dbinfo.conninfo_id
		   )==-1)
		buf=NULL;
	result=ndo2db_db_query(idi,buf);
	free(buf);

	time(&ndo2db_db_last_checkin_time);

	return result;
        }



/****************************************************************************/
/* MISC FUNCTIONS                                                           */
/****************************************************************************/

/* escape a string for a SQL statement */
char *ndo2db_db_escape_string(ndo2db_idi *idi, char *buf){
	register int x,y,z;
	char *newbuf=NULL;

	if(idi==NULL || buf==NULL)
		return NULL;

	z=strlen(buf);

	/* allocate space for the new string */
	if((newbuf=(char *)malloc((z*2)+1))==NULL)
		return NULL;

	/* escape characters */
	for(x=0,y=0;x<z;x++){

		if(idi->dbinfo.server_type==NDO2DB_DBSERVER_MYSQL){
			if(buf[x]=='\'' || buf[x]=='\"' || buf[x]=='*' || buf[x]=='\\' || buf[x]=='$' || buf[x]=='?' || buf[x]=='.' || buf[x]=='^' || buf[x]=='+' || buf[x]=='[' || buf[x]==']' || buf[x]=='(' || buf[x]==')')
				newbuf[y++]='\\';
		        }
		else if(idi->dbinfo.server_type==NDO2DB_DBSERVER_PGSQL){
			if(! (isspace(buf[x]) || isalnum(buf[x]) || (buf[x]=='_')) )
				newbuf[y++]='\\';
		        }
		else if(idi->dbinfo.server_type==NDO2DB_DBSERVER_ORACLE){
			if(buf[x]=='\'' )
				newbuf[y++]='\'';
			}

		newbuf[y++]=buf[x];
	        }

	/* terminate escape string */
	newbuf [y]='\0';

	return newbuf;
        }


/* SQL query conversion of time_t format to date/time format */
char *ndo2db_db_timet_to_sql(ndo2db_idi *idi, time_t t){
	char *buf=NULL;

	switch(idi->dbinfo.server_type){
	case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
		asprintf(&buf,"FROM_UNIXTIME(%lu)",(unsigned long)t);
#endif
		break;
	case NDO2DB_DBSERVER_PGSQL:
#ifdef USE_PGSQL
		asprintf(&buf,"FROM_UNIXTIME(%lu)",(unsigned long)t);
#endif
		break;
	case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
		/* unixts2date is a PL/SQL function (defined in db/oracle.sql */
		asprintf(&buf,"(SELECT unixts2date(%lu) FROM DUAL)",(unsigned long)t);
#endif
		break;
	default:
		break;
	        }
	
	return buf;
        }


/* SQL query conversion of date/time format to time_t format */
char *ndo2db_db_sql_to_timet(ndo2db_idi *idi, char *field){
	char *buf=NULL;

	switch(idi->dbinfo.server_type){
	case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
		asprintf(&buf,"UNIX_TIMESTAMP(%s)",(field==NULL)?"":field);
#endif
		break;
	case NDO2DB_DBSERVER_PGSQL:
#ifdef USE_PGSQL
		asprintf(&buf,"UNIX_TIMESTAMP(%s)",(field==NULL)?"":field);
#endif
		break;
	case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
		asprintf(&buf,"((SELECT ((SELECT %s FROM %%s) - TO_DATE('01-01-1970 00:00:00','dd-mm-yyyy hh24:mi:ss')) * 86400) FROM DUAL)",(field==NULL)?"":field);
#endif
		break;
	default:
		break;
	        }
	
	return buf;
        }


/* executes a SQL statement */
int ndo2db_db_query(ndo2db_idi *idi, char *buf){
	int result=NDO_OK;
	int query_result=0;

	if(idi==NULL || buf==NULL)
		return NDO_ERROR;

	/* if we're not connected, try and reconnect... */
	if(idi->dbinfo.connected==NDO_FALSE){
		if(ndo2db_db_connect(idi)==NDO_ERROR)
			return NDO_ERROR;
		ndo2db_db_hello(idi);
	        }

#ifdef DEBUG_NDO2DB_QUERIES
	printf("%s\n\n",buf);
#endif

	ndo2db_log_debug_info(NDO2DB_DEBUGL_SQL,0,"%s\n",buf);

	switch(idi->dbinfo.server_type){
	case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
		if((query_result=mysql_query(&idi->dbinfo.mysql_conn,buf))){
			syslog(LOG_USER|LOG_INFO,"Error: mysql_query() failed for '%s'\n",buf);
			result=NDO_ERROR;
		        }
#endif
		break;
	case NDO2DB_DBSERVER_PGSQL:
#ifdef USE_PGSQL
		idi->dbinfo.pgsql_result==PQexec(idi->dbinfo.pgsql_conn,buf);
		if((query_result=PQresultStatus(idi->dbinfo.pgsql_result))!=PGRES_COMMAND_OK){
			syslog(LOG_USER|LOG_INFO,"Error: PQexec() failed for '%s'\n",buf);
			PQclear(idi->dbinfo.pgsql_result);
			result=NDO_ERROR;
	                }
#endif
		break;
	case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
		if((query_result=ora_oci_query(buf))){
			syslog(LOG_USER|LOG_INFO,"Error: ora_oci_query() failed with %s for '%s'\n",ora_oci_error(), buf);
			result=NDO_ERROR;
		        }
#endif
		break;
	default:
		break;
	        }

	/* handle errors */
	if(result==NDO_ERROR)
		ndo2db_handle_db_error(idi,query_result);

	return result;
        }

/* executes a SQL statement */
/*
 int ndo2db_db_merge_servicestatus(ndo2db_idi *idi, unsigned long v1, unsigned long v2, int v3, char *v4, char *v5, int v6, int v7, int v8, int v9, int v10, int v11, int v12, int v13, int v14, int v15, int v16, int v17, int v18, int v19, int v20, int v21, int v22, int v23, int v24, int v25, int v26, int v27, int v28, int v29, int v30, int v31, int v32, int v33, float v34, float v35, float v36, int v37, int v38, int v39, int v40, unsigned long v41, char *v42, char *v43, float v44, float v45, unsigned long v46)
*/
int ndo2db_db_query2(ndo2db_idi *idi, int type, void **data)
{
	int result=NDO_OK;
	int query_result=0;

	if(idi==NULL)
		return NDO_ERROR;

	/* if we're not connected, try and reconnect... */
	if(idi->dbinfo.connected==NDO_FALSE){
		if(ndo2db_db_connect(idi)==NDO_ERROR)
			return NDO_ERROR;
		ndo2db_db_hello(idi);
        }

	switch(idi->dbinfo.server_type){
	case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
/*
		if((query_result=ora_oci_merge_servicestatus(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46))){
*/
		if((query_result=ora_oci_query2(type, data))){
			syslog(LOG_USER|LOG_INFO,"Error: ora_oci_query2() failed\n");
			result=NDO_ERROR;
		        }
#endif
		break;
	default:
		break;
	        }

	/* handle errors */
	if(result==NDO_ERROR)
		ndo2db_handle_db_error(idi,query_result);

	return result;
}

/* frees memory associated with a query */
int ndo2db_db_free_query(ndo2db_idi *idi){

	if(idi==NULL)
		return NDO_ERROR;

	switch(idi->dbinfo.server_type){
	case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
#endif
		break;
	case NDO2DB_DBSERVER_PGSQL:
#ifdef USE_PGSQL
		PQclear(idi->dbinfo.pgsql_result);
#endif
		break;
	case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
		ora_oci_free_result(idi->dbinfo.oracle_result);
		idi->dbinfo.oracle_result=NULL;
#endif
		break;
	default:
		break;
	        }

	return NDO_OK;
        }


/* handles SQL query errors */
int ndo2db_handle_db_error(ndo2db_idi *idi, int query_result){
	int result=0;

	if(idi==NULL)
		return NDO_ERROR;

	/* we're not currently connected... */
	if(idi->dbinfo.connected==NDO_FALSE)
		return NDO_OK;

	switch(idi->dbinfo.server_type){
	case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
		result=mysql_errno(&idi->dbinfo.mysql_conn);
		if(result==CR_SERVER_LOST || result==CR_SERVER_GONE_ERROR){
			syslog(LOG_USER|LOG_INFO,"Error: Connection to MySQL database has been lost!\n");
			ndo2db_db_disconnect(idi);
			idi->disconnect_client=NDO_TRUE;
		        }
#endif
		break;
	case NDO2DB_DBSERVER_PGSQL:
#ifdef USE_PGSQL
		result=PQstatus(idi->dbinfo.pgsql_conn);
		if(result!=CONNECTION_OK){
			syslog(LOG_USER|LOG_INFO,"Error: Connection to PostgreSQL database has been lost!\n");
			ndo2db_db_disconnect(idi);
			idi->disconnect_client=NDO_TRUE;
	                }
#endif
		break;
		case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
		result=ora_oci_ping();
		if(result!=CONNECTION_OK){
			syslog(LOG_USER|LOG_INFO,"Error: Connection to Oracle database has been lost! %s (%d)\n", ora_oci_error(), result);
			ndo2db_db_disconnect(idi);
			idi->disconnect_client=NDO_TRUE;
	                }
#endif
		break;
	default:
		break;
	        }

	return NDO_OK;
        }


/* clears data from a given table (current instance only) */
int ndo2db_db_clear_table(ndo2db_idi *idi, char *table_name){
	char *buf=NULL;
	int result=NDO_OK;

	if(idi==NULL || table_name==NULL)
		return NDO_ERROR;

	if(asprintf(&buf,"DELETE FROM %s WHERE instance_id='%lu'"
		    ,table_name
		    ,idi->dbinfo.instance_id
		   )==-1)
		buf=NULL;

	result=ndo2db_db_query(idi,buf);
	free(buf);

	return result;
        }
		

/* gets latest data time value from a given table */
int ndo2db_db_get_latest_data_time(ndo2db_idi *idi, char *table_name, char *field_name, unsigned long *t){
	char *buf=NULL;
	char *ts[1];
	int result=NDO_OK;

	if(idi==NULL || table_name==NULL || field_name==NULL || t==NULL)
		return NDO_ERROR;

	*t=(time_t)0L;
	ts[0]=ndo2db_db_sql_to_timet(idi,field_name);
#ifndef USE_ORACLE
	if(asprintf(&buf,"SELECT %s AS latest_time FROM %s WHERE instance_id='%lu' ORDER BY %s DESC LIMIT 0,1"
		    ,ts[0]
		    ,table_name
		    ,idi->dbinfo.instance_id
		    ,field_name
		   )==-1)
		buf=NULL;
#else
	//XXX: Use ndo2db_db_sql_to_timet()
	if( asprintf(&buf,"SELECT ( ( ( SELECT * FROM ( SELECT %s FROM %s WHERE instance_id=%lu ORDER BY %s DESC) WHERE ROWNUM = 1 ) - TO_DATE( '01-01-1970 00:00:00','dd-mm-yyyy hh24:mi:ss' )) * 86400) AS latest_time FROM DUAL"
		    ,(field_name==NULL)?"":field_name
		    ,table_name
		    ,idi->dbinfo.instance_id
		    ,field_name
		   )==-1)
		buf=NULL;
#endif

	if((result=ndo2db_db_query(idi,buf))==NDO_OK){
		switch(idi->dbinfo.server_type){
		case NDO2DB_DBSERVER_MYSQL:
#ifdef USE_MYSQL
			idi->dbinfo.mysql_result=mysql_store_result(&idi->dbinfo.mysql_conn);
			if((idi->dbinfo.mysql_row=mysql_fetch_row(idi->dbinfo.mysql_result))!=NULL){
				ndo2db_convert_string_to_unsignedlong(idi->dbinfo.mysql_row[0],t);
		                }
			mysql_free_result(idi->dbinfo.mysql_result);
			idi->dbinfo.mysql_result=NULL;
#endif
			break;
			case NDO2DB_DBSERVER_ORACLE:
#ifdef USE_ORACLE
			idi->dbinfo.oracle_result=ora_oci_store_result();
			if((idi->dbinfo.oracle_row=ora_oci_fetch_row(idi->dbinfo.oracle_result))!=NULL){
				t = (unsigned long *)idi->dbinfo.oracle_row[0];
		                }
			ora_oci_free_result(idi->dbinfo.oracle_result);
			idi->dbinfo.oracle_result=NULL;
#endif
			break;
		default:
			break;
		        }
	        }
	free(buf);
	free(ts[0]);

	return result;
        }
		

/* trim/delete old data from a given table */
int ndo2db_db_trim_data_table(ndo2db_idi *idi, char *table_name, char *field_name, unsigned long t){
	char *buf=NULL;
	char *ts[1];
	int result=NDO_OK;

	if(idi==NULL || table_name==NULL || field_name==NULL)
		return NDO_ERROR;

	ts[0]=ndo2db_db_timet_to_sql(idi,(time_t)t);

	if(asprintf(&buf,"DELETE FROM %s WHERE instance_id='%lu' AND %s<%s"
		    ,table_name
		    ,idi->dbinfo.instance_id
		    ,field_name
		    ,ts[0]
		   )==-1)
		buf=NULL;

	result=ndo2db_db_query(idi,buf);
	free(buf);
	free(ts[0]);

	return result;
        }
		

/* performs some periodic table maintenance... */
int ndo2db_db_perform_maintenance(ndo2db_idi *idi){
	time_t current_time;

	/* get the current time */
	time(&current_time);

	/* trim tables */
	if(((unsigned long)current_time-60)>(unsigned long)idi->dbinfo.last_table_trim_time){
		if(idi->dbinfo.max_timedevents_age>0L)
			ndo2db_db_trim_data_table(idi,ndo2db_db_tablenames[NDO2DB_DBTABLE_TIMEDEVENTS],"scheduled_time",(time_t)((unsigned long)current_time-idi->dbinfo.max_timedevents_age));
		if(idi->dbinfo.max_systemcommands_age>0L)
			ndo2db_db_trim_data_table(idi,ndo2db_db_tablenames[NDO2DB_DBTABLE_SYSTEMCOMMANDS],"start_time",(time_t)((unsigned long)current_time-idi->dbinfo.max_systemcommands_age));
		if(idi->dbinfo.max_servicechecks_age>0L)
			ndo2db_db_trim_data_table(idi,ndo2db_db_tablenames[NDO2DB_DBTABLE_SERVICECHECKS],"start_time",(time_t)((unsigned long)current_time-idi->dbinfo.max_servicechecks_age));
		if(idi->dbinfo.max_hostchecks_age>0L)
			ndo2db_db_trim_data_table(idi,ndo2db_db_tablenames[NDO2DB_DBTABLE_HOSTCHECKS],"start_time",(time_t)((unsigned long)current_time-idi->dbinfo.max_hostchecks_age));
		if(idi->dbinfo.max_eventhandlers_age>0L)
			ndo2db_db_trim_data_table(idi,ndo2db_db_tablenames[NDO2DB_DBTABLE_EVENTHANDLERS],"start_time",(time_t)((unsigned long)current_time-idi->dbinfo.max_eventhandlers_age));
		idi->dbinfo.last_table_trim_time=current_time;
	        }

	return NDO_OK;
        }