File: anna.cpp

package info (click to toggle)
nagircbot 0.0.33-2
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 296 kB
  • sloc: cpp: 3,293; sh: 208; makefile: 90; ansic: 66
file content (1244 lines) | stat: -rw-r--r-- 29,515 bytes parent folder | download
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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
/* (C) 2006-2011 by folkert@vanheusden.com GPLv2 applies */
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <signal.h>
#include <pwd.h>
#include <sys/types.h>
#include <regex.h>

#include "utils.h"
#include "pl.h"
extern "C" {
#include "error.h"
#include "ssl.h"
#include "log.h"
}

#define S_DISCONNECTED		1
#define S_CONNECTED		2
#define S_JOINING_CHANNEL	3
#define S_ON_CHANNEL		4
#define S_DISCONNECTING		127

#define L_HOST			1
#define L_FILE			2

#define ST_HARD			1
#define ST_SOFT			0

int check_interval = 60;	/* check for new events every 1 minute */
int default_sleep = 2;		/* initial sleep time between connect failures */
int max_sleep_time = 300;
double sleep_multiply_factor = 2.0;
int minimum_time_for_successfull_login = 25; // one needs to be on-channel for at least 5 seconds to be considered a successfull login
int join_timeout = 5;	// it should take no longer then 5 seconds to join a channel, otherwhise: abort connection and retry
int max_n_join_tries = 2;	// try 2 times to get on a channel
char *server = "localhost:6667";	/* default irc server */
char *channel = "#nagircbot";	/* default channel to connect to */
char *nick_prefix = "";   /* prefix text for all messages sent to channel */
char *keyword = NULL;	/* keyword for the channel to connect to */
char *nick = "nagircbot";
char *user = "nagircbot";
char *password = NULL;
int one_line = 1;
char *username = "Nagios IRC Bot " VERSION ", (C) www.vanheusden.com";	/* complete username */
int verbose = 255;		/* default is log everything */
char *statuslog = "/usr/local/nagios/var/status.log";
int statuslog_version = 2;
int statuslog_location = L_FILE;
char use_colors = 0;
char topic_summary = 0;
char hard_only = 1;
int max_time_last_host_update = 300, max_time_oldest_host_update = 3600, max_time_last_host_check = 300, max_time_oldest_host_check = 3 * 86400, max_time_last_service_check = 20 * 60, max_time_oldest_service_check = 3 * 86400, max_time_oldest_next_service_check = 20 * 60;
int irc_server_keep_alive = 60;	/* send an irc-command at least every 300 seconds (currently 'TIME') */
int announce_global_status_interval = 0;
time_t last_announce_global_status_interval = 0;
char critical_only = 0;
regex_t *filters = NULL;
int n_filters = 0;
int use_ssl       = 0;


server_t server_conn;

char *state_str[4] = { " OK ", "WARN", "CRIT", " ?? " };
char *color_str[4];
struct stats *prev = NULL;
int n_prev = 0;
char topic[4096] = { 0 };
time_t last_irc_io = 0;
char *pidfile = NULL;

int send_irc(server_t server_conn, char *format, ...)
{
	int rc;
	char buffer[4096];
	va_list ap;

	va_start(ap, format);
	vsnprintf(buffer, sizeof(buffer) - 3, format, ap);
	va_end(ap);

	if (verbose > 1) dolog("OUT: `%s'", buffer);

	strcat(buffer, "\r\n"); /* yes this is safe: check the vsnprintf command */

	rc = IRCWRITE(server_conn, buffer, strlen(buffer));
	if (rc == -1)
	{
		dolog("error sending: -1");
		return -1;
	}
	else if (rc == 0)
	{
		dolog("connection closed");
		return -1;
	}

	time(&last_irc_io);

	return 0;
}

int irc_set_nick(server_t server_conn, char *nick)
{
	if (send_irc(server_conn, "NICK %s", nick) == -1)
		return -1;

	return 0;
}

int irc_login(server_t server_conn, char *user, char *username, char *server, char *password)
{
	if (password != NULL && send_irc(server_conn, "PASS %s", password) == -1)
		return -1;

	if (irc_set_nick(server_conn, nick) == -1)
		return -1;

	/* FIXME: localhost must be, ehr, local host */
	if (send_irc(server_conn, "USER %s \"localhost\" \"%s\" :%s", user, server, username) == -1)
		return -1;

	return 0;
}

