/
nsca.c
1657 lines (1322 loc) · 49.8 KB
/
nsca.c
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
/*******************************************************************************
*
* NSCA.C - Nagios Service Check Acceptor
* Copyright (c) 2009 Nagios Core Development Team and Community Contributors
* Copyright (c) 2000-2009 Ethan Galstad (egalstad@nagios.org)
* License: GPL v2
*
* Last Modified: 12-07-2016
*
* Command line: NSCA -c <config_file> [mode]
*
* Description:
*
* This program is designed to run as a daemon on the main Nagios machine
* and accept service check results from remote hosts.
*
******************************************************************************/
#include "../include/common.h"
#include "../include/config.h"
#include "../include/netutils.h"
#include "../include/utils.h"
#include "../include/nsca.h"
static int server_port=DEFAULT_SERVER_PORT;
static char server_address[16]="0.0.0.0";
static int socket_timeout=DEFAULT_SOCKET_TIMEOUT;
static int log_facility=LOG_DAEMON;
static char config_file[MAX_INPUT_BUFFER]="nsca.cfg";
static char alternate_dump_file[MAX_INPUT_BUFFER]="/dev/null";
static char command_file[MAX_INPUT_BUFFER]="";
static char password[MAX_INPUT_BUFFER]="";
static enum { OPTIONS_ERROR, SINGLE_PROCESS_DAEMON, MULTI_PROCESS_DAEMON, INETD } mode=SINGLE_PROCESS_DAEMON;
static int debug=FALSE;
static int aggregate_writes=FALSE;
static int decryption_method=ENCRYPT_XOR;
static int append_to_file=FALSE;
static unsigned long max_packet_age=30;
char *nsca_user=NULL;
char *nsca_group=NULL;
char *nsca_chroot=NULL;
char *check_result_path=NULL;
char *pid_file=NULL;
int wrote_pid_file=FALSE;
int show_help=FALSE;
int show_license=FALSE;
int show_version=FALSE;
int sigrestart=FALSE;
int sigshutdown=FALSE;
int using_alternate_dump_file=FALSE;
static FILE *command_file_fp=NULL;
struct handler_entry *rhand=NULL;
struct handler_entry *whand=NULL;
struct pollfd *pfds=NULL;
int maxrhand=0;
int maxwhand=0;
int maxpfds=0;
int nrhand=0;
int nwhand=0;
int npfds=0;
#ifdef HAVE_LIBWRAP
int allow_severity=LOG_INFO;
int deny_severity=LOG_WARNING;
#endif
int main(int argc, char **argv){
char buffer[MAX_INPUT_BUFFER];
int result;
uid_t uid=-1;
gid_t gid=-1;
#ifdef HAVE_SIGACTION
struct sigaction sig_action;
#endif
/* process command-line arguments */
result=process_arguments(argc,argv);
if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE){
if(result!=OK)
printf("Incorrect command line arguments supplied\n");
printf("\n");
printf("NSCA - Nagios Service Check Acceptor\n");
printf("Copyright (c) 2009 Nagios Core Development Team and Community Contributors\n");
printf("Copyright (c) 2000-2009 Ethan Galstad\n");
printf("Version: %s\n",PROGRAM_VERSION);
printf("Last Modified: %s\n",MODIFICATION_DATE);
printf("License: GPL v2\n");
printf("Encryption Routines: ");
#ifdef HAVE_LIBMCRYPT
printf("AVAILABLE");
#else
printf("NOT AVAILABLE");
#endif
printf("\n");
#ifdef HAVE_LIBWRAP
printf("TCP Wrappers Available\n");
#endif
printf("\n");
}
if(result!=OK || show_help==TRUE){
printf("Usage: %s -c <config_file> [mode]\n",argv[0]);
printf("\n");
printf("Options:\n");
printf(" <config_file> = Name of config file to use\n");
printf(" [mode] = Determines how NSCA should run. Valid modes:\n");
printf(" --inetd = Run as a service under inetd or xinetd\n");
printf(" --daemon = Run as a standalone multi-process daemon\n");
printf(" --single = Run as a standalone single-process daemon (default)\n");
printf("\n");
printf("Notes:\n");
printf("This program is designed to accept passive check results from\n");
printf("remote hosts that use the send_nsca utility. Can run as a service\n");
printf("under inetd or xinetd (read the docs for info on this), or as a\n");
printf("standalone daemon.\n");
printf("\n");
}
if(show_license==TRUE)
display_license();
if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE)
do_exit(STATE_UNKNOWN);
/* open a connection to the syslog facility */
/* facility may be overridden later */
get_log_facility(NSCA_LOG_FACILITY);
openlog("nsca",LOG_PID|LOG_NDELAY,log_facility);
/* make sure the config file uses an absolute path */
if(config_file[0]!='/'){
/* save the name of the config file */
strncpy(buffer,config_file,sizeof(buffer));
buffer[sizeof(buffer)-1]='\0';
/* get absolute path of current working directory */
strcpy(config_file,"");
getcwd(config_file,sizeof(config_file));
/* append a forward slash */
strncat(config_file,"/",sizeof(config_file)-2);
config_file[sizeof(config_file)-1]='\0';
/* append the config file to the path */
strncat(config_file,buffer,sizeof(config_file)-strlen(config_file)-1);
config_file[sizeof(config_file)-1]='\0';
}
/* read the config file */
result=read_config_file(config_file);
/* exit if there are errors... */
if(result==ERROR)
do_exit(STATE_CRITICAL);
/* generate the CRC 32 table */
generate_crc32_table();
/* how should we handle client connections? */
switch(mode){
case INETD:
/* chroot if configured */
do_chroot();
/* if we're running under inetd, handle one connection and get out */
handle_connection(0,NULL);
break;
case MULTI_PROCESS_DAEMON:
/* older style, mult-process daemon */
/* execution cascades below... */
install_child_handler();
/* |
|
| */
case SINGLE_PROCESS_DAEMON:
/* |
|
V */
/* daemonize and start listening for requests... */
if(fork()==0){
/* we're a daemon - set up a new process group */
setsid();
/* handle signals */
#ifdef HAVE_SIGACTION
sig_action.sa_sigaction = NULL;
sig_action.sa_handler = sighandler;
sigfillset(&sig_action.sa_mask);
sig_action.sa_flags = SA_NODEFER|SA_RESTART;
sigaction(SIGQUIT, &sig_action, NULL);
sigaction(SIGTERM, &sig_action, NULL);
sigaction(SIGHUP, &sig_action, NULL);
#else /* HAVE_SIGACTION */
signal(SIGQUIT,sighandler);
signal(SIGTERM,sighandler);
signal(SIGHUP,sighandler);
#endif /* HAVE_SIGACTION */
/* close standard file descriptors */
close(0);
close(1);
close(2);
/* redirect standard descriptors to /dev/null */
open("/dev/null",O_RDONLY);
open("/dev/null",O_WRONLY);
open("/dev/null",O_WRONLY);
/* get group information before chrooting */
get_user_info(nsca_user,&uid);
get_group_info(nsca_group,&gid);
/* write pid file */
if(write_pid_file(uid,gid)==ERROR)
return STATE_CRITICAL;
/* chroot if configured */
do_chroot();
/* drop privileges */
if(drop_privileges(nsca_user,uid,gid)==ERROR)
do_exit(STATE_CRITICAL);
do{
/* reset flags */
sigrestart=FALSE;
sigshutdown=FALSE;
/* wait for connections */
wait_for_connections();
if(sigrestart==TRUE){
/* free memory */
free_memory();
/* re-read the config file */
result=read_config_file(config_file);
/* exit if there are errors... */
if(result==ERROR){
syslog(LOG_ERR,"Config file '%s' contained errors, bailing out...",config_file);
break;
}
}
}while(sigrestart==TRUE && sigshutdown==FALSE);
/* remove pid file */
remove_pid_file();
syslog(LOG_NOTICE,"Daemon shutdown\n");
}
break;
default:
break;
}
/* we are now running in daemon mode, or the connection handed over by inetd has been completed, so the parent process exits */
do_exit(STATE_OK);
/* keep the compilers happy... */
return STATE_OK;
}
/* cleanup */
static void do_cleanup(void){
/* free memory */
free_memory();
/* close the command file if its still open */
if(command_file_fp!=NULL)
close_command_file();
/*** CLEAR SENSITIVE INFO FROM MEMORY ***/
/* overwrite password */
clear_buffer(password,sizeof(password));
/* disguise decryption method */
decryption_method=-1;
return;
}
/* free some memory */
static void free_memory(void){
if(nsca_user){
free(nsca_user);
nsca_user=NULL;
}
if(nsca_group){
free(nsca_group);
nsca_group=NULL;
}
if(nsca_chroot){
free(nsca_chroot);
nsca_chroot=NULL;
}
if(pid_file){
free(pid_file);
pid_file=NULL;
}
return;
}
/* exit cleanly */
static void do_exit(int return_code){
do_cleanup();
exit(return_code);
}
/* read in the configuration file */
static int read_config_file(char *filename){
FILE *fp;
char input_buffer[MAX_INPUT_BUFFER];
char *varname;
char *varvalue;
int line;
/* open the config file for reading */
fp=fopen(filename,"r");
/* exit if we couldn't open the config file */
if(fp==NULL){
syslog(LOG_ERR,"Could not open config file '%s' for reading\n",filename);
return ERROR;
}
line=0;
while(fgets(input_buffer,MAX_INPUT_BUFFER-1,fp)){
line++;
/* skip comments and blank lines */
if(input_buffer[0]=='#')
continue;
if(input_buffer[0]=='\0')
continue;
if(input_buffer[0]=='\n')
continue;
/* get the variable name */
varname=strtok(input_buffer,"=");
if(varname==NULL){
syslog(LOG_ERR,"No variable name specified in config file '%s' - Line %d\n",filename,line);
return ERROR;
}
/* get the variable value */
varvalue=strtok(NULL,"\n");
if(varvalue==NULL){
syslog(LOG_ERR,"No variable value specified in config file '%s' - Line %d\n",filename,line);
return ERROR;
}
if(!strcmp(varname,"server_port")){
server_port=atoi(varvalue);
if((server_port<1024 && (geteuid()!=0)) || server_port<0){
syslog(LOG_ERR,"Invalid port number specified in config file '%s' - Line %d\n",filename,line);
return ERROR;
}
}
else if(!strcmp(varname,"server_address")){
strncpy(server_address,varvalue,sizeof(server_address) - 1);
server_address[sizeof(server_address)-1]='\0';
}
else if(strstr(input_buffer,"command_file")){
if(strlen(varvalue)>sizeof(command_file)-1){
syslog(LOG_ERR,"Command file name is too long in config file '%s' - Line %d\n",filename,line);
return ERROR;
}
strncpy(command_file,varvalue,sizeof(command_file)-1);
command_file[sizeof(command_file)-1]='\0';
}
else if(strstr(input_buffer,"alternate_dump_file")){
if(strlen(varvalue)>sizeof(alternate_dump_file)-1){
syslog(LOG_ERR,"Alternate dump file name is too long in config file '%s' - Line %d\n",filename,line);
return ERROR;
}
strncpy(alternate_dump_file,varvalue,sizeof(alternate_dump_file)-1);
alternate_dump_file[sizeof(alternate_dump_file)-1]='\0';
}
else if(strstr(input_buffer,"password")){
if(strlen(varvalue)>sizeof(password)-1){
syslog(LOG_ERR,"Password is too long in config file '%s' - Line %d\n",filename,line);
return ERROR;
}
strncpy(password,varvalue,sizeof(password)-1);
password[sizeof(password)-1]='\0';
}
else if(strstr(input_buffer,"decryption_method")){
decryption_method=atoi(varvalue);
switch(decryption_method){
case ENCRYPT_NONE:
case ENCRYPT_XOR:
break;
#ifdef HAVE_LIBMCRYPT
case ENCRYPT_DES:
case ENCRYPT_3DES:
case ENCRYPT_CAST128:
case ENCRYPT_CAST256:
case ENCRYPT_XTEA:
case ENCRYPT_3WAY:
case ENCRYPT_BLOWFISH:
case ENCRYPT_TWOFISH:
case ENCRYPT_LOKI97:
case ENCRYPT_RC2:
case ENCRYPT_ARCFOUR:
case ENCRYPT_RIJNDAEL128:
case ENCRYPT_RIJNDAEL192:
case ENCRYPT_RIJNDAEL256:
case ENCRYPT_WAKE:
case ENCRYPT_SERPENT:
case ENCRYPT_ENIGMA:
case ENCRYPT_GOST:
case ENCRYPT_SAFER64:
case ENCRYPT_SAFER128:
case ENCRYPT_SAFERPLUS:
break;
#endif
default:
syslog(LOG_ERR,"Invalid decryption method (%d) in config file '%s' - Line %d\n",decryption_method,filename,line);
#ifndef HAVE_LIBMCRYPT
if(decryption_method>=2)
syslog(LOG_ERR,"Daemon was not compiled with mcrypt library, so decryption is unavailable.\n");
#endif
return ERROR;
}
}
else if(strstr(input_buffer,"debug")){
if(atoi(varvalue)>0)
debug=TRUE;
else
debug=FALSE;
}
else if(strstr(input_buffer,"aggregate_writes")){
if(atoi(varvalue)>0)
aggregate_writes=TRUE;
else
aggregate_writes=FALSE;
}
else if(strstr(input_buffer,"check_result_path")){
if(strlen(varvalue)>MAX_INPUT_BUFFER-1){
syslog(LOG_ERR,"Check result path is too long in config file '%s' - Line %d\n",filename,line);
return ERROR;
}
check_result_path=strdup(varvalue);
int checkresult_test_fd=-1;
char *checkresult_test=NULL;
asprintf(&checkresult_test,"%s/nsca.test.%i",check_result_path,getpid());
checkresult_test_fd=open(checkresult_test,O_WRONLY|O_CREAT,S_IWUSR);
if (checkresult_test_fd>0){
unlink(checkresult_test);
}
else {
printf("error!\n");
syslog(LOG_ERR,"check_result_path config variable found, but directory not writeable.\n");
return ERROR;
}
}
else if(strstr(input_buffer,"append_to_file")){
if(atoi(varvalue)>0)
append_to_file=TRUE;
else
append_to_file=FALSE;
}
else if(!strcmp(varname,"max_packet_age")){
max_packet_age=strtoul(varvalue,NULL,10);
if(max_packet_age>900){
syslog(LOG_ERR,"Max packet age cannot be greater than 15 minutes (900 seconds).\n");
return ERROR;
}
}
else if(!strcmp(varname,"nsca_user"))
nsca_user=strdup(varvalue);
else if(!strcmp(varname,"nsca_group"))
nsca_group=strdup(varvalue);
else if(!strcmp(varname,"nsca_chroot"))
nsca_chroot=strdup(varvalue);
else if(!strcmp(varname,"pid_file"))
pid_file=strdup(varvalue);
else if(!strcmp(varname,"log_facility")){
if((get_log_facility(varvalue))==OK){
/* re-open log using new facility */
closelog();
openlog("nsca",LOG_PID|LOG_NDELAY,log_facility);
}
else
syslog(LOG_WARNING,"Invalid log_facility specified in config file '%s' - Line %d\n",filename,line);
}
else{
syslog(LOG_ERR,"Unknown option specified in config file '%s' - Line %d\n",filename,line);
return ERROR;
}
}
/* close the config file */
fclose(fp);
return OK;
}
/* determines facility to use with syslog */
int get_log_facility(char *varvalue){
if(!strcmp(varvalue,"kern"))
log_facility=LOG_KERN;
else if(!strcmp(varvalue,"user"))
log_facility=LOG_USER;
else if(!strcmp(varvalue,"mail"))
log_facility=LOG_MAIL;
else if(!strcmp(varvalue,"daemon"))
log_facility=LOG_DAEMON;
else if(!strcmp(varvalue,"auth"))
log_facility=LOG_AUTH;
else if(!strcmp(varvalue,"syslog"))
log_facility=LOG_SYSLOG;
else if(!strcmp(varvalue,"lrp"))
log_facility=LOG_LPR;
else if(!strcmp(varvalue,"news"))
log_facility=LOG_NEWS;
else if(!strcmp(varvalue,"uucp"))
log_facility=LOG_UUCP;
else if(!strcmp(varvalue,"cron"))
log_facility=LOG_CRON;
else if(!strcmp(varvalue,"authpriv"))
log_facility=LOG_AUTHPRIV;
else if(!strcmp(varvalue,"ftp"))
log_facility=LOG_FTP;
else if(!strcmp(varvalue,"local0"))
log_facility=LOG_LOCAL0;
else if(!strcmp(varvalue,"local1"))
log_facility=LOG_LOCAL1;
else if(!strcmp(varvalue,"local2"))
log_facility=LOG_LOCAL2;
else if(!strcmp(varvalue,"local3"))
log_facility=LOG_LOCAL3;
else if(!strcmp(varvalue,"local4"))
log_facility=LOG_LOCAL4;
else if(!strcmp(varvalue,"local5"))
log_facility=LOG_LOCAL5;
else if(!strcmp(varvalue,"local6"))
log_facility=LOG_LOCAL6;
else if(!strcmp(varvalue,"local7"))
log_facility=LOG_LOCAL7;
else{
log_facility=LOG_DAEMON;
return ERROR;
}
return OK;
}
/* get rid of all the children we can... */
static void reap_children(int sig){
while(waitpid(-1,NULL,WNOHANG)>0);
return;
}
/* install reap_children() signal handler */
static void install_child_handler(void){
struct sigaction sa;
sa.sa_handler=reap_children;
sa.sa_flags=SA_NOCLDSTOP;
sigaction(SIGCHLD,&sa,NULL);
return;
}
/* register a file descriptor to be polled for an event set */
static void register_poll(short events, int fd){
int i;
/* if it's already in the list, just flag the events */
for(i=0;i<npfds;i++){
if(pfds[i].fd==fd){
pfds[i].events|=events;
return;
}
}
/* else add it to the list */
if(maxpfds==0){
maxpfds++;
pfds=malloc(sizeof(struct pollfd));
}
else if(npfds+1 > maxpfds){
maxpfds++;
pfds=realloc(pfds, sizeof(struct pollfd) * maxpfds);
}
pfds[npfds].fd=fd;
pfds[npfds].events=events;
pfds[npfds].revents=0;
npfds++;
}
/* register a read handler */
static void register_read_handler(int fd, void (*fp)(int, void *), void *data){
int i;
/* register our interest in this descriptor */
register_poll(POLLIN,fd);
/* if it's already in the list, just update the handler */
for(i=0;i<nrhand;i++){
if(rhand[i].fd==fd){
rhand[i].handler=fp;
rhand[i].data=data;
return;
}
}
/* else add it to the list */
if(maxrhand==0){
maxrhand++;
rhand=malloc(sizeof(struct handler_entry));
}
else if(nrhand+1 > maxrhand){
maxrhand++;
rhand=realloc(rhand, sizeof(struct handler_entry) * maxrhand);
}
rhand[nrhand].fd=fd;
rhand[nrhand].handler=fp;
rhand[nrhand].data=data;
nrhand++;
}
/* register a write handler */
static void register_write_handler(int fd, void (*fp)(int, void *), void *data){
int i;
/* register our interest in this descriptor */
register_poll(POLLOUT,fd);
/* if it's already in the list, just update the handler */
for(i=0;i<nwhand;i++){
if(whand[i].fd==fd){
whand[i].handler=fp;
whand[i].data=data;
return;
}
}
/* else add it to the list */
if(maxwhand==0){
maxwhand++;
whand=malloc(sizeof(struct handler_entry));
}
else if(nwhand+1 > maxwhand){
maxwhand++;
whand=realloc(whand, sizeof(struct handler_entry) * maxwhand);
}
whand[nwhand].fd=fd;
whand[nwhand].handler=fp;
whand[nwhand].data=data;
nwhand++;
}
/* find read handler */
static int find_rhand(int fd){
int i;
for(i=0;i<nrhand;i++){
if(rhand[i].fd==fd)
return i;
}
/* we couldn't find the read handler */
syslog(LOG_ERR, "Handler stack corrupt - aborting");
do_exit(STATE_CRITICAL);
}
/* find write handler */
static int find_whand(int fd){
int i;
for(i=0;i<nwhand;i++){
if(whand[i].fd==fd)
return i;
}
/* we couldn't find the write handler */
syslog(LOG_ERR, "Handler stack corrupt - aborting");
do_exit(STATE_CRITICAL);
}
/* handle pending events */
static void handle_events(void){
void (*handler)(int, void *);
void *data;
int i, hand;
/* bail out if necessary */
if(sigrestart==TRUE || sigshutdown==TRUE)
return;
poll(pfds,npfds,-1);
for(i=0;i<npfds;i++){
if((pfds[i].events&POLLIN) && (pfds[i].revents&(POLLIN|POLLERR|POLLHUP|POLLNVAL))){
pfds[i].events&=~POLLIN;
hand=find_rhand(pfds[i].fd);
handler=rhand[hand].handler;
data=rhand[hand].data;
rhand[hand].handler=NULL;
rhand[hand].data=NULL;
if((pfds[i].revents&POLLNVAL)==0)
handler(pfds[i].fd,data);
}
if((pfds[i].events&POLLOUT) && (pfds[i].revents&(POLLOUT|POLLERR|POLLHUP|POLLNVAL))){
pfds[i].events&=~POLLOUT;
hand=find_whand(pfds[i].fd);
handler=whand[hand].handler;
data=whand[hand].data;
whand[hand].handler=NULL;
whand[hand].data=NULL;
if((pfds[i].revents&POLLNVAL)==0)
handler(pfds[i].fd,data);
}
}
for(i=0;i<npfds;i++){
if(pfds[i].events==0){
npfds--;
pfds[i].fd=pfds[npfds].fd;
pfds[i].events=pfds[npfds].events;
}
}
return;
}
/* wait for incoming connection requests */
static void wait_for_connections(void) {
struct sockaddr_in myname;
int sock=0;
int flag=1;
/* create a socket for listening */
sock=socket(AF_INET,SOCK_STREAM,0);
/* exit if we couldn't create the socket */
if(sock<0){
syslog(LOG_ERR,"Network server socket failure (%d: %s)",errno,strerror(errno));
do_exit(STATE_CRITICAL);
}
/* set the reuse address flag so we don't get errors when restarting */
flag=1;
if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char *)&flag,sizeof(flag))<0){
syslog(LOG_ERR,"Could not set reuse address option on socket!\n");
do_exit(STATE_CRITICAL);
}
myname.sin_family=AF_INET;
myname.sin_port=htons(server_port);
bzero(&myname.sin_zero,8);
/* what address should we bind to? */
if(!strlen(server_address))
myname.sin_addr.s_addr=INADDR_ANY;
else if(!my_inet_aton(server_address,&myname.sin_addr)){
syslog(LOG_ERR,"Server address is not a valid IP address\n");
do_exit(STATE_CRITICAL);
}
/* bind the address to the Internet socket */
if(bind(sock,(struct sockaddr *)&myname,sizeof(myname))<0){
syslog(LOG_ERR,"Network server bind failure (%d: %s)\n",errno,strerror(errno));
do_exit(STATE_CRITICAL);
}
/* open the socket for listening */
if(listen(sock,SOMAXCONN)<0){
syslog(LOG_ERR,"Network server listen failure (%d: %s)\n",errno,strerror(errno));
do_exit(STATE_CRITICAL);
}
/* log info to syslog facility */
syslog(LOG_NOTICE,"Starting up daemon");
if(debug==TRUE){
syslog(LOG_DEBUG,"Listening for connections on port %d\n",htons(myname.sin_port));
}
/* socket should be non-blocking for mult-process daemon */
if(mode==MULTI_PROCESS_DAEMON)
fcntl(sock,F_SETFL,O_NONBLOCK);
/* listen for connection requests */
if(mode==SINGLE_PROCESS_DAEMON)
register_read_handler(sock,accept_connection,NULL);
while(1){
/* bail out if necessary */
if(sigrestart==TRUE || sigshutdown==TRUE){
/* close the socket we're listening on */
close(sock);
break;
}
/* accept a new connection */
if(mode==MULTI_PROCESS_DAEMON)
accept_connection(sock,NULL);
/* handle the new connection (if any) */
else
handle_events();
}
return;
}
static void accept_connection(int sock, void *unused){
int new_sd;
pid_t pid;
struct sockaddr addr;
struct sockaddr_in *nptr;
socklen_t addrlen;
int rc;
#ifdef HAVE_LIBWRAP
struct request_info req;
#endif
/* DO NOT REMOVE! 01/29/2007 single process daemon will fail if this is removed */
if(mode==SINGLE_PROCESS_DAEMON)
register_read_handler(sock,accept_connection,NULL);
/* wait for a connection request */
while(1){
/* we got a live one... */
if((new_sd=accept(sock,0,0))>=0)
break;
/* handle the error */
else{
/* bail out if necessary */
if(sigrestart==TRUE || sigshutdown==TRUE)
return;
/* try and handle temporary errors */
if(errno==EWOULDBLOCK || errno==EINTR || errno==ECHILD){
if(mode==MULTI_PROCESS_DAEMON)
sleep(1);
else
return;
}
else
break;
}
}
/* hey, there was an error... */
if(new_sd<0){
/* log error to syslog facility */
syslog(LOG_ERR,"Network server accept failure (%d: %s)",errno,strerror(errno));
/* close socket prior to exiting */
close(sock);
if(mode==MULTI_PROCESS_DAEMON)
do_exit(STATE_CRITICAL);
return;
}
#ifdef HAVE_LIBWRAP
/* Check whether or not connections are allowed from this host */
request_init(&req,RQ_DAEMON,"nsca",RQ_FILE,new_sd,0);
fromhost(&req);
if(!hosts_access(&req)){
/* refuse the connection */
syslog(LOG_ERR, "refused connect from %s", eval_client(&req));
close(new_sd);
return;
}
#endif
/* fork() if we have to... */
if(mode==MULTI_PROCESS_DAEMON){
pid=fork();
if(pid){
/* parent doesn't need the new connection */
close(new_sd);
return;
}
else{
/* child does not need to listen for connections */
close(sock);
}
}
/* find out who just connected... */
addrlen=sizeof(addr);
rc=getpeername(new_sd,&addr,&addrlen);
if(rc<0){
/* log error to syslog facility */
syslog(LOG_ERR,"Error: Network server getpeername() failure (%d: %s)",errno,strerror(errno));
/* close socket prior to exiting */
close(new_sd);
if(mode==MULTI_PROCESS_DAEMON)
do_exit(STATE_CRITICAL);
return;
}
nptr=(struct sockaddr_in *)&addr;
/* log info to syslog facility */
if(debug==TRUE)
syslog(LOG_DEBUG,"Connection from %s port %d",inet_ntoa(nptr->sin_addr),nptr->sin_port);
/* handle the connection */
if(mode==SINGLE_PROCESS_DAEMON)
/* mark the connection as ready to be handled */
register_write_handler(new_sd, handle_connection, NULL);
else
/* handle the client connection */