Optimised pst3 for systems with large number of processes (Duncan Ferguson)
[monitoring-plugins.git] / plugins-root / check_dhcp.c
blob241f13ed90f9daa6c2d7dd897dae9b8e5c0c7a5c
1 /*****************************************************************************
2 *
3 * Nagios check_dhcp plugin
4 *
5 * License: GPL
6 * Copyright (c) 2001-2004 Ethan Galstad (nagios@nagios.org)
7 * Copyright (c) 2001-2007 Nagios Plugin Development Team
8 *
9 * Last Modified: $Date$
11 * Description:
13 * This file contains the check_dhcp plugin
15 * This plugin tests the availability of DHCP servers on a network.
17 * Unicast mode was originally implemented by Heiti of Boras Kommun with
18 * general improvements as well as usability fixes and "forward"-porting by
19 * Andreas Ericsson of OP5 AB.
22 * This program is free software: you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation, either version 3 of the License, or
25 * (at your option) any later version.
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
32 * You should have received a copy of the GNU General Public License
33 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 * $Id$
37 *****************************************************************************/
39 const char *progname = "check_dhcp";
40 const char *revision = "$Revision$";
41 const char *copyright = "2001-2007";
42 const char *email = "nagiosplug-devel@lists.sourceforge.net";
44 #include "common.h"
45 #include "netutils.h"
46 #include "utils.h"
48 #include <ctype.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <errno.h>
53 #include <unistd.h>
54 #include <sys/time.h>
55 #include <sys/ioctl.h>
56 #include <fcntl.h>
57 #include <getopt.h>
58 #include <sys/socket.h>
59 #include <sys/types.h>
60 #include <netdb.h>
61 #include <netinet/in.h>
62 #include <net/if.h>
63 #include <arpa/inet.h>
64 #if HAVE_SYS_SOCKIO_H
65 #include <sys/sockio.h>
66 #endif
68 #if defined( __linux__ )
70 #include <linux/if_ether.h>
71 #include <features.h>
73 #elif defined (__bsd__)
75 #include <netinet/if_ether.h>
76 #include <sys/param.h>
77 #include <sys/sysctl.h>
78 #include <net/if_dl.h>
80 #elif defined(__sun__) || defined(__solaris__) || defined(__hpux__)
82 #define INSAP 22
83 #define OUTSAP 24
85 #include <signal.h>
86 #include <ctype.h>
87 #include <sys/stropts.h>
88 #include <sys/poll.h>
89 #include <sys/dlpi.h>
91 #define bcopy(source, destination, length) memcpy(destination, source, length)
93 #define AREA_SZ 5000 /* buffer length in bytes */
94 static u_long ctl_area[AREA_SZ];
95 static u_long dat_area[AREA_SZ];
96 static struct strbuf ctl = {AREA_SZ, 0, (char *)ctl_area};
97 static struct strbuf dat = {AREA_SZ, 0, (char *)dat_area};
99 #define GOT_CTRL 1
100 #define GOT_DATA 2
101 #define GOT_BOTH 3
102 #define GOT_INTR 4
103 #define GOT_ERR 128
105 #define u_int8_t uint8_t
106 #define u_int16_t uint16_t
107 #define u_int32_t uint32_t
109 static int get_msg(int);
110 static int check_ctrl(int);
111 static int put_ctrl(int, int, int);
112 static int put_both(int, int, int, int);
113 static int dl_open(const char *, int, int *);
114 static int dl_bind(int, int, u_char *);
115 long mac_addr_dlpi( const char *, int, u_char *);
117 #endif
121 /**** Common definitions ****/
123 #define OK 0
124 #define ERROR -1
126 #define FALSE 0
127 #define TRUE 1
130 /**** DHCP definitions ****/
132 #define MAX_DHCP_CHADDR_LENGTH 16
133 #define MAX_DHCP_SNAME_LENGTH 64
134 #define MAX_DHCP_FILE_LENGTH 128
135 #define MAX_DHCP_OPTIONS_LENGTH 312
138 typedef struct dhcp_packet_struct{
139 u_int8_t op; /* packet type */
140 u_int8_t htype; /* type of hardware address for this machine (Ethernet, etc) */
141 u_int8_t hlen; /* length of hardware address (of this machine) */
142 u_int8_t hops; /* hops */
143 u_int32_t xid; /* random transaction id number - chosen by this machine */
144 u_int16_t secs; /* seconds used in timing */
145 u_int16_t flags; /* flags */
146 struct in_addr ciaddr; /* IP address of this machine (if we already have one) */
147 struct in_addr yiaddr; /* IP address of this machine (offered by the DHCP server) */
148 struct in_addr siaddr; /* IP address of DHCP server */
149 struct in_addr giaddr; /* IP address of DHCP relay */
150 unsigned char chaddr [MAX_DHCP_CHADDR_LENGTH]; /* hardware address of this machine */
151 char sname [MAX_DHCP_SNAME_LENGTH]; /* name of DHCP server */
152 char file [MAX_DHCP_FILE_LENGTH]; /* boot file name (used for diskless booting?) */
153 char options[MAX_DHCP_OPTIONS_LENGTH]; /* options */
154 }dhcp_packet;
157 typedef struct dhcp_offer_struct{
158 struct in_addr server_address; /* address of DHCP server that sent this offer */
159 struct in_addr offered_address; /* the IP address that was offered to us */
160 u_int32_t lease_time; /* lease time in seconds */
161 u_int32_t renewal_time; /* renewal time in seconds */
162 u_int32_t rebinding_time; /* rebinding time in seconds */
163 struct dhcp_offer_struct *next;
164 }dhcp_offer;
167 typedef struct requested_server_struct{
168 struct in_addr server_address;
169 int answered;
170 struct requested_server_struct *next;
171 }requested_server;
174 #define BOOTREQUEST 1
175 #define BOOTREPLY 2
177 #define DHCPDISCOVER 1
178 #define DHCPOFFER 2
179 #define DHCPREQUEST 3
180 #define DHCPDECLINE 4
181 #define DHCPACK 5
182 #define DHCPNACK 6
183 #define DHCPRELEASE 7
185 #define DHCP_OPTION_MESSAGE_TYPE 53
186 #define DHCP_OPTION_HOST_NAME 12
187 #define DHCP_OPTION_BROADCAST_ADDRESS 28
188 #define DHCP_OPTION_REQUESTED_ADDRESS 50
189 #define DHCP_OPTION_LEASE_TIME 51
190 #define DHCP_OPTION_SERVER_IDENTIFIER 54
191 #define DHCP_OPTION_RENEWAL_TIME 58
192 #define DHCP_OPTION_REBINDING_TIME 59
193 #define DHCP_OPTION_END 255
195 #define DHCP_INFINITE_TIME 0xFFFFFFFF
197 #define DHCP_BROADCAST_FLAG 32768
198 #define DHCP_UNICAST_FLAG 0
200 #define DHCP_SERVER_PORT 67
201 #define DHCP_CLIENT_PORT 68
203 #define ETHERNET_HARDWARE_ADDRESS 1 /* used in htype field of dhcp packet */
204 #define ETHERNET_HARDWARE_ADDRESS_LENGTH 6 /* length of Ethernet hardware addresses */
206 u_int8_t unicast = 0; /* unicast mode: mimic a DHCP relay */
207 struct in_addr my_ip; /* our address (required for relay) */
208 struct in_addr dhcp_ip; /* server to query (if in unicast mode) */
209 unsigned char client_hardware_address[MAX_DHCP_CHADDR_LENGTH]="";
210 unsigned char *user_specified_mac=NULL;
212 char network_interface_name[IFNAMSIZ]="eth0";
214 u_int32_t packet_xid=0;
216 u_int32_t dhcp_lease_time=0;
217 u_int32_t dhcp_renewal_time=0;
218 u_int32_t dhcp_rebinding_time=0;
220 int dhcpoffer_timeout=2;
222 dhcp_offer *dhcp_offer_list=NULL;
223 requested_server *requested_server_list=NULL;
225 int valid_responses=0; /* number of valid DHCPOFFERs we received */
226 int requested_servers=0;
227 int requested_responses=0;
229 int request_specific_address=FALSE;
230 int received_requested_address=FALSE;
231 int verbose=0;
232 struct in_addr requested_address;
235 int process_arguments(int, char **);
236 int call_getopt(int, char **);
237 int validate_arguments(void);
238 void print_usage(void);
239 void print_help(void);
241 void resolve_host(const char *in,struct in_addr *out);
242 unsigned char *mac_aton(const char *);
243 void print_hardware_address(const unsigned char *);
244 int get_hardware_address(int,char *);
245 int get_ip_address(int,char *);
247 int send_dhcp_discover(int);
248 int get_dhcp_offer(int);
250 int get_results(void);
252 int add_dhcp_offer(struct in_addr,dhcp_packet *);
253 int free_dhcp_offer_list(void);
254 int free_requested_server_list(void);
256 int create_dhcp_socket(void);
257 int close_dhcp_socket(int);
258 int send_dhcp_packet(void *,int,int,struct sockaddr_in *);
259 int receive_dhcp_packet(void *,int,int,int,struct sockaddr_in *);
263 int main(int argc, char **argv){
264 int dhcp_socket;
265 int result = STATE_UNKNOWN;
267 setlocale (LC_ALL, "");
268 bindtextdomain (PACKAGE, LOCALEDIR);
269 textdomain (PACKAGE);
271 /* Parse extra opts if any */
272 argv=np_extra_opts(&argc, argv, progname);
274 if(process_arguments(argc,argv)!=OK){
275 usage4 (_("Could not parse arguments"));
278 /* this plugin almost certainly needs root permissions. */
279 np_warn_if_not_root();
281 /* create socket for DHCP communications */
282 dhcp_socket=create_dhcp_socket();
284 /* get hardware address of client machine */
285 if(user_specified_mac!=NULL)
286 memcpy(client_hardware_address,user_specified_mac,6);
287 else
288 get_hardware_address(dhcp_socket,network_interface_name);
290 if(unicast) /* get IP address of client machine */
291 get_ip_address(dhcp_socket,network_interface_name);
293 /* send DHCPDISCOVER packet */
294 send_dhcp_discover(dhcp_socket);
296 /* wait for a DHCPOFFER packet */
297 get_dhcp_offer(dhcp_socket);
299 /* close socket we created */
300 close_dhcp_socket(dhcp_socket);
302 /* determine state/plugin output to return */
303 result=get_results();
305 /* free allocated memory */
306 free_dhcp_offer_list();
307 free_requested_server_list();
309 return result;
314 /* determines hardware address on client machine */
315 int get_hardware_address(int sock,char *interface_name){
317 #if defined(__linux__)
318 struct ifreq ifr;
320 strncpy((char *)&ifr.ifr_name,interface_name,sizeof(ifr.ifr_name)-1);
321 ifr.ifr_name[sizeof(ifr.ifr_name)-1]='\0';
323 /* try and grab hardware address of requested interface */
324 if(ioctl(sock,SIOCGIFHWADDR,&ifr)<0){
325 printf(_("Error: Could not get hardware address of interface '%s'\n"),interface_name);
326 exit(STATE_UNKNOWN);
329 memcpy(&client_hardware_address[0],&ifr.ifr_hwaddr.sa_data,6);
331 #elif defined(__bsd__)
332 /* King 2004 see ACKNOWLEDGEMENTS */
334 int mib[6], len;
335 char *buf;
336 unsigned char *ptr;
337 struct if_msghdr *ifm;
338 struct sockaddr_dl *sdl;
340 mib[0] = CTL_NET;
341 mib[1] = AF_ROUTE;
342 mib[2] = 0;
343 mib[3] = AF_LINK;
344 mib[4] = NET_RT_IFLIST;
346 if((mib[5] = if_nametoindex(interface_name)) == 0){
347 printf(_("Error: if_nametoindex error - %s.\n"), strerror(errno));
348 exit(STATE_UNKNOWN);
351 if(sysctl(mib, 6, NULL, &len, NULL, 0) < 0){
352 printf(_("Error: Couldn't get hardware address from %s. sysctl 1 error - %s.\n"), interface_name, strerror(errno));
353 exit(STATE_UNKNOWN);
356 if((buf = malloc(len)) == NULL){
357 printf(_("Error: Couldn't get hardware address from interface %s. malloc error - %s.\n"), interface_name, strerror(errno));
358 exit(4);
361 if(sysctl(mib, 6, buf, &len, NULL, 0) < 0){
362 printf(_("Error: Couldn't get hardware address from %s. sysctl 2 error - %s.\n"), interface_name, strerror(errno));
363 exit(STATE_UNKNOWN);
366 ifm = (struct if_msghdr *)buf;
367 sdl = (struct sockaddr_dl *)(ifm + 1);
368 ptr = (unsigned char *)LLADDR(sdl);
369 memcpy(&client_hardware_address[0], ptr, 6) ;
370 /* King 2004 */
372 #elif defined(__sun__) || defined(__solaris__)
374 /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */
375 long stat;
376 char dev[20] = "/dev/";
377 char *p;
378 int unit;
380 for(p = interface_name; *p && isalpha(*p); p++)
381 /* no-op */ ;
382 if( p != '\0' ){
383 unit = atoi(p) ;
384 *p = '\0' ;
385 strncat(dev, interface_name, 6) ;
387 else{
388 printf(_("Error: can't find unit number in interface_name (%s) - expecting TypeNumber eg lnc0.\n"), interface_name);
389 exit(STATE_UNKNOWN);
391 stat = mac_addr_dlpi(dev, unit, client_hardware_address);
392 if(stat != 0){
393 printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit);
394 exit(STATE_UNKNOWN);
397 #elif defined(__hpux__)
399 long stat;
400 char dev[20] = "/dev/dlpi" ;
401 int unit = 0;
403 stat = mac_addr_dlpi(dev, unit, client_hardware_address);
404 if(stat != 0){
405 printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit);
406 exit(STATE_UNKNOWN);
408 /* Kompf 2000-2003 */
410 #else
411 printf(_("Error: can't get MAC address for this architecture. Use the --mac option.\n"));
412 exit(STATE_UNKNOWN);
413 #endif
415 if(verbose)
416 print_hardware_address(client_hardware_address);
418 return OK;
421 /* determines IP address of the client interface */
422 int get_ip_address(int sock,char *interface_name){
423 #if defined(SIOCGIFADDR)
424 struct ifreq ifr;
426 strncpy((char *)&ifr.ifr_name,interface_name,sizeof(ifr.ifr_name)-1);
427 ifr.ifr_name[sizeof(ifr.ifr_name)-1]='\0';
429 if(ioctl(sock,SIOCGIFADDR,&ifr)<0){
430 printf(_("Error: Cannot determine IP address of interface %s\n"),
431 interface_name);
432 exit(STATE_UNKNOWN);
435 my_ip=((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
437 #else
438 printf(_("Error: Cannot get interface IP address on this platform.\n"));
439 exit(STATE_UNKNOWN);
440 #endif
442 if(verbose)
443 printf(_("Pretending to be relay client %s\n"),inet_ntoa(my_ip));
445 return OK;
448 /* sends a DHCPDISCOVER broadcast message in an attempt to find DHCP servers */
449 int send_dhcp_discover(int sock){
450 dhcp_packet discover_packet;
451 struct sockaddr_in sockaddr_broadcast;
452 unsigned short opts;
455 /* clear the packet data structure */
456 bzero(&discover_packet,sizeof(discover_packet));
459 /* boot request flag (backward compatible with BOOTP servers) */
460 discover_packet.op=BOOTREQUEST;
462 /* hardware address type */
463 discover_packet.htype=ETHERNET_HARDWARE_ADDRESS;
465 /* length of our hardware address */
466 discover_packet.hlen=ETHERNET_HARDWARE_ADDRESS_LENGTH;
469 * transaction ID is supposed to be random. We won't use the address so
470 * we don't care about high entropy here. time(2) is good enough.
472 srand(time(NULL));
473 packet_xid=random();
474 discover_packet.xid=htonl(packet_xid);
476 /**** WHAT THE HECK IS UP WITH THIS?!? IF I DON'T MAKE THIS CALL, ONLY ONE SERVER RESPONSE IS PROCESSED!!!! ****/
477 /* downright bizzarre... */
478 ntohl(discover_packet.xid);
480 /*discover_packet.secs=htons(65535);*/
481 discover_packet.secs=0xFF;
484 * server needs to know if it should broadcast or unicast its response:
485 * 0x8000L == 32768 == 1 << 15 == broadcast, 0 == unicast
487 discover_packet.flags = unicast ? 0 : htons(DHCP_BROADCAST_FLAG);
489 /* our hardware address */
490 memcpy(discover_packet.chaddr,client_hardware_address,ETHERNET_HARDWARE_ADDRESS_LENGTH);
492 /* first four bytes of options field is magic cookie (as per RFC 2132) */
493 discover_packet.options[0]='\x63';
494 discover_packet.options[1]='\x82';
495 discover_packet.options[2]='\x53';
496 discover_packet.options[3]='\x63';
498 opts = 4;
499 /* DHCP message type is embedded in options field */
500 discover_packet.options[opts++]=DHCP_OPTION_MESSAGE_TYPE; /* DHCP message type option identifier */
501 discover_packet.options[opts++]='\x01'; /* DHCP message option length in bytes */
502 discover_packet.options[opts++]=DHCPDISCOVER;
504 /* the IP address we're requesting */
505 if(request_specific_address==TRUE){
506 discover_packet.options[opts++]=DHCP_OPTION_REQUESTED_ADDRESS;
507 discover_packet.options[opts++]='\x04';
508 memcpy(&discover_packet.options[opts],&requested_address,sizeof(requested_address));
509 opts += sizeof(requested_address);
511 discover_packet.options[opts++]=DHCP_OPTION_END;
513 /* unicast fields */
514 if(unicast)
515 discover_packet.giaddr.s_addr = my_ip.s_addr;
517 /* see RFC 1542, 4.1.1 */
518 discover_packet.hops = unicast ? 1 : 0;
520 /* send the DHCPDISCOVER packet to broadcast address */
521 sockaddr_broadcast.sin_family=AF_INET;
522 sockaddr_broadcast.sin_port=htons(DHCP_SERVER_PORT);
523 sockaddr_broadcast.sin_addr.s_addr = unicast ? dhcp_ip.s_addr : INADDR_BROADCAST;
524 bzero(&sockaddr_broadcast.sin_zero,sizeof(sockaddr_broadcast.sin_zero));
527 if(verbose){
528 printf(_("DHCPDISCOVER to %s port %d\n"),inet_ntoa(sockaddr_broadcast.sin_addr),ntohs(sockaddr_broadcast.sin_port));
529 printf("DHCPDISCOVER XID: %u (0x%X)\n",ntohl(discover_packet.xid),ntohl(discover_packet.xid));
530 printf("DHCDISCOVER ciaddr: %s\n",inet_ntoa(discover_packet.ciaddr));
531 printf("DHCDISCOVER yiaddr: %s\n",inet_ntoa(discover_packet.yiaddr));
532 printf("DHCDISCOVER siaddr: %s\n",inet_ntoa(discover_packet.siaddr));
533 printf("DHCDISCOVER giaddr: %s\n",inet_ntoa(discover_packet.giaddr));
536 /* send the DHCPDISCOVER packet out */
537 send_dhcp_packet(&discover_packet,sizeof(discover_packet),sock,&sockaddr_broadcast);
539 if(verbose)
540 printf("\n\n");
542 return OK;
548 /* waits for a DHCPOFFER message from one or more DHCP servers */
549 int get_dhcp_offer(int sock){
550 dhcp_packet offer_packet;
551 struct sockaddr_in source;
552 struct sockaddr_in via;
553 int result=OK;
554 int responses=0;
555 int x;
556 time_t start_time;
557 time_t current_time;
559 time(&start_time);
561 /* receive as many responses as we can */
562 for(responses=0,valid_responses=0;;){
564 time(&current_time);
565 if((current_time-start_time)>=dhcpoffer_timeout)
566 break;
568 if(verbose)
569 printf("\n\n");
571 bzero(&source,sizeof(source));
572 bzero(&via,sizeof(via));
573 bzero(&offer_packet,sizeof(offer_packet));
575 result=OK;
576 result=receive_dhcp_packet(&offer_packet,sizeof(offer_packet),sock,dhcpoffer_timeout,&source);
578 if(result!=OK){
579 if(verbose)
580 printf(_("Result=ERROR\n"));
582 continue;
584 else{
585 if(verbose)
586 printf(_("Result=OK\n"));
588 responses++;
591 /* The "source" is either a server or a relay. */
592 /* Save a copy of "source" into "via" even if it's via itself */
593 memcpy(&via,&source,sizeof(source)) ;
595 /* If siaddr is non-zero, set "source" to siaddr */
596 if(offer_packet.siaddr.s_addr != 0L){
597 source.sin_addr.s_addr = offer_packet.siaddr.s_addr ;
600 if(verbose){
601 printf(_("DHCPOFFER from IP address %s"),inet_ntoa(source.sin_addr));
602 printf(_(" via %s\n"),inet_ntoa(via.sin_addr));
603 printf("DHCPOFFER XID: %u (0x%X)\n",ntohl(offer_packet.xid),ntohl(offer_packet.xid));
606 /* check packet xid to see if its the same as the one we used in the discover packet */
607 if(ntohl(offer_packet.xid)!=packet_xid){
608 if(verbose)
609 printf(_("DHCPOFFER XID (%u) did not match DHCPDISCOVER XID (%u) - ignoring packet\n"),ntohl(offer_packet.xid),packet_xid);
611 continue;
614 /* check hardware address */
615 result=OK;
616 if(verbose)
617 printf("DHCPOFFER chaddr: ");
619 for(x=0;x<ETHERNET_HARDWARE_ADDRESS_LENGTH;x++){
620 if(verbose)
621 printf("%02X",(unsigned char)offer_packet.chaddr[x]);
623 if(offer_packet.chaddr[x]!=client_hardware_address[x])
624 result=ERROR;
626 if(verbose)
627 printf("\n");
629 if(result==ERROR){
630 if(verbose)
631 printf(_("DHCPOFFER hardware address did not match our own - ignoring packet\n"));
633 continue;
636 if(verbose){
637 printf("DHCPOFFER ciaddr: %s\n",inet_ntoa(offer_packet.ciaddr));
638 printf("DHCPOFFER yiaddr: %s\n",inet_ntoa(offer_packet.yiaddr));
639 printf("DHCPOFFER siaddr: %s\n",inet_ntoa(offer_packet.siaddr));
640 printf("DHCPOFFER giaddr: %s\n",inet_ntoa(offer_packet.giaddr));
643 add_dhcp_offer(source.sin_addr,&offer_packet);
645 valid_responses++;
648 if(verbose){
649 printf(_("Total responses seen on the wire: %d\n"),responses);
650 printf(_("Valid responses for this machine: %d\n"),valid_responses);
653 return OK;
658 /* sends a DHCP packet */
659 int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in *dest){
660 int result;
662 result=sendto(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)dest,sizeof(*dest));
664 if(verbose)
665 printf(_("send_dhcp_packet result: %d\n"),result);
667 if(result<0)
668 return ERROR;
670 return OK;
675 /* receives a DHCP packet */
676 int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, struct sockaddr_in *address){
677 struct timeval tv;
678 fd_set readfds;
679 fd_set oobfds;
680 int recv_result;
681 socklen_t address_size;
682 struct sockaddr_in source_address;
683 int nfound;
686 /* wait for data to arrive (up time timeout) */
687 tv.tv_sec=timeout;
688 tv.tv_usec=0;
689 FD_ZERO(&readfds);
690 FD_ZERO(&oobfds);
691 FD_SET(sock,&readfds);
692 FD_SET(sock,&oobfds);
693 nfound = select(sock+1,&readfds,NULL,&oobfds,&tv);
695 /* make sure some data has arrived */
696 if(!FD_ISSET(sock,&readfds)){
697 if(verbose)
698 printf(_("No (more) data received (nfound: %d)\n"), nfound);
699 return ERROR;
702 else{
704 /* why do we need to peek first? i don't know, its a hack. without it, the source address of the first packet received was
705 not being interpreted correctly. sigh... */
706 bzero(&source_address,sizeof(source_address));
707 address_size=sizeof(source_address);
708 recv_result=recvfrom(sock,(char *)buffer,buffer_size,MSG_PEEK,(struct sockaddr *)&source_address,&address_size);
709 if(verbose)
710 printf("recv_result_1: %d\n",recv_result);
711 recv_result=recvfrom(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)&source_address,&address_size);
712 if(verbose)
713 printf("recv_result_2: %d\n",recv_result);
715 if(recv_result==-1){
716 if(verbose){
717 printf(_("recvfrom() failed, "));
718 printf("errno: (%d) -> %s\n",errno,strerror(errno));
720 return ERROR;
722 else{
723 if(verbose){
724 printf(_("receive_dhcp_packet() result: %d\n"),recv_result);
725 printf(_("receive_dhcp_packet() source: %s\n"),inet_ntoa(source_address.sin_addr));
728 memcpy(address,&source_address,sizeof(source_address));
729 return OK;
733 return OK;
737 /* creates a socket for DHCP communication */
738 int create_dhcp_socket(void){
739 struct sockaddr_in myname;
740 struct ifreq interface;
741 int sock;
742 int flag=1;
744 /* Set up the address we're going to bind to. */
745 bzero(&myname,sizeof(myname));
746 myname.sin_family=AF_INET;
747 /* listen to DHCP server port if we're in unicast mode */
748 myname.sin_port = htons(unicast ? DHCP_SERVER_PORT : DHCP_CLIENT_PORT);
749 myname.sin_addr.s_addr = unicast ? my_ip.s_addr : INADDR_ANY;
750 bzero(&myname.sin_zero,sizeof(myname.sin_zero));
752 /* create a socket for DHCP communications */
753 sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
754 if(sock<0){
755 printf(_("Error: Could not create socket!\n"));
756 exit(STATE_UNKNOWN);
759 if(verbose)
760 printf("DHCP socket: %d\n",sock);
762 /* set the reuse address flag so we don't get errors when restarting */
763 flag=1;
764 if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char *)&flag,sizeof(flag))<0){
765 printf(_("Error: Could not set reuse address option on DHCP socket!\n"));
766 exit(STATE_UNKNOWN);
769 /* set the broadcast option - we need this to listen to DHCP broadcast messages */
770 if(setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char *)&flag,sizeof flag)<0){
771 printf(_("Error: Could not set broadcast option on DHCP socket!\n"));
772 exit(STATE_UNKNOWN);
775 /* bind socket to interface */
776 #if defined(__linux__)
777 strncpy(interface.ifr_ifrn.ifrn_name,network_interface_name,IFNAMSIZ-1);
778 interface.ifr_ifrn.ifrn_name[IFNAMSIZ-1]='\0';
779 if(setsockopt(sock,SOL_SOCKET,SO_BINDTODEVICE,(char *)&interface,sizeof(interface))<0){
780 printf(_("Error: Could not bind socket to interface %s. Check your privileges...\n"),network_interface_name);
781 exit(STATE_UNKNOWN);
784 #else
785 strncpy(interface.ifr_name,network_interface_name,IFNAMSIZ-1);
786 interface.ifr_name[IFNAMSIZ-1]='\0';
787 #endif
789 /* bind the socket */
790 if(bind(sock,(struct sockaddr *)&myname,sizeof(myname))<0){
791 printf(_("Error: Could not bind to DHCP socket (port %d)! Check your privileges...\n"),DHCP_CLIENT_PORT);
792 exit(STATE_UNKNOWN);
795 return sock;
799 /* closes DHCP socket */
800 int close_dhcp_socket(int sock){
802 close(sock);
804 return OK;
808 /* adds a requested server address to list in memory */
809 int add_requested_server(struct in_addr server_address){
810 requested_server *new_server;
812 new_server=(requested_server *)malloc(sizeof(requested_server));
813 if(new_server==NULL)
814 return ERROR;
816 new_server->server_address=server_address;
817 new_server->answered=FALSE;
819 new_server->next=requested_server_list;
820 requested_server_list=new_server;
822 requested_servers++;
824 if(verbose)
825 printf(_("Requested server address: %s\n"),inet_ntoa(new_server->server_address));
827 return OK;
833 /* adds a DHCP OFFER to list in memory */
834 int add_dhcp_offer(struct in_addr source,dhcp_packet *offer_packet){
835 dhcp_offer *new_offer;
836 int x;
837 unsigned option_type;
838 unsigned option_length;
839 struct in_addr serv_ident = {0};
841 if(offer_packet==NULL)
842 return ERROR;
844 /* process all DHCP options present in the packet */
845 for(x=4;x<MAX_DHCP_OPTIONS_LENGTH;){
847 /* end of options (0 is really just a pad, but bail out anyway) */
848 if((int)offer_packet->options[x]==-1 || (int)offer_packet->options[x]==0)
849 break;
851 /* get option type */
852 option_type=offer_packet->options[x++];
854 /* get option length */
855 option_length=offer_packet->options[x++];
857 if(verbose)
858 printf("Option: %d (0x%02X)\n",option_type,option_length);
860 /* get option data */
861 switch(option_type){
862 case DHCP_OPTION_LEASE_TIME:
863 memcpy(&dhcp_lease_time, &offer_packet->options[x],sizeof(dhcp_lease_time));
864 dhcp_lease_time = ntohl(dhcp_lease_time);
865 break;
866 case DHCP_OPTION_RENEWAL_TIME:
867 memcpy(&dhcp_renewal_time, &offer_packet->options[x],sizeof(dhcp_renewal_time));
868 dhcp_renewal_time = ntohl(dhcp_renewal_time);
869 break;
870 case DHCP_OPTION_REBINDING_TIME:
871 memcpy(&dhcp_rebinding_time, &offer_packet->options[x],sizeof(dhcp_rebinding_time));
872 dhcp_rebinding_time = ntohl(dhcp_rebinding_time);
873 break;
874 case DHCP_OPTION_SERVER_IDENTIFIER:
875 memcpy(&serv_ident.s_addr, &offer_packet->options[x],sizeof(serv_ident.s_addr));
876 break;
879 /* skip option data we're ignoring */
880 if(option_type!=DHCP_OPTION_REBINDING_TIME)
881 x+=option_length;
884 if(verbose){
885 if(dhcp_lease_time==DHCP_INFINITE_TIME)
886 printf(_("Lease Time: Infinite\n"));
887 else
888 printf(_("Lease Time: %lu seconds\n"),(unsigned long)dhcp_lease_time);
889 if(dhcp_renewal_time==DHCP_INFINITE_TIME)
890 printf(_("Renewal Time: Infinite\n"));
891 else
892 printf(_("Renewal Time: %lu seconds\n"),(unsigned long)dhcp_renewal_time);
893 if(dhcp_rebinding_time==DHCP_INFINITE_TIME)
894 printf(_("Rebinding Time: Infinite\n"));
895 printf(_("Rebinding Time: %lu seconds\n"),(unsigned long)dhcp_rebinding_time);
898 new_offer=(dhcp_offer *)malloc(sizeof(dhcp_offer));
900 if(new_offer==NULL)
901 return ERROR;
904 * RFC 2131 (2.) says: "DHCP clarifies the interpretation of the
905 * 'siaddr' field as the address of the server to use in the next step
906 * of the client's bootstrap process. A DHCP server may return its own
907 * address in the 'siaddr' field, if the server is prepared to supply
908 * the next bootstrap service (e.g., delivery of an operating system
909 * executable image). A DHCP server always returns its own address in
910 * the 'server identifier' option." 'serv_ident' is the 'server
911 * identifier' option, 'source' is the 'siaddr' field or (if 'siaddr'
912 * wasn't available) the IP address we received the DHCPOFFER from. If
913 * 'serv_ident' isn't available for some reason, we use 'source'.
915 new_offer->server_address=serv_ident.s_addr?serv_ident:source;
916 new_offer->offered_address=offer_packet->yiaddr;
917 new_offer->lease_time=dhcp_lease_time;
918 new_offer->renewal_time=dhcp_renewal_time;
919 new_offer->rebinding_time=dhcp_rebinding_time;
922 if(verbose){
923 printf(_("Added offer from server @ %s"),inet_ntoa(new_offer->server_address));
924 printf(_(" of IP address %s\n"),inet_ntoa(new_offer->offered_address));
927 /* add new offer to head of list */
928 new_offer->next=dhcp_offer_list;
929 dhcp_offer_list=new_offer;
931 return OK;
935 /* frees memory allocated to DHCP OFFER list */
936 int free_dhcp_offer_list(void){
937 dhcp_offer *this_offer;
938 dhcp_offer *next_offer;
940 for(this_offer=dhcp_offer_list;this_offer!=NULL;this_offer=next_offer){
941 next_offer=this_offer->next;
942 free(this_offer);
945 return OK;
949 /* frees memory allocated to requested server list */
950 int free_requested_server_list(void){
951 requested_server *this_server;
952 requested_server *next_server;
954 for(this_server=requested_server_list;this_server!=NULL;this_server=next_server){
955 next_server=this_server->next;
956 free(this_server);
959 return OK;
963 /* gets state and plugin output to return */
964 int get_results(void){
965 dhcp_offer *temp_offer;
966 requested_server *temp_server;
967 int result;
968 u_int32_t max_lease_time=0;
970 received_requested_address=FALSE;
972 /* checks responses from requested servers */
973 requested_responses=0;
974 if(requested_servers>0){
976 for(temp_server=requested_server_list;temp_server!=NULL;temp_server=temp_server->next){
978 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
980 /* get max lease time we were offered */
981 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
982 max_lease_time=temp_offer->lease_time;
984 /* see if we got the address we requested */
985 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
986 received_requested_address=TRUE;
988 /* see if the servers we wanted a response from talked to us or not */
989 if(!memcmp(&temp_offer->server_address,&temp_server->server_address,sizeof(temp_server->server_address))){
990 if(verbose){
991 printf(_("DHCP Server Match: Offerer=%s"),inet_ntoa(temp_offer->server_address));
992 printf(_(" Requested=%s"),inet_ntoa(temp_server->server_address));
993 if(temp_server->answered)
994 printf(_(" (duplicate)"));
995 printf(_("\n"));
997 if(temp_server->answered == FALSE){
998 requested_responses++;
999 temp_server->answered=TRUE;
1007 /* else check and see if we got our requested address from any server */
1008 else{
1010 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
1012 /* get max lease time we were offered */
1013 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
1014 max_lease_time=temp_offer->lease_time;
1016 /* see if we got the address we requested */
1017 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
1018 received_requested_address=TRUE;
1022 result=STATE_OK;
1023 if(valid_responses==0)
1024 result=STATE_CRITICAL;
1025 else if(requested_servers>0 && requested_responses==0)
1026 result=STATE_CRITICAL;
1027 else if(requested_responses<requested_servers)
1028 result=STATE_WARNING;
1029 else if(request_specific_address==TRUE && received_requested_address==FALSE)
1030 result=STATE_WARNING;
1032 if(result==0) /* garrett honeycutt 2005 */
1033 printf("OK: ");
1034 else if(result==1)
1035 printf("WARNING: ");
1036 else if(result==2)
1037 printf("CRITICAL: ");
1038 else if(result==3)
1039 printf("UNKNOWN: ");
1041 /* we didn't receive any DHCPOFFERs */
1042 if(dhcp_offer_list==NULL){
1043 printf(_("No DHCPOFFERs were received.\n"));
1044 return result;
1047 printf(_("Received %d DHCPOFFER(s)"),valid_responses);
1049 if(requested_servers>0)
1050 printf(_(", %s%d of %d requested servers responded"),((requested_responses<requested_servers) && requested_responses>0)?"only ":"",requested_responses,requested_servers);
1052 if(request_specific_address==TRUE)
1053 printf(_(", requested address (%s) was %soffered"),inet_ntoa(requested_address),(received_requested_address==TRUE)?"":_("not "));
1055 printf(_(", max lease time = "));
1056 if(max_lease_time==DHCP_INFINITE_TIME)
1057 printf(_("Infinity"));
1058 else
1059 printf("%lu sec",(unsigned long)max_lease_time);
1061 printf(".\n");
1063 return result;
1067 /* process command-line arguments */
1068 int process_arguments(int argc, char **argv){
1069 int c;
1071 if(argc<1)
1072 return ERROR;
1074 c=0;
1075 while((c+=(call_getopt(argc-c,&argv[c])))<argc){
1078 if(is_option(argv[c]))
1079 continue;
1083 return validate_arguments();
1088 int call_getopt(int argc, char **argv){
1089 int c=0;
1090 int i=0;
1092 int option_index = 0;
1093 static struct option long_options[] =
1095 {"serverip", required_argument,0,'s'},
1096 {"requestedip", required_argument,0,'r'},
1097 {"timeout", required_argument,0,'t'},
1098 {"interface", required_argument,0,'i'},
1099 {"mac", required_argument,0,'m'},
1100 {"unicast", no_argument, 0,'u'},
1101 {"verbose", no_argument, 0,'v'},
1102 {"version", no_argument, 0,'V'},
1103 {"help", no_argument, 0,'h'},
1104 {0,0,0,0}
1107 while(1){
1108 c=getopt_long(argc,argv,"+hVvt:s:r:t:i:m:u",long_options,&option_index);
1110 i++;
1112 if(c==-1||c==EOF||c==1)
1113 break;
1115 switch(c){
1116 case 'w':
1117 case 'r':
1118 case 't':
1119 case 'i':
1120 i++;
1121 break;
1122 default:
1123 break;
1126 switch(c){
1128 case 's': /* DHCP server address */
1129 resolve_host(optarg,&dhcp_ip);
1130 add_requested_server(dhcp_ip);
1131 break;
1133 case 'r': /* address we are requested from DHCP servers */
1134 resolve_host(optarg,&requested_address);
1135 request_specific_address=TRUE;
1136 break;
1138 case 't': /* timeout */
1141 if(is_intnonneg(optarg))
1143 if(atoi(optarg)>0)
1144 dhcpoffer_timeout=atoi(optarg);
1146 else
1147 usage("Time interval must be a nonnegative integer\n");
1149 break;
1151 case 'm': /* MAC address */
1153 if((user_specified_mac=mac_aton(optarg)) == NULL)
1154 usage("Cannot parse MAC address.\n");
1155 if(verbose)
1156 print_hardware_address(user_specified_mac);
1158 break;
1160 case 'i': /* interface name */
1162 strncpy(network_interface_name,optarg,sizeof(network_interface_name)-1);
1163 network_interface_name[sizeof(network_interface_name)-1]='\x0';
1165 break;
1167 case 'u': /* unicast testing */
1168 unicast=1;
1169 break;
1171 case 'V': /* version */
1172 print_revision(progname,revision);
1173 exit(STATE_OK);
1175 case 'h': /* help */
1176 print_help();
1177 exit(STATE_OK);
1179 case 'v': /* verbose */
1180 verbose=1;
1181 break;
1183 case '?': /* help */
1184 usage5 ();
1185 break;
1187 default:
1188 break;
1192 return i;
1196 int validate_arguments(void){
1198 return OK;
1202 #if defined(__sun__) || defined(__solaris__) || defined(__hpux__)
1203 /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */
1205 /* get a message from a stream; return type of message */
1206 static int get_msg(int fd){
1207 int flags = 0;
1208 int res, ret;
1209 ctl_area[0] = 0;
1210 dat_area[0] = 0;
1211 ret = 0;
1212 res = getmsg(fd, &ctl, &dat, &flags);
1214 if(res < 0){
1215 if(errno == EINTR){
1216 return(GOT_INTR);
1218 else{
1219 printf("%s\n", "get_msg FAILED.");
1220 return(GOT_ERR);
1223 if(ctl.len > 0){
1224 ret |= GOT_CTRL;
1226 if(dat.len > 0){
1227 ret |= GOT_DATA;
1230 return(ret);
1233 /* verify that dl_primitive in ctl_area = prim */
1234 static int check_ctrl(int prim){
1235 dl_error_ack_t *err_ack = (dl_error_ack_t *)ctl_area;
1237 if(err_ack->dl_primitive != prim){
1238 printf(_("Error: DLPI stream API failed to get MAC in check_ctrl: %s.\n"), strerror(errno));
1239 exit(STATE_UNKNOWN);
1242 return 0;
1245 /* put a control message on a stream */
1246 static int put_ctrl(int fd, int len, int pri){
1248 ctl.len = len;
1249 if(putmsg(fd, &ctl, 0, pri) < 0){
1250 printf(_("Error: DLPI stream API failed to get MAC in put_ctrl/putmsg(): %s.\n"), strerror(errno));
1251 exit(STATE_UNKNOWN);
1254 return 0;
1257 /* put a control + data message on a stream */
1258 static int put_both(int fd, int clen, int dlen, int pri){
1260 ctl.len = clen;
1261 dat.len = dlen;
1262 if(putmsg(fd, &ctl, &dat, pri) < 0){
1263 printf(_("Error: DLPI stream API failed to get MAC in put_both/putmsg().\n"), strerror(errno));
1264 exit(STATE_UNKNOWN);
1267 return 0;
1270 /* open file descriptor and attach */
1271 static int dl_open(const char *dev, int unit, int *fd){
1272 dl_attach_req_t *attach_req = (dl_attach_req_t *)ctl_area;
1274 if((*fd = open(dev, O_RDWR)) == -1){
1275 printf(_("Error: DLPI stream API failed to get MAC in dl_attach_req/open(%s..): %s.\n"), dev, strerror(errno));
1276 exit(STATE_UNKNOWN);
1278 attach_req->dl_primitive = DL_ATTACH_REQ;
1279 attach_req->dl_ppa = unit;
1280 put_ctrl(*fd, sizeof(dl_attach_req_t), 0);
1281 get_msg(*fd);
1282 return check_ctrl(DL_OK_ACK);
1285 /* send DL_BIND_REQ */
1286 static int dl_bind(int fd, int sap, u_char *addr){
1287 dl_bind_req_t *bind_req = (dl_bind_req_t *)ctl_area;
1288 dl_bind_ack_t *bind_ack = (dl_bind_ack_t *)ctl_area;
1290 bind_req->dl_primitive = DL_BIND_REQ;
1291 bind_req->dl_sap = sap;
1292 bind_req->dl_max_conind = 1;
1293 bind_req->dl_service_mode = DL_CLDLS;
1294 bind_req->dl_conn_mgmt = 0;
1295 bind_req->dl_xidtest_flg = 0;
1296 put_ctrl(fd, sizeof(dl_bind_req_t), 0);
1297 get_msg(fd);
1298 if (GOT_ERR == check_ctrl(DL_BIND_ACK)){
1299 printf(_("Error: DLPI stream API failed to get MAC in dl_bind/check_ctrl(): %s.\n"), strerror(errno));
1300 exit(STATE_UNKNOWN);
1302 bcopy((u_char *)bind_ack + bind_ack->dl_addr_offset, addr,
1303 bind_ack->dl_addr_length);
1305 return 0;
1308 /***********************************************************************
1309 * interface:
1310 * function mac_addr_dlpi - get the mac address of the interface with
1311 * type dev (eg lnc, hme) and unit (0, 1 ..)
1313 * parameter: addr: an array of six bytes, has to be allocated by the caller
1315 * return: 0 if OK, -1 if the address could not be determined
1318 ***********************************************************************/
1320 long mac_addr_dlpi( const char *dev, int unit, u_char *addr){
1321 int fd;
1322 u_char mac_addr[25];
1324 if(GOT_ERR != dl_open(dev, unit, &fd)){
1325 if(GOT_ERR != dl_bind(fd, INSAP, mac_addr)){
1326 bcopy( mac_addr, addr, 6);
1327 return 0;
1330 close(fd);
1332 return -1;
1335 /* Kompf 2000-2003 */
1336 #endif
1339 /* resolve host name or die (TODO: move this to netutils.c!) */
1340 void resolve_host(const char *in,struct in_addr *out){
1341 struct addrinfo hints, *ai;
1343 memset(&hints,0,sizeof(hints));
1344 hints.ai_family=PF_INET;
1345 if (getaddrinfo(in,NULL,&hints,&ai) != 0)
1346 usage_va(_("Invalid hostname/address - %s"),optarg);
1348 memcpy(out,&((struct sockaddr_in *)ai->ai_addr)->sin_addr,sizeof(*out));
1349 freeaddrinfo(ai);
1353 /* parse MAC address string, return 6 bytes (unterminated) or NULL */
1354 unsigned char *mac_aton(const char *string){
1355 static unsigned char result[6];
1356 char tmp[3];
1357 unsigned i, j;
1359 for(i=0, j=0; string[i] != '\0' && j < sizeof(result); i++){
1360 /* ignore ':' and any other non-hex character */
1361 if(!isxdigit(string[i]) || !isxdigit(string[i+1]))
1362 continue;
1363 tmp[0]=string[i];
1364 tmp[1]=string[i+1];
1365 tmp[2]='\0';
1366 result[j]=strtol(tmp,(char **)NULL,16);
1367 i++;
1368 j++;
1371 return (j==6) ? result : NULL;
1375 void print_hardware_address(const unsigned char *address){
1376 int i;
1378 printf(_("Hardware address: "));
1379 for (i=0; i<5; i++)
1380 printf("%2.2x:", address[i]);
1381 printf("%2.2x", address[i]);
1382 putchar('\n');
1386 /* print usage help */
1387 void print_help(void){
1389 print_revision(progname,revision);
1391 printf("Copyright (c) 2001-2004 Ethan Galstad (nagios@nagios.org)\n");
1392 printf (COPYRIGHT, copyright, email);
1394 printf("%s\n", _("This plugin tests the availability of DHCP servers on a network."));
1396 printf ("\n\n");
1398 print_usage();
1400 printf (_(UT_HELP_VRSN));
1401 printf (_(UT_EXTRA_OPTS));
1403 printf (_(UT_VERBOSE));
1405 printf (" %s\n", "-s, --serverip=IPADDRESS");
1406 printf (" %s\n", _("IP address of DHCP server that we must hear from"));
1407 printf (" %s\n", "-r, --requestedip=IPADDRESS");
1408 printf (" %s\n", _("IP address that should be offered by at least one DHCP server"));
1409 printf (" %s\n", "-t, --timeout=INTEGER");
1410 printf (" %s\n", _("Seconds to wait for DHCPOFFER before timeout occurs"));
1411 printf (" %s\n", "-i, --interface=STRING");
1412 printf (" %s\n", _("Interface to to use for listening (i.e. eth0)"));
1413 printf (" %s\n", "-m, --mac=STRING");
1414 printf (" %s\n", _("MAC address to use in the DHCP request"));
1415 printf (" %s\n", "-u, --unicast");
1416 printf (" %s\n", _("Unicast testing: mimic a DHCP relay, requires -s"));
1418 #ifdef NP_EXTRA_OPTS
1419 printf ("\n");
1420 printf ("%s\n", _("Notes:"));
1421 printf (_(UT_EXTRA_OPTS_NOTES));
1422 #endif
1424 printf (_(UT_SUPPORT));
1425 return;
1429 void
1430 print_usage(void){
1432 printf (_("Usage:"));
1433 printf (" %s [-v] [-u] [-s serverip] [-r requestedip] [-t timeout]\n",progname);
1434 printf (" [-i interface] [-m mac]\n");
1436 return;