int irc_join_channel(server_t server_conn, char *channel, char *keyword)
{
	if (keyword != NULL)
		return send_irc(server_conn, "JOIN %s %s", channel, keyword);

	return send_irc(server_conn, "JOIN %s", channel);
}

int irc_topic(server_t server_conn, char *channel, char *topic)
{
	return send_irc(server_conn, "TOPIC %s :%s", channel, topic);
}

int check_ping(server_t server_conn, char *data)
{
	if (strncmp(data, "PING ", 5) == 0)
	{
		char *colon = strchr(data, ':');
		char *cr = strchr(data, '\r');
		char *lf = strchr(data, '\n');

		if (cr>lf && cr != NULL)
			cr[1] = 0x00;
		else if (lf != NULL)
			lf[1] = 0x00;
		if (colon)
		{
			if (send_irc(server_conn, "PONG %s", colon + 1) == -1)
				return -1;
		}
		else if (verbose > 1)
		{
			dolog("Malformed PING request (%s)", data);
		}
	}

	return 0;
}

int irc_privmsg(server_t server_conn, char *channel, char *msg)
{
	return send_irc(server_conn, "PRIVMSG %s :%s", channel, msg);
}

int irc_time(server_t server_conn)
{
	return send_irc(server_conn, "TIME");
}

void load_statuslog(char *statuslog, char is_file, char is_20_format, int prev_n_elements_in_stats_array, struct stats **pstats, int *n_stats)
{
	char reload = 0;

	for(;;)
	{
		int fd;

		/* open file or connection to nagios status socket */
		if (is_file == 1)     /* file */
			fd = open64(statuslog, O_RDONLY);
		else
			fd = connect_to(statuslog);
		if (fd == -1)
		{
			dolog("Failed to open nagios status-log at %s\n", statuslog);
			sleep(1);
			continue;
		}

		/* file/socket open, load data */
		if (is_20_format)
			parse_2_0_statuslog(fd, pstats, n_stats);
		else
			parse_1_0_statuslog(fd, pstats, n_stats);

		close(fd);

		if (*n_stats == prev_n_elements_in_stats_array)
		{
			break;
		}

		dolog("Number of elements in status-log is different (%d) from previous run (%d), retrying", *n_stats, prev_n_elements_in_stats_array);
		reload = 1;
		sleep(1);

		/* remember the current number of elements for this load */
		prev_n_elements_in_stats_array = *n_stats;
		/* and free up - it'll be reloaded */
		free_stats_array(*pstats, *n_stats);
	}

	if (reload)
	{
		dolog("Size of status.log is stable (%d elements), continuing", *n_stats);
	}
}

int emit_status(server_t server_conn, char *channel, struct stats *what)
{
	int loop;
	char buffer[4096];
	char *prefix = "", *suffix = "";
	struct tm *ptm = localtime(&what -> last_state_change);

	if (use_colors)
	{
		prefix = color_str[what -> current_state];
		suffix = "\03";
	}

	if (n_filters || one_line)
	{
		snprintf(buffer, sizeof(buffer), "%s%s%04d/%02d/%02d %02d:%02d %s %s %s %s%s",
				prefix,
				nick_prefix,
				ptm -> tm_year + 1900, ptm -> tm_mon + 1, ptm -> tm_mday, ptm -> tm_hour, ptm -> tm_min,
				state_str[what -> current_state],
				what -> host_name?what -> host_name:"",
				what -> service_description?what -> service_description:"",
				what -> plugin_output?what -> plugin_output:"",
				suffix);
	}

	/* regexp matches? then do not emit */
	for(loop=0; loop<n_filters; loop++)
	{
		int rc = regexec(&filters[loop], buffer, 0, NULL, 0);

		if (rc == 0)
		{
#ifdef _DEBUG
			printf("Line '%s' filtered by regexp\n", buffer);
#endif
			return 0; /* assume we're still on channel */
		}
		else if (rc != REG_NOMATCH)
		{
			char buffer[4096];

			regerror(rc, &filters[loop], buffer, sizeof(buffer));

			dolog("Executing of regexp failed: %s", buffer);
		}
	}

	if (one_line)
	{
		if (irc_privmsg(server_conn, channel, buffer) == -1)
			return -1;
	}
	else
	{
		snprintf(buffer, sizeof(buffer), "%s%04d/%02d/%02d %02d:%02d",
				prefix,
				ptm -> tm_year + 1900, ptm -> tm_mon + 1, ptm -> tm_mday, ptm -> tm_hour, ptm -> tm_min);

		if (irc_privmsg(server_conn, channel, buffer) == -1) return -1;

		if (irc_privmsg(server_conn, channel, state_str[what -> current_state]) == -1) return -1;

		if (irc_privmsg(server_conn, channel, (char *)(what -> host_name?what -> host_name:"")) == -1) return -1;

		if (irc_privmsg(server_conn, channel, (char *)(what -> service_description?what -> service_description:"")) == -1) return -1;

		snprintf(buffer, sizeof(buffer), "%s%s", (char *)(what -> plugin_output?what -> plugin_output:""), suffix);
		if (irc_privmsg(server_conn, channel, buffer) == -1) return -1;
	}

	return 0;
}

void calc_statistics(struct stats *stats, int n_stats, char list_all_problems, char always_notify, char also_acknowledged, char hide_ok, char *buffer, int buffer_size)
{
	int n_critical=0, n_warning=0, n_ok=0, n_up=0, n_down=0, n_unreachable=0, n_pending=0;

	calc_stats_stats(stats, n_stats, list_all_problems, always_notify, also_acknowledged, hide_ok, &n_critical, &n_warning, &n_ok, &n_up, &n_down, &n_unreachable, &n_pending);
	snprintf(buffer, buffer_size, "Critical: %d, warning: %d, ok: %d, up: %d, down: %d, unreachable: %d, pending: %d",
			n_critical, n_warning, n_ok, n_up, n_down, n_unreachable, n_pending);
}

int check_nagios_status(server_t server_conn)
{
	struct stats *cur = NULL;
	int n_cur = 0;
	int loop;
	int any_shown = 0;
	time_t now = time(NULL);
#ifdef _DEBUG
	printf("Checking @ %s", ctime(&now));
#endif

	load_statuslog(statuslog, statuslog_location == L_FILE?1:0, statuslog_version == 2?1:0, n_prev, &cur, &n_cur);

	if (topic_summary)
	{
		char buffer[4096];

		calc_statistics(cur, n_cur, 0, 0, 0, 1, buffer, sizeof(buffer));

		if (strcmp(topic, buffer) != 0)
		{
			strcpy(topic, buffer);

			if (irc_topic(server_conn, channel, buffer) == -1)
				return -1;
		}
	}

	if (announce_global_status_interval > 0)
	{
		if ((now - last_announce_global_status_interval) >= announce_global_status_interval)
		{
			char buffer[4096];

			last_announce_global_status_interval = now;

			calc_statistics(cur, n_cur, 0, 0, 0, 1, buffer, sizeof(buffer));

			if (irc_privmsg(server_conn, channel, buffer) == -1)
				return -1;
		}
	}

	for(loop=0; loop<n_cur; loop++)
	{
		char show = 0;
		int prev_index = -1;

		if (prev)
			prev_index = find_index_by_host_and_service(prev, n_prev, cur[loop].host_name, cur[loop].service_description);

		if (prev_index == -1)
		{
			if (prev == NULL)
			{
				if (should_i_show_entry(cur, n_cur, loop, 0, 0, 0, 1))
				{
					show = 1;
				}
			}
			else
			{
				show = 1;
			}
		}
		else
		{
			if (hard_only)
			{
				if (prev[prev_index].state_type == ST_HARD && cur[loop].state_type == ST_HARD)
				{
					if (prev[prev_index].current_state != cur[loop].current_state)
					{
						show = 1;
					}
				}
				else if (prev[prev_index].state_type == ST_SOFT && cur[loop].state_type == ST_HARD)
				{
					if (cur[loop].current_state != 0)
					{
						show = 1;
					}
				}
			}
			else
			{
				if (prev[prev_index].current_state != cur[loop].current_state)
				{
					show = 1;
				}
			}
		}

		/* also 'unknown' is emitted when 'critical_only' is selected */
		if (show && cur[loop].current_state < 2 && critical_only)
		{
			show = 0;
		}

		if (show)
		{
#ifdef _DEBUG
			if (prev != NULL && prev_index != -1)
			{
				printf("%s %s\n", cur[loop].host_name, cur[loop].service_description);
				printf("cur[current_state]: %d, prev[current_state]: %d\n", cur[loop].current_state, prev[prev_index].current_state);
				printf("cur[state_type]: %d, prev[state_type]: %d\n", cur[loop].state_type, prev[prev_index].state_type);
			}
#endif

#ifdef _DEBUG
			if (any_shown == 0)
			{
				any_shown = 1;
				dolog("emitting results");
			}
#endif
			if (emit_status(server_conn, channel, &cur[loop]) == -1)
				return -1;
		}
	}

	free_stats_array(prev, n_prev);
	prev = cur;
	n_prev = n_cur;

	return 0;
}

int resend_nagios_status(server_t server_conn, char *to_who)
{
	int something_sent = 0;

	if (n_prev == 0)
		return irc_privmsg(server_conn, to_who, "not available yet");

	for(int loop=0; loop<n_prev; loop++)
	{
		if (should_i_show_entry(prev, n_prev, loop, 0, 0, 0, 1))
		{
			something_sent = 1;

			if (emit_status(server_conn, to_who, &prev[loop]) == -1)
				return -1;
		}
	}

	if (!something_sent)
		return irc_privmsg(server_conn, to_who, "all fine");

	return 0;
}

int send_help(server_t server_conn, char *to_who)
{
	if (irc_privmsg(server_conn, to_who, "'resend' lets the bot resend the current nagios status in a private message") == -1)
		return -1;

	if (irc_privmsg(server_conn, to_who, "'statistics' sends you the statistics") == -1)
		return -1;

	if (irc_privmsg(server_conn, to_who, "'check' verifies if Nagios is still checking hosts/services") == -1)
		return -1;

	return 0;
}

int reload_statuslog(void)
{
	int fd_sl;
	struct stats *cur = NULL;
	int n_cur = 0;

	if (verbose > 1) dolog("reload_statuslog started");

	if (statuslog_location == L_FILE)     /* file */
		fd_sl = open64(statuslog, O_RDONLY);
	else
		fd_sl = connect_to(statuslog);

	if (fd_sl != -1)
	{
		if (statuslog_version == 2)
			parse_2_0_statuslog(fd_sl, &cur, &n_cur);
		else
			parse_1_0_statuslog(fd_sl, &cur, &n_cur);

		close(fd_sl);

		free_stats_array(prev, n_prev);
		prev = cur;
		n_prev = n_cur;

		return 0;
	}

	dolog("reload failed: %s", strerror(errno));

	return -1;
}

char * check_nagios()
{
	char *message = NULL;

	(void)check_max_age_last_check(prev, n_prev, max_time_last_host_update, max_time_oldest_host_update, max_time_last_host_check, max_time_oldest_host_check, max_time_last_service_check, max_time_oldest_service_check, max_time_oldest_next_service_check, &message);

	return message;
}

int do_nagircbot(server_t server_conn, char *channel)
{
	time_t last_check = 0;

	for(;;)
	{
		fd_set rfds;
		struct timeval tv;
		time_t now = time(NULL);

		if ((now - last_check) >= check_interval)
		{
			if (check_nagios_status(server_conn) == -1)
				return -1;

			last_check = now;
		}

		if (now >= (last_irc_io + irc_server_keep_alive))
		{
			if (irc_time(server_conn) == -1)
				return -1;
		}

		FD_ZERO(&rfds);
		FD_SET(server_conn.fd, &rfds);

		tv.tv_sec = max(check_interval - (now - last_check), 0);
		tv.tv_usec = 0;

		if (irc_server_keep_alive > 0)
		{
			tv.tv_sec = min(max(0, (last_irc_io + irc_server_keep_alive) - now), tv.tv_sec);
		}

		if (announce_global_status_interval > 0)
		{
			tv.tv_sec = min(max(0, (last_announce_global_status_interval + announce_global_status_interval) - now), tv.tv_sec);
		}

		if (select(server_conn.fd + 1, &rfds, NULL, NULL, &tv) == -1)
		{
			if (errno == EAGAIN || errno == EINTR)
				continue;

			error_exit("select() failed %s\n", strerror(errno));
		}

		if (FD_ISSET(server_conn.fd, &rfds))
		{
			char recv_buffer[4096];
			int rc = IRCREAD(server_conn, recv_buffer, sizeof(recv_buffer) - 1);

			if (rc == 0)
			{
				dolog("connection closed by IRC server");
				return -1;
			}
			else if (rc == -1)
			{
				if (errno != EAGAIN && errno != EINTR)
				{
					dolog("error transmitting data to IRC server: %s", strerror(errno));
					return -1;
				}
			}
			else
			{
				char *next_response = recv_buffer;
				char *response = NULL;
				char *cmd = NULL;
				char *crlf = NULL;

				recv_buffer[rc] = 0x00;

				while ((response = next_response)
				       && (crlf = strchr( response, '\r')))
				{
					if (*(crlf + 1) != '\n')
					{
						dolog( "Malformed server response: `%s' at `%s'.", recv_buffer, response );
						return -1;
					}

					*crlf = '\0';
					if (( crlf + 2 ) - recv_buffer < rc)
						next_response = crlf + 2;
					else
						next_response = NULL;

					if (verbose > 1) dolog("IN: `%s'", response);

					if (check_ping(server_conn, response) == -1)
						return -1;

					cmd = strchr(response, ' ');
					if (cmd)
					{
						while(*cmd == ' ') cmd++;

						if (strncmp(cmd, "KICK ", 5) == 0)
						{
							char *dummy = strchr(cmd, ' ');
							if (dummy)
							{
								while(*dummy == ' ') dummy++;
								dummy = strchr(dummy, ' ');
							}
							if (dummy)
							{
								while(*dummy == ' ') dummy++;

								if (strncmp(dummy, nick, strlen(nick)) == 0)
								{
									dolog("nagircbot got kicked (%s)", response);
									return -1;
								}
								else if (verbose > 1)
								{
									dolog("user %s got kicked from channel", dummy);
								}
							}
						}
						else if (strncmp(cmd, "PRIVMSG ", 8) == 0)
						{
							/* :flok!~flok@rammstein.amc.nl PRIVMSG nagircbot :test */

							char *to_me = &cmd[8];
							while(*to_me == ' ') to_me++;

							/* message to this bot? */
							if (strncmp(to_me, nick, strlen(nick)) == 0)
							{
								/* yes */
								char *msg = strchr(cmd, ':');
								char *from_who = response + 1;
								char *dummy = strchr(from_who, '!');

								if (msg != NULL && dummy != NULL)
								{
									msg++;
									*dummy = 0x00;

									if (strcasecmp(msg, "help") == 0)
									{
										int rc = 0;

										dolog("help requested by %s", from_who);

										rc |= irc_privmsg(server_conn, from_who, "resend - resend the last known problems");
										rc |= irc_privmsg(server_conn, from_who, "statistics - returns the number of criticals/warnings/etc.");
										rc |= irc_privmsg(server_conn, from_who, "reload - completely forced reload the nagios status");
										rc |= irc_privmsg(server_conn, from_who, "check - check if nagios is still running");

										if (rc == -1)
											return -1;
									}
									else if (strcmp(msg, "resend") == 0)
									{
										dolog("resend requested by %s", from_who);

										if (resend_nagios_status(server_conn, from_who) == -1)
											return -1;
									}
									else if (strcmp(msg, "check") == 0)
									{
										char *message;
										int rc;

										dolog("nagios check requested by %s", from_who);

										message = check_nagios();
										if (message)
										{
											char buffer[4096];
											snprintf(buffer, sizeof(buffer), "Nagios has stopped running! -> %s", message);
											rc = irc_privmsg(server_conn, from_who, buffer);
											free(message);
										}
										else
											rc = irc_privmsg(server_conn, from_who, "Nagios is still running");

										if (rc == -1)
											return -1;
									}
									else if (strcmp(msg, "statistics") == 0)
									{
										char buffer[4096];

										dolog("statistics requested by %s", from_who);

										calc_statistics(prev, n_prev, 0, 0, 0, 1, buffer, sizeof(buffer));

										if (irc_privmsg(server_conn, from_who, buffer) == -1)
											return -1;
									}
									else if (strcmp(msg, "reload") == 0)
									{
										dolog("reload requested by %s", from_who);

										if (reload_statuslog() == -1)
										{
											if (irc_privmsg(server_conn, from_who, "cannot access status.log") == -1)
												return -1;
										}
										else
										{
											if (irc_privmsg(server_conn, from_who, "nagios status reloaded") == -1)
												return -1;
										}
									}
									else
									{
										char buffer[4096];

										dolog("giberish sent by %s", from_who);

										snprintf(buffer, sizeof(buffer), "'%s' is not understood - send 'help' for help", msg);
										if (irc_privmsg(server_conn, from_who, buffer) == -1)
											return -1;

										if (send_help(server_conn, from_who) == -1)
											return -1;
									}
								}
							}

						}
						else if (strncmp(cmd, "QUIT ", 5) == 0)
						{
							char *quit_nick = &response[1];
							char *exclamation_mark = strchr(quit_nick, '!');
							if (exclamation_mark) *exclamation_mark = 0x00;

							if (strcmp(nick, quit_nick) == 0)
							{
								dolog("Got QUITed (%s)", cmd);
								return -1;
							}
							else if (verbose > 1)
							{
								dolog("user %s quit", quit_nick);
							}
						}

					}
				}
			}
		}
	}

	dolog("NagIRCBot dropped of IRC server");

	return -1;
}

void sighandler(int pid)
{
	if (pid == SIGTERM)
	{
		if (pidfile)
			unlink(pidfile);

		exit(1);
	}
}

void version(void)
{
	printf("nagircbot, v" VERSION " (C) 2006-2011 by folkert@vanheusden.com\n");
}

void usage(void)
{
	version();

	printf("\n");

	printf("-f     path to status.log ('status_file' parameter in nagios.cfg)\n");
	printf("-F     host:port for retrieving status.log\n");
	printf("-x     status.log is in nagios 1.0 format\n");
	printf("-X     status.log is in nagios 2.0/3.0 format\n");
	printf("-s     IRC server to connect to (host:port)\n");
	printf("-c     channel to connect to (#channel - do not forget to escape the '#' in your shell)\n");
	printf("-k     keyword for the channel to connect to (default: no keyword)\n");
	printf("-C     use colors\n");
	printf("-n     nick\n");
	printf("-u     username (for logging into the irc server)\n");
	printf("-U     name (as seen by other users)\n");
	printf("-p     password (for logging into the irc server)\n");
	printf("-N     prefix for all in-channel messages, e.g. for nick highlight\n");
	printf("-m     display all information on separate lines\n");
	printf("-t     show a summary in the topic-line\n");
	printf("-i     check interval (in seconds - default 60)\n");
	printf("-I     how often to announce the global status in the channel (in seconds, 0 for off)\n");
	printf("       do not set it smaller then the -i value\n");
	printf("-d     do not fork into the background\n");
	printf("-T x   checks to see if nagios is still running. comma-seperated list\n");
	printf("       (without spaces!) with the following elements:\n");
	printf("       max_time_last_host_update, max_time_oldest_host_update,\n");
	printf("       max_time_last_host_check, max_time_oldest_host_check,\n");
	printf("       max_time_last_service_check, max_time_oldest_service_check,\n");
	printf("       max_time_oldest_next_service_check\n");
	printf("       send 'check' in a private message to invoke the check\n");
	printf("-z user	user to run as\n");
	printf("-H     show only state type 'HARD' (default)\n");
	printf("-S     show also state type 'SOFT'\n");
	printf("-R     only announce CRITICAL/UNKNOWN errors on the channel\n");
	printf("-A x   filter (omit) lines that match with the given regular expression\n");
	printf("-P x   write pid to file x\n");
	printf("-e     Use encryption (SSL) (default: no)\n");
}

void add_filter(char *string)
{
	filters = (regex_t *)realloc(filters, sizeof(regex_t) * (n_filters + 1));
	if (!filters)
		error_exit("add_filter: out of memory");

	if (regcomp(&filters[n_filters], string, REG_EXTENDED))
		error_exit("add_filter: failed to compile regexp '%s'", string);

	n_filters++;
}

int main(int argc, char *argv[])
{
	int state = S_DISCONNECTED;
	int fd = -1;
	int sleep_time = default_sleep;
	int c;
	int do_fork = 1;
	time_t time_join_channel_started = (time_t)0;
	time_t time_tcp_connected = (time_t)0;
	int join_tries = 0;
	char *runas = NULL;

	color_str[0] = mystrdup("_3,1 ");
	color_str[1] = mystrdup("_8,1 ");
	color_str[2] = mystrdup("_4,1 ");
	color_str[3] = mystrdup("_11,1 ");
	color_str[0][0] = color_str[1][0] = color_str[2][0] = color_str[3][0] = 3;

	while((c = getopt(argc, argv, "N:A:eRP:xXF:f:i:hHSs:c:k:Ctn:u:U:p:T:mvdVz:I:")) != -1)
	{
		switch(c)
		{
			case 'A':
				add_filter(optarg);
				break;

			case 'R':
				critical_only = 1;
				break;

			case 'e':
				use_ssl = 1;
				break;

			case 'P':
				pidfile = optarg;
				break;

			case 'I':
				announce_global_status_interval = atoi(optarg);
				break;

			case 'z':
				runas = optarg;
				break;

			case 'T':
				{
					char *dummy = optarg;

					max_time_last_host_update = atoi(dummy);
					dummy = strchr(dummy, ',') + 1;

					max_time_oldest_host_update = atoi(dummy);
					dummy = strchr(dummy, ',') + 1;

					max_time_last_host_check = atoi(dummy);
					dummy = strchr(dummy, ',') + 1;

					max_time_oldest_host_check = atoi(dummy);
					dummy = strchr(dummy, ',') + 1;

					max_time_last_service_check = atoi(dummy);
					dummy = strchr(dummy, ',') + 1;

					max_time_oldest_service_check = atoi(dummy);
					dummy = strchr(dummy, ',') + 1;

					max_time_oldest_next_service_check = atoi(dummy);
					break;
				}

			case 'H':
				hard_only = 1;
				break;

			case 'S':
				hard_only = 0;
				break;

			case 'd':
				do_fork = 0;
				break;

			case 't':
				topic_summary = 1;
				break;

			case 'C':
				use_colors = 1;
				break;

			case 'm':
				one_line = 0;
				break;

			case 'N':
				nick_prefix = mystrdup(optarg);
				break;

			case 'p':
				password = mystrdup(optarg);
				break;

			case 'U':
				username = mystrdup(optarg);
				break;

			case 'n':
				nick = mystrdup(optarg);
				break;

			case 'u':
				user = mystrdup(optarg);
				break;

			case 's':
				server = mystrdup(optarg);
				break;

			case 'c':
				channel = mystrdup(optarg);
				break;

			case 'k':
				keyword = mystrdup(optarg);
				break;

			case 'x':
				statuslog_version = 1;
				break;

			case 'X':
				statuslog_version = 2;
				break;

			case 'f':
				statuslog = optarg;
				statuslog_location = L_FILE;
				break;

			case 'F':
				statuslog = optarg;
				statuslog_location = L_HOST;
				break;

			case 'i':
				check_interval = atoi(optarg);
				break;

			case 'v':
				verbose = 1;
				break;

			case 'V':
				version();
				return 0;

			case 'h':
				usage();
				return 0;

			default:
				usage();
				return 1;
		}
	}

	if (do_fork)
	{
		if (daemon(0, 0) == -1)
		{
			error_exit("Failed to become daemon process!");
		}
	}

	if (pidfile)
		write_pidfile(pidfile);

	if (runas)
	{
		struct passwd *p = getpwnam(runas);
		if (p)
		{
			if (setgid(p -> pw_gid) == -1)
				error_exit("setgid(%d) failed", p -> pw_gid);

			if (setuid(p -> pw_uid) == -1)
				error_exit("setuid(%d) failed", p -> pw_uid);
		}
		else
		{
			error_exit("User '%s' not found.", runas);
		}
	}

	signal(SIGPIPE, SIG_IGN);
	signal(SIGTERM, sighandler);
	server_conn.addr = server;
	for(;;)
	{
		if (state == S_DISCONNECTED)
		{
			dolog("Connecting to %s", server);

			fd = connect_to(server);
			if (fd == -1)
			{
				if (verbose > 1)
					dolog("Cannot connect to %s: %m, will sleep %d seconds", server, sleep_time);

				sleep(sleep_time);
				if (sleep_time < max_sleep_time)
					sleep_time = (int)((double)sleep_time * 1.5);
				else
					sleep_time = max_sleep_time;
			}
			else
			{
				server_conn.fd = fd;
				if( use_ssl ) {
					dolog("Doing SSL handshake");
					if( !ssl_handshake( &server_conn ) ){
						dolog("SSL handshake failed!");
						return 1;
					}
				}
				state = S_CONNECTED;
				join_tries = 0;
				time_tcp_connected = time(NULL);
			}

			if (verbose == 1)
				dolog("Connected to IRC server %s", server);
		}

		if (state == S_CONNECTED)
		{

			dolog("Logging in...");

			if (irc_login(server_conn, user, username, server, password) == -1)
				state = S_DISCONNECTING;

			if (irc_join_channel(server_conn, channel, keyword) == -1)
				state = S_DISCONNECTING;

			state = S_JOINING_CHANNEL;

			time_join_channel_started = time(NULL);
		}

		if (state == S_JOINING_CHANNEL)
		{
			fd_set rfds;
			struct timeval tv;

			dolog("Joining channel...");

			FD_ZERO(&rfds);
			FD_SET(server_conn.fd, &rfds);

			tv.tv_sec = 1;
			tv.tv_usec = 0;

			if (select(server_conn.fd + 1, &rfds, NULL, NULL, &tv) == -1)
			{
				if (errno != EAGAIN && errno != EINTR)
					error_exit("select() failed");
			}

			if (FD_ISSET(server_conn.fd, &rfds))
			{
				char recv_buffer[4096];
				int rc = IRCREAD(server_conn, recv_buffer, sizeof(recv_buffer) - 1);

				if (rc == 0)
					state = S_DISCONNECTING;
				else if (rc == -1)
				{
					if (errno != EAGAIN && errno != EINTR)
					{
						dolog("failed joining channel: %s", strerror(errno));
						state = S_DISCONNECTING;
					}
				}
				else
				{
					char *cmd, *pnt = recv_buffer, *end_marker;

					recv_buffer[rc] = 0x00;

					if (check_ping(server_conn, recv_buffer) == -1)
						return -1;

					do
					{
						end_marker = strchr(pnt, '\n');
						if (end_marker) *end_marker = 0x00;
						if (!end_marker) end_marker = strchr(pnt, '\r');
						if (end_marker) *end_marker = 0x00;
#ifdef _DEBUG
						//						printf("[%s]", pnt);
#endif

						cmd = strchr(pnt, ' ');
						if (cmd)
						{
							while(*cmd == ' ') cmd++;

							if (strncmp(cmd, "JOIN ", 5) == 0)
							{
								if (verbose > 1)
									dolog("on channel");
								state = S_ON_CHANNEL;
							}
							else if (strncmp(cmd, "KICK ", 5) == 0)
							{
								char *dummy = strchr(cmd, ' ');
								if (dummy)
								{
									while(*dummy == ' ') dummy++;
									dummy = strchr(dummy, ' ');
								}
								if (dummy)
								{
									while(*dummy == ' ') dummy++;

									if (strncmp(dummy, nick, strlen(nick)) == 0)
										state = S_CONNECTED;
								}
							}
						}

						pnt = end_marker + 1;
					}
					while(end_marker);
				}
			}
		}

		if (state == S_JOINING_CHANNEL && (time(NULL) - time_join_channel_started) > join_timeout)
		{
			if (++join_tries == max_n_join_tries)
			{
				state = S_DISCONNECTING;
				dolog("joining the channel %s too to long (%ds, timeout set to %ds), aborting and retrying ", channel, time(NULL) - time_join_channel_started, join_timeout);
			}
			else
			{
				state = S_CONNECTED;
				dolog("failed joining channel %s, retrying (%d/%d)", channel, join_tries, max_n_join_tries);
			}
		}

		if (state == S_ON_CHANNEL)
		{
			dolog("On channel, starting nagtail...");
			sleep_time = default_sleep;

			(void)do_nagircbot(server_conn, channel);

			state = S_DISCONNECTING;
		}

		if (state == S_DISCONNECTING)
		{
			int took = time(NULL) - time_tcp_connected;

			dolog("Disconnected");

			close(fd);
			fd = -1;
			state = S_DISCONNECTED;

			dolog("Session took %d seconds", took);

			if (took < minimum_time_for_successfull_login)
			{
				dolog("Will sleep %d seconds before retrying", sleep_time);

				sleep(sleep_time);

				if (sleep_time < max_sleep_time)
					sleep_time = (int)((double)sleep_time * sleep_multiply_factor);
				else
					sleep_time = max_sleep_time;
			}
		}
	}

	return 0;
}