Under some circumstances, the 'url' path of a redirection target missed
[monitoring-plugins.git] / plugins-root / check_dhcp.c
blob5781f758db2e2f5a3efbc6f2e0ab2c89b90b47a3
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
199 #define DHCP_SERVER_PORT 67
200 #define DHCP_CLIENT_PORT 68
202 #define ETHERNET_HARDWARE_ADDRESS 1 /* used in htype field of dhcp packet */
203 #define ETHERNET_HARDWARE_ADDRESS_LENGTH 6 /* length of Ethernet hardware addresses */
205 u_int8_t unicast = 0; /* unicast mode: mimic a DHCP relay */
206 struct in_addr my_ip; /* our address (required for relay) */
207 struct in_addr dhcp_ip; /* server to query (if in unicast mode) */
208 unsigned char client_hardware_address[MAX_DHCP_CHADDR_LENGTH]="";
209 unsigned char *user_specified_mac=NULL;
211 char network_interface_name[IFNAMSIZ]="eth0";
213 u_int32_t packet_xid=0;
215 u_int32_t dhcp_lease_time=0;
216 u_int32_t dhcp_renewal_time=0;
217 u_int32_t dhcp_rebinding_time=0;
219 int dhcpoffer_timeout=2;
221 dhcp_offer *dhcp_offer_list=NULL;
222 requested_server *requested_server_list=NULL;
224 int valid_responses=0; /* number of valid DHCPOFFERs we received */
225 int requested_servers=0;
226 int requested_responses=0;
228 int request_specific_address=FALSE;
229 int received_requested_address=FALSE;
230 int verbose=0;
231 struct in_addr requested_address;
234 int process_arguments(int, char **);
235 int call_getopt(int, char **);
236 int validate_arguments(void);
237 void print_usage(void);
238 void print_help(void);
240 void resolve_host(const char *in,struct in_addr *out);
241 unsigned char *mac_aton(const char *);
242 void print_hardware_address(const unsigned char *);
243 int get_hardware_address(int,char *);
244 int get_ip_address(int,char *);
246 int send_dhcp_discover(int);
247 int get_dhcp_offer(int);
249 int get_results(void);
251 int add_dhcp_offer(struct in_addr,dhcp_packet *);
252 int free_dhcp_offer_list(void);
253 int free_requested_server_list(void);
255 int create_dhcp_socket(void);
256 int close_dhcp_socket(int);
257 int send_dhcp_packet(void *,int,int,struct sockaddr_in *);
258 int receive_dhcp_packet(void *,int,int,int,struct sockaddr_in *);
262 int main(int argc, char **argv){
263 int dhcp_socket;
264 int result = STATE_UNKNOWN;
266 setlocale (LC_ALL, "");
267 bindtextdomain (PACKAGE, LOCALEDIR);
268 textdomain (PACKAGE);
270 /* Parse extra opts if any */
271 argv=np_extra_opts(&argc, argv, progname);
273 if(process_arguments(argc,argv)!=OK){
274 usage4 (_("Could not parse arguments"));
277 /* this plugin almost certainly needs root permissions. */
278 np_warn_if_not_root();
280 /* create socket for DHCP communications */
281 dhcp_socket=create_dhcp_socket();
283 /* get hardware address of client machine */
284 if(user_specified_mac!=NULL)
285 memcpy(client_hardware_address,user_specified_mac,6);
286 else
287 get_hardware_address(dhcp_socket,network_interface_name);
289 if(unicast) /* get IP address of client machine */
290 get_ip_address(dhcp_socket,network_interface_name);
292 /* send DHCPDISCOVER packet */
293 send_dhcp_discover(dhcp_socket);
295 /* wait for a DHCPOFFER packet */
296 get_dhcp_offer(dhcp_socket);
298 /* close socket we created */
299 close_dhcp_socket(dhcp_socket);
301 /* determine state/plugin output to return */
302 result=get_results();
304 /* free allocated memory */
305 free_dhcp_offer_list();
306 free_requested_server_list();
308 return result;
313 /* determines hardware address on client machine */
314 int get_hardware_address(int sock,char *interface_name){
316 #if defined(__linux__)
317 struct ifreq ifr;
319 strncpy((char *)&ifr.ifr_name,interface_name,sizeof(ifr.ifr_name)-1);
320 ifr.ifr_name[sizeof(ifr.ifr_name)-1]='\0';
322 /* try and grab hardware address of requested interface */
323 if(ioctl(sock,SIOCGIFHWADDR,&ifr)<0){
324 printf(_("Error: Could not get hardware address of interface '%s'\n"),interface_name);
325 exit(STATE_UNKNOWN);
328 memcpy(&client_hardware_address[0],&ifr.ifr_hwaddr.sa_data,6);
330 #elif defined(__bsd__)
331 /* King 2004 see ACKNOWLEDGEMENTS */
333 int mib[6], len;
334 char *buf;
335 unsigned char *ptr;
336 struct if_msghdr *ifm;
337 struct sockaddr_dl *sdl;
339 mib[0] = CTL_NET;
340 mib[1] = AF_ROUTE;
341 mib[2] = 0;
342 mib[3] = AF_LINK;
343 mib[4] = NET_RT_IFLIST;
345 if((mib[5] = if_nametoindex(interface_name)) == 0){
346 printf(_("Error: if_nametoindex error - %s.\n"), strerror(errno));
347 exit(STATE_UNKNOWN);
350 if(sysctl(mib, 6, NULL, &len, NULL, 0) < 0){
351 printf(_("Error: Couldn't get hardware address from %s. sysctl 1 error - %s.\n"), interface_name, strerror(errno));
352 exit(STATE_UNKNOWN);
355 if((buf = malloc(len)) == NULL){
356 printf(_("Error: Couldn't get hardware address from interface %s. malloc error - %s.\n"), interface_name, strerror(errno));
357 exit(4);
360 if(sysctl(mib, 6, buf, &len, NULL, 0) < 0){
361 printf(_("Error: Couldn't get hardware address from %s. sysctl 2 error - %s.\n"), interface_name, strerror(errno));
362 exit(STATE_UNKNOWN);
365 ifm = (struct if_msghdr *)buf;
366 sdl = (struct sockaddr_dl *)(ifm + 1);
367 ptr = (unsigned char *)LLADDR(sdl);
368 memcpy(&client_hardware_address[0], ptr, 6) ;
369 /* King 2004 */
371 #elif defined(__sun__) || defined(__solaris__)
373 /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */
374 long stat;
375 char dev[20] = "/dev/";
376 char *p;
377 int unit;
379 for(p = interface_name; *p && isalpha(*p); p++)
380 /* no-op */ ;
381 if( p != '\0' ){
382 unit = atoi(p) ;
383 *p = '\0' ;
384 strncat(dev, interface_name, 6) ;
386 else{
387 printf(_("Error: can't find unit number in interface_name (%s) - expecting TypeNumber eg lnc0.\n"), interface_name);
388 exit(STATE_UNKNOWN);
390 stat = mac_addr_dlpi(dev, unit, client_hardware_address);
391 if(stat != 0){
392 printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit);
393 exit(STATE_UNKNOWN);
396 #elif defined(__hpux__)
398 long stat;
399 char dev[20] = "/dev/dlpi" ;
400 int unit = 0;
402 stat = mac_addr_dlpi(dev, unit, client_hardware_address);
403 if(stat != 0){
404 printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit);
405 exit(STATE_UNKNOWN);
407 /* Kompf 2000-2003 */
409 #else
410 printf(_("Error: can't get MAC address for this architecture. Use the --mac option.\n"));
411 exit(STATE_UNKNOWN);
412 #endif
414 if(verbose)
415 print_hardware_address(client_hardware_address);
417 return OK;
420 /* determines IP address of the client interface */
421 int get_ip_address(int sock,char *interface_name){
422 #if defined(SIOCGIFADDR)
423 struct ifreq ifr;
425 strncpy((char *)&ifr.ifr_name,interface_name,sizeof(ifr.ifr_name)-1);
426 ifr.ifr_name[sizeof(ifr.ifr_name)-1]='\0';
428 if(ioctl(sock,SIOCGIFADDR,&ifr)<0){
429 printf(_("Error: Cannot determine IP address of interface %s\n"),
430 interface_name);
431 exit(STATE_UNKNOWN);
434 my_ip=((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
436 #else
437 printf(_("Error: Cannot get interface IP address on this platform.\n"));
438 exit(STATE_UNKNOWN);
439 #endif
441 if(verbose)
442 printf(_("Pretending to be relay client %s\n"),inet_ntoa(my_ip));
444 return OK;
447 /* sends a DHCPDISCOVER broadcast message in an attempt to find DHCP servers */
448 int send_dhcp_discover(int sock){
449 dhcp_packet discover_packet;
450 struct sockaddr_in sockaddr_broadcast;
451 unsigned short opts;
454 /* clear the packet data structure */
455 bzero(&discover_packet,sizeof(discover_packet));
458 /* boot request flag (backward compatible with BOOTP servers) */
459 discover_packet.op=BOOTREQUEST;
461 /* hardware address type */
462 discover_packet.htype=ETHERNET_HARDWARE_ADDRESS;
464 /* length of our hardware address */
465 discover_packet.hlen=ETHERNET_HARDWARE_ADDRESS_LENGTH;
468 * transaction ID is supposed to be random. We won't use the address so
469 * we don't care about high entropy here. time(2) is good enough.
471 srand(time(NULL));
472 packet_xid=random();
473 discover_packet.xid=htonl(packet_xid);
475 /**** WHAT THE HECK IS UP WITH THIS?!? IF I DON'T MAKE THIS CALL, ONLY ONE SERVER RESPONSE IS PROCESSED!!!! ****/
476 /* downright bizzarre... */
477 ntohl(discover_packet.xid);
479 /*discover_packet.secs=htons(65535);*/
480 discover_packet.secs=0xFF;
483 * server needs to know if it should broadcast or unicast its response:
484 * 0x8000L == 32768 == 1 << 15 == broadcast, 0 == unicast
486 discover_packet.flags = unicast ? 0 : htons(DHCP_BROADCAST_FLAG);
488 /* our hardware address */
489 memcpy(discover_packet.chaddr,client_hardware_address,ETHERNET_HARDWARE_ADDRESS_LENGTH);
491 /* first four bytes of options field is magic cookie (as per RFC 2132) */
492 discover_packet.options[0]='\x63';
493 discover_packet.options[1]='\x82';
494 discover_packet.options[2]='\x53';
495 discover_packet.options[3]='\x63';
497 opts = 4;
498 /* DHCP message type is embedded in options field */
499 discover_packet.options[opts++]=DHCP_OPTION_MESSAGE_TYPE; /* DHCP message type option identifier */
500 discover_packet.options[opts++]='\x01'; /* DHCP message option length in bytes */
501 discover_packet.options[opts++]=DHCPDISCOVER;
503 /* the IP address we're requesting */
504 if(request_specific_address==TRUE){
505 discover_packet.options[opts++]=DHCP_OPTION_REQUESTED_ADDRESS;
506 discover_packet.options[opts++]='\x04';
507 memcpy(&discover_packet.options[opts],&requested_address,sizeof(requested_address));
508 opts += sizeof(requested_address);
510 discover_packet.options[opts++]=DHCP_OPTION_END;
512 /* unicast fields */
513 if(unicast)
514 discover_packet.giaddr.s_addr = my_ip.s_addr;
516 /* see RFC 1542, 4.1.1 */
517 discover_packet.hops = unicast ? 1 : 0;
519 /* send the DHCPDISCOVER packet to broadcast address */
520 sockaddr_broadcast.sin_family=AF_INET;
521 sockaddr_broadcast.sin_port=htons(DHCP_SERVER_PORT);
522 sockaddr_broadcast.sin_addr.s_addr = unicast ? dhcp_ip.s_addr : INADDR_BROADCAST;
523 bzero(&sockaddr_broadcast.sin_zero,sizeof(sockaddr_broadcast.sin_zero));
526 if(verbose){
527 printf(_("DHCPDISCOVER to %s port %d\n"),inet_ntoa(sockaddr_broadcast.sin_addr),ntohs(sockaddr_broadcast.sin_port));
528 printf("DHCPDISCOVER XID: %u (0x%X)\n",ntohl(discover_packet.xid),ntohl(discover_packet.xid));
529 printf("DHCDISCOVER ciaddr: %s\n",inet_ntoa(discover_packet.ciaddr));
530 printf("DHCDISCOVER yiaddr: %s\n",inet_ntoa(discover_packet.yiaddr));
531 printf("DHCDISCOVER siaddr: %s\n",inet_ntoa(discover_packet.siaddr));
532 printf("DHCDISCOVER giaddr: %s\n",inet_ntoa(discover_packet.giaddr));
535 /* send the DHCPDISCOVER packet out */
536 send_dhcp_packet(&discover_packet,sizeof(discover_packet),sock,&sockaddr_broadcast);
538 if(verbose)
539 printf("\n\n");
541 return OK;
547 /* waits for a DHCPOFFER message from one or more DHCP servers */
548 int get_dhcp_offer(int sock){
549 dhcp_packet offer_packet;
550 struct sockaddr_in source;
551 struct sockaddr_in via;
552 int result=OK;
553 int responses=0;
554 int x;
555 time_t start_time;
556 time_t current_time;
558 time(&start_time);
560 /* receive as many responses as we can */
561 for(responses=0,valid_responses=0;;){
563 time(&current_time);
564 if((current_time-start_time)>=dhcpoffer_timeout)
565 break;
567 if(verbose)
568 printf("\n\n");
570 bzero(&source,sizeof(source));
571 bzero(&via,sizeof(via));
572 bzero(&offer_packet,sizeof(offer_packet));
574 result=OK;
575 result=receive_dhcp_packet(&offer_packet,sizeof(offer_packet),sock,dhcpoffer_timeout,&source);
577 if(result!=OK){
578 if(verbose)
579 printf(_("Result=ERROR\n"));
581 continue;
583 else{
584 if(verbose)
585 printf(_("Result=OK\n"));
587 responses++;
590 /* The "source" is either a server or a relay. */
591 /* Save a copy of "source" into "via" even if it's via itself */
592 memcpy(&via,&source,sizeof(source)) ;
594 /* If siaddr is non-zero, set "source" to siaddr */
595 if(offer_packet.siaddr.s_addr != 0L){
596 source.sin_addr.s_addr = offer_packet.siaddr.s_addr ;
599 if(verbose){
600 printf(_("DHCPOFFER from IP address %s"),inet_ntoa(source.sin_addr));
601 printf(_(" via %s\n"),inet_ntoa(via.sin_addr));
602 printf("DHCPOFFER XID: %u (0x%X)\n",ntohl(offer_packet.xid),ntohl(offer_packet.xid));
605 /* check packet xid to see if its the same as the one we used in the discover packet */
606 if(ntohl(offer_packet.xid)!=packet_xid){
607 if(verbose)
608 printf(_("DHCPOFFER XID (%u) did not match DHCPDISCOVER XID (%u) - ignoring packet\n"),ntohl(offer_packet.xid),packet_xid);
610 continue;
613 /* check hardware address */
614 result=OK;
615 if(verbose)
616 printf("DHCPOFFER chaddr: ");
618 for(x=0;x<ETHERNET_HARDWARE_ADDRESS_LENGTH;x++){
619 if(verbose)
620 printf("%02X",(unsigned char)offer_packet.chaddr[x]);
622 if(offer_packet.chaddr[x]!=client_hardware_address[x])
623 result=ERROR;
625 if(verbose)
626 printf("\n");
628 if(result==ERROR){
629 if(verbose)
630 printf(_("DHCPOFFER hardware address did not match our own - ignoring packet\n"));
632 continue;
635 if(verbose){
636 printf("DHCPOFFER ciaddr: %s\n",inet_ntoa(offer_packet.ciaddr));
637 printf("DHCPOFFER yiaddr: %s\n",inet_ntoa(offer_packet.yiaddr));
638 printf("DHCPOFFER siaddr: %s\n",inet_ntoa(offer_packet.siaddr));
639 printf("DHCPOFFER giaddr: %s\n",inet_ntoa(offer_packet.giaddr));
642 add_dhcp_offer(source.sin_addr,&offer_packet);
644 valid_responses++;
647 if(verbose){
648 printf(_("Total responses seen on the wire: %d\n"),responses);
649 printf(_("Valid responses for this machine: %d\n"),valid_responses);
652 return OK;
657 /* sends a DHCP packet */
658 int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in *dest){
659 int result;
661 result=sendto(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)dest,sizeof(*dest));
663 if(verbose)
664 printf(_("send_dhcp_packet result: %d\n"),result);
666 if(result<0)
667 return ERROR;
669 return OK;
674 /* receives a DHCP packet */
675 int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, struct sockaddr_in *address){
676 struct timeval tv;
677 fd_set readfds;
678 fd_set oobfds;
679 int recv_result;
680 socklen_t address_size;
681 struct sockaddr_in source_address;
682 int nfound;
685 /* wait for data to arrive (up time timeout) */
686 tv.tv_sec=timeout;
687 tv.tv_usec=0;
688 FD_ZERO(&readfds);
689 FD_ZERO(&oobfds);
690 FD_SET(sock,&readfds);
691 FD_SET(sock,&oobfds);
692 nfound = select(sock+1,&readfds,NULL,&oobfds,&tv);
694 /* make sure some data has arrived */
695 if(!FD_ISSET(sock,&readfds)){
696 if(verbose)
697 printf(_("No (more) data received (nfound: %d)\n"), nfound);
698 return ERROR;
701 else{
703 /* 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
704 not being interpreted correctly. sigh... */
705 bzero(&source_address,sizeof(source_address));
706 address_size=sizeof(source_address);
707 recv_result=recvfrom(sock,(char *)buffer,buffer_size,MSG_PEEK,(struct sockaddr *)&source_address,&address_size);
708 if(verbose)
709 printf("recv_result_1: %d\n",recv_result);
710 recv_result=recvfrom(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)&source_address,&address_size);
711 if(verbose)
712 printf("recv_result_2: %d\n",recv_result);
714 if(recv_result==-1){
715 if(verbose){
716 printf(_("recvfrom() failed, "));
717 printf("errno: (%d) -> %s\n",errno,strerror(errno));
719 return ERROR;
721 else{
722 if(verbose){
723 printf(_("receive_dhcp_packet() result: %d\n"),recv_result);
724 printf(_("receive_dhcp_packet() source: %s\n"),inet_ntoa(source_address.sin_addr));
727 memcpy(address,&source_address,sizeof(source_address));
728 return OK;
732 return OK;
736 /* creates a socket for DHCP communication */
737 int create_dhcp_socket(void){
738 struct sockaddr_in myname;
739 struct ifreq interface;
740 int sock;
741 int flag=1;
743 /* Set up the address we're going to bind to. */
744 bzero(&myname,sizeof(myname));
745 myname.sin_family=AF_INET;
746 /* listen to DHCP server port if we're in unicast mode */
747 myname.sin_port = htons(unicast ? DHCP_SERVER_PORT : DHCP_CLIENT_PORT);
748 myname.sin_addr.s_addr = unicast ? my_ip.s_addr : INADDR_ANY;
749 bzero(&myname.sin_zero,sizeof(myname.sin_zero));
751 /* create a socket for DHCP communications */
752 sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
753 if(sock<0){
754 printf(_("Error: Could not create socket!\n"));
755 exit(STATE_UNKNOWN);
758 if(verbose)
759 printf("DHCP socket: %d\n",sock);
761 /* set the reuse address flag so we don't get errors when restarting */
762 flag=1;
763 if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char *)&flag,sizeof(flag))<0){
764 printf(_("Error: Could not set reuse address option on DHCP socket!\n"));
765 exit(STATE_UNKNOWN);
768 /* set the broadcast option - we need this to listen to DHCP broadcast messages */
769 if(!unicast && setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char *)&flag,sizeof flag)<0){
770 printf(_("Error: Could not set broadcast option on DHCP socket!\n"));
771 exit(STATE_UNKNOWN);
774 /* bind socket to interface */
775 #if defined(__linux__)
776 strncpy(interface.ifr_ifrn.ifrn_name,network_interface_name,IFNAMSIZ-1);
777 interface.ifr_ifrn.ifrn_name[IFNAMSIZ-1]='\0';
778 if(setsockopt(sock,SOL_SOCKET,SO_BINDTODEVICE,(char *)&interface,sizeof(interface))<0){
779 printf(_("Error: Could not bind socket to interface %s. Check your privileges...\n"),network_interface_name);
780 exit(STATE_UNKNOWN);
783 #else
784 strncpy(interface.ifr_name,network_interface_name,IFNAMSIZ-1);
785 interface.ifr_name[IFNAMSIZ-1]='\0';
786 #endif
788 /* bind the socket */
789 if(bind(sock,(struct sockaddr *)&myname,sizeof(myname))<0){
790 printf(_("Error: Could not bind to DHCP socket (port %d)! Check your privileges...\n"),DHCP_CLIENT_PORT);
791 exit(STATE_UNKNOWN);
794 return sock;
798 /* closes DHCP socket */
799 int close_dhcp_socket(int sock){
801 close(sock);
803 return OK;
807 /* adds a requested server address to list in memory */
808 int add_requested_server(struct in_addr server_address){
809 requested_server *new_server;
811 new_server=(requested_server *)malloc(sizeof(requested_server));
812 if(new_server==NULL)
813 return ERROR;
815 new_server->server_address=server_address;
816 new_server->answered=FALSE;
818 new_server->next=requested_server_list;
819 requested_server_list=new_server;
821 requested_servers++;
823 if(verbose)
824 printf(_("Requested server address: %s\n"),inet_ntoa(new_server->server_address));
826 return OK;
832 /* adds a DHCP OFFER to list in memory */
833 int add_dhcp_offer(struct in_addr source,dhcp_packet *offer_packet){
834 dhcp_offer *new_offer;
835 int x;
836 unsigned option_type;
837 unsigned option_length;
838 struct in_addr serv_ident = {0};
840 if(offer_packet==NULL)
841 return ERROR;
843 /* process all DHCP options present in the packet */
844 for(x=4;x<MAX_DHCP_OPTIONS_LENGTH;){
846 /* end of options (0 is really just a pad, but bail out anyway) */
847 if((int)offer_packet->options[x]==-1 || (int)offer_packet->options[x]==0)
848 break;
850 /* get option type */
851 option_type=offer_packet->options[x++];
853 /* get option length */
854 option_length=offer_packet->options[x++];
856 if(verbose)
857 printf("Option: %d (0x%02X)\n",option_type,option_length);
859 /* get option data */
860 switch(option_type){
861 case DHCP_OPTION_LEASE_TIME:
862 memcpy(&dhcp_lease_time, &offer_packet->options[x],sizeof(dhcp_lease_time));
863 dhcp_lease_time = ntohl(dhcp_lease_time);
864 break;
865 case DHCP_OPTION_RENEWAL_TIME:
866 memcpy(&dhcp_renewal_time, &offer_packet->options[x],sizeof(dhcp_renewal_time));
867 dhcp_renewal_time = ntohl(dhcp_renewal_time);
868 break;
869 case DHCP_OPTION_REBINDING_TIME:
870 memcpy(&dhcp_rebinding_time, &offer_packet->options[x],sizeof(dhcp_rebinding_time));
871 dhcp_rebinding_time = ntohl(dhcp_rebinding_time);
872 break;
873 case DHCP_OPTION_SERVER_IDENTIFIER:
874 memcpy(&serv_ident.s_addr, &offer_packet->options[x],sizeof(serv_ident.s_addr));
875 break;
878 /* skip option data we're ignoring */
879 if(option_type!=DHCP_OPTION_REBINDING_TIME)
880 x+=option_length;
883 if(verbose){
884 if(dhcp_lease_time==DHCP_INFINITE_TIME)
885 printf(_("Lease Time: Infinite\n"));
886 else
887 printf(_("Lease Time: %lu seconds\n"),(unsigned long)dhcp_lease_time);
888 if(dhcp_renewal_time==DHCP_INFINITE_TIME)
889 printf(_("Renewal Time: Infinite\n"));
890 else
891 printf(_("Renewal Time: %lu seconds\n"),(unsigned long)dhcp_renewal_time);
892 if(dhcp_rebinding_time==DHCP_INFINITE_TIME)
893 printf(_("Rebinding Time: Infinite\n"));
894 printf(_("Rebinding Time: %lu seconds\n"),(unsigned long)dhcp_rebinding_time);
897 new_offer=(dhcp_offer *)malloc(sizeof(dhcp_offer));
899 if(new_offer==NULL)
900 return ERROR;
903 * RFC 2131 (2.) says: "DHCP clarifies the interpretation of the
904 * 'siaddr' field as the address of the server to use in the next step
905 * of the client's bootstrap process. A DHCP server may return its own
906 * address in the 'siaddr' field, if the server is prepared to supply
907 * the next bootstrap service (e.g., delivery of an operating system
908 * executable image). A DHCP server always returns its own address in
909 * the 'server identifier' option." 'serv_ident' is the 'server
910 * identifier' option, 'source' is the 'siaddr' field or (if 'siaddr'
911 * wasn't available) the IP address we received the DHCPOFFER from. If
912 * 'serv_ident' isn't available for some reason, we use 'source'.
914 new_offer->server_address=serv_ident.s_addr?serv_ident:source;
915 new_offer->offered_address=offer_packet->yiaddr;
916 new_offer->lease_time=dhcp_lease_time;
917 new_offer->renewal_time=dhcp_renewal_time;
918 new_offer->rebinding_time=dhcp_rebinding_time;
921 if(verbose){
922 printf(_("Added offer from server @ %s"),inet_ntoa(new_offer->server_address));
923 printf(_(" of IP address %s\n"),inet_ntoa(new_offer->offered_address));
926 /* add new offer to head of list */
927 new_offer->next=dhcp_offer_list;
928 dhcp_offer_list=new_offer;
930 return OK;
934 /* frees memory allocated to DHCP OFFER list */
935 int free_dhcp_offer_list(void){
936 dhcp_offer *this_offer;
937 dhcp_offer *next_offer;
939 for(this_offer=dhcp_offer_list;this_offer!=NULL;this_offer=next_offer){
940 next_offer=this_offer->next;
941 free(this_offer);
944 return OK;
948 /* frees memory allocated to requested server list */
949 int free_requested_server_list(void){
950 requested_server *this_server;
951 requested_server *next_server;
953 for(this_server=requested_server_list;this_server!=NULL;this_server=next_server){
954 next_server=this_server->next;
955 free(this_server);
958 return OK;
962 /* gets state and plugin output to return */
963 int get_results(void){
964 dhcp_offer *temp_offer;
965 requested_server *temp_server;
966 int result;
967 u_int32_t max_lease_time=0;
969 received_requested_address=FALSE;
971 /* checks responses from requested servers */
972 requested_responses=0;
973 if(requested_servers>0){
975 for(temp_server=requested_server_list;temp_server!=NULL;temp_server=temp_server->next){
977 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
979 /* get max lease time we were offered */
980 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
981 max_lease_time=temp_offer->lease_time;
983 /* see if we got the address we requested */
984 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
985 received_requested_address=TRUE;
987 /* see if the servers we wanted a response from talked to us or not */
988 if(!memcmp(&temp_offer->server_address,&temp_server->server_address,sizeof(temp_server->server_address))){
989 if(verbose){
990 printf(_("DHCP Server Match: Offerer=%s"),inet_ntoa(temp_offer->server_address));
991 printf(_(" Requested=%s"),inet_ntoa(temp_server->server_address));
992 if(temp_server->answered)
993 printf(_(" (duplicate)"));
994 printf(_("\n"));
996 if(temp_server->answered == FALSE){
997 requested_responses++;
998 temp_server->answered=TRUE;
1006 /* else check and see if we got our requested address from any server */
1007 else{
1009 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
1011 /* get max lease time we were offered */
1012 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
1013 max_lease_time=temp_offer->lease_time;
1015 /* see if we got the address we requested */
1016 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
1017 received_requested_address=TRUE;
1021 result=STATE_OK;
1022 if(valid_responses==0)
1023 result=STATE_CRITICAL;
1024 else if(requested_servers>0 && requested_responses==0)
1025 result=STATE_CRITICAL;
1026 else if(requested_responses<requested_servers)
1027 result=STATE_WARNING;
1028 else if(request_specific_address==TRUE && received_requested_address==FALSE)
1029 result=STATE_WARNING;
1031 if(result==0) /* garrett honeycutt 2005 */
1032 printf("OK: ");
1033 else if(result==1)
1034 printf("WARNING: ");
1035 else if(result==2)
1036 printf("CRITICAL: ");
1037 else if(result==3)
1038 printf("UNKNOWN: ");
1040 /* we didn't receive any DHCPOFFERs */
1041 if(dhcp_offer_list==NULL){
1042 printf(_("No DHCPOFFERs were received.\n"));
1043 return result;
1046 printf(_("Received %d DHCPOFFER(s)"),valid_responses);
1048 if(requested_servers>0)
1049 printf(_(", %s%d of %d requested servers responded"),((requested_responses<requested_servers) && requested_responses>0)?"only ":"",requested_responses,requested_servers);
1051 if(request_specific_address==TRUE)
1052 printf(_(", requested address (%s) was %soffered"),inet_ntoa(requested_address),(received_requested_address==TRUE)?"":_("not "));
1054 printf(_(", max lease time = "));
1055 if(max_lease_time==DHCP_INFINITE_TIME)
1056 printf(_("Infinity"));
1057 else
1058 printf("%lu sec",(unsigned long)max_lease_time);
1060 printf(".\n");
1062 return result;
1066 /* process command-line arguments */
1067 int process_arguments(int argc, char **argv){
1068 int c;
1070 if(argc<1)
1071 return ERROR;
1073 c=0;
1074 while((c+=(call_getopt(argc-c,&argv[c])))<argc){
1077 if(is_option(argv[c]))
1078 continue;
1082 return validate_arguments();
1087 int call_getopt(int argc, char **argv){
1088 int c=0;
1089 int i=0;
1091 int option_index = 0;
1092 static struct option long_options[] =
1094 {"serverip", required_argument,0,'s'},
1095 {"requestedip", required_argument,0,'r'},
1096 {"timeout", required_argument,0,'t'},
1097 {"interface", required_argument,0,'i'},
1098 {"mac", required_argument,0,'m'},
1099 {"unicast", no_argument, 0,'u'},
1100 {"verbose", no_argument, 0,'v'},
1101 {"version", no_argument, 0,'V'},
1102 {"help", no_argument, 0,'h'},
1103 {0,0,0,0}
1106 while(1){
1107 c=getopt_long(argc,argv,"+hVvt:s:r:t:i:m:u",long_options,&option_index);
1109 i++;
1111 if(c==-1||c==EOF||c==1)
1112 break;
1114 switch(c){
1115 case 'w':
1116 case 'r':
1117 case 't':
1118 case 'i':
1119 i++;
1120 break;
1121 default:
1122 break;
1125 switch(c){
1127 case 's': /* DHCP server address */
1128 resolve_host(optarg,&dhcp_ip);
1129 add_requested_server(dhcp_ip);
1130 break;
1132 case 'r': /* address we are requested from DHCP servers */
1133 resolve_host(optarg,&requested_address);
1134 request_specific_address=TRUE;
1135 break;
1137 case 't': /* timeout */
1140 if(is_intnonneg(optarg))
1142 if(atoi(optarg)>0)
1143 dhcpoffer_timeout=atoi(optarg);
1145 else
1146 usage("Time interval must be a nonnegative integer\n");
1148 break;
1150 case 'm': /* MAC address */
1152 if((user_specified_mac=mac_aton(optarg)) == NULL)
1153 usage("Cannot parse MAC address.\n");
1154 if(verbose)
1155 print_hardware_address(user_specified_mac);
1157 break;
1159 case 'i': /* interface name */
1161 strncpy(network_interface_name,optarg,sizeof(network_interface_name)-1);
1162 network_interface_name[sizeof(network_interface_name)-1]='\x0';
1164 break;
1166 case 'u': /* unicast testing */
1167 unicast=1;
1168 break;
1170 case 'V': /* version */
1171 print_revision(progname,revision);
1172 exit(STATE_OK);
1174 case 'h': /* help */
1175 print_help();
1176 exit(STATE_OK);
1178 case 'v': /* verbose */
1179 verbose=1;
1180 break;
1182 case '?': /* help */
1183 usage5 ();
1184 break;
1186 default:
1187 break;
1191 return i;
1195 int validate_arguments(void){
1197 return OK;
1201 #if defined(__sun__) || defined(__solaris__) || defined(__hpux__)
1202 /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */
1204 /* get a message from a stream; return type of message */
1205 static int get_msg(int fd){
1206 int flags = 0;
1207 int res, ret;
1208 ctl_area[0] = 0;
1209 dat_area[0] = 0;
1210 ret = 0;
1211 res = getmsg(fd, &ctl, &dat, &flags);
1213 if(res < 0){
1214 if(errno == EINTR){
1215 return(GOT_INTR);
1217 else{
1218 printf("%s\n", "get_msg FAILED.");
1219 return(GOT_ERR);
1222 if(ctl.len > 0){
1223 ret |= GOT_CTRL;
1225 if(dat.len > 0){
1226 ret |= GOT_DATA;
1229 return(ret);
1232 /* verify that dl_primitive in ctl_area = prim */
1233 static int check_ctrl(int prim){
1234 dl_error_ack_t *err_ack = (dl_error_ack_t *)ctl_area;
1236 if(err_ack->dl_primitive != prim){
1237 printf(_("Error: DLPI stream API failed to get MAC in check_ctrl: %s.\n"), strerror(errno));
1238 exit(STATE_UNKNOWN);
1241 return 0;
1244 /* put a control message on a stream */
1245 static int put_ctrl(int fd, int len, int pri){
1247 ctl.len = len;
1248 if(putmsg(fd, &ctl, 0, pri) < 0){
1249 printf(_("Error: DLPI stream API failed to get MAC in put_ctrl/putmsg(): %s.\n"), strerror(errno));
1250 exit(STATE_UNKNOWN);
1253 return 0;
1256 /* put a control + data message on a stream */
1257 static int put_both(int fd, int clen, int dlen, int pri){
1259 ctl.len = clen;
1260 dat.len = dlen;
1261 if(putmsg(fd, &ctl, &dat, pri) < 0){
1262 printf(_("Error: DLPI stream API failed to get MAC in put_both/putmsg().\n"), strerror(errno));
1263 exit(STATE_UNKNOWN);
1266 return 0;
1269 /* open file descriptor and attach */
1270 static int dl_open(const char *dev, int unit, int *fd){
1271 dl_attach_req_t *attach_req = (dl_attach_req_t *)ctl_area;
1273 if((*fd = open(dev, O_RDWR)) == -1){
1274 printf(_("Error: DLPI stream API failed to get MAC in dl_attach_req/open(%s..): %s.\n"), dev, strerror(errno));
1275 exit(STATE_UNKNOWN);
1277 attach_req->dl_primitive = DL_ATTACH_REQ;
1278 attach_req->dl_ppa = unit;
1279 put_ctrl(*fd, sizeof(dl_attach_req_t), 0);
1280 get_msg(*fd);
1281 return check_ctrl(DL_OK_ACK);
1284 /* send DL_BIND_REQ */
1285 static int dl_bind(int fd, int sap, u_char *addr){
1286 dl_bind_req_t *bind_req = (dl_bind_req_t *)ctl_area;
1287 dl_bind_ack_t *bind_ack = (dl_bind_ack_t *)ctl_area;
1289 bind_req->dl_primitive = DL_BIND_REQ;
1290 bind_req->dl_sap = sap;
1291 bind_req->dl_max_conind = 1;
1292 bind_req->dl_service_mode = DL_CLDLS;
1293 bind_req->dl_conn_mgmt = 0;
1294 bind_req->dl_xidtest_flg = 0;
1295 put_ctrl(fd, sizeof(dl_bind_req_t), 0);
1296 get_msg(fd);
1297 if (GOT_ERR == check_ctrl(DL_BIND_ACK)){
1298 printf(_("Error: DLPI stream API failed to get MAC in dl_bind/check_ctrl(): %s.\n"), strerror(errno));
1299 exit(STATE_UNKNOWN);
1301 bcopy((u_char *)bind_ack + bind_ack->dl_addr_offset, addr,
1302 bind_ack->dl_addr_length);
1304 return 0;
1307 /***********************************************************************
1308 * interface:
1309 * function mac_addr_dlpi - get the mac address of the interface with
1310 * type dev (eg lnc, hme) and unit (0, 1 ..)
1312 * parameter: addr: an array of six bytes, has to be allocated by the caller
1314 * return: 0 if OK, -1 if the address could not be determined
1317 ***********************************************************************/
1319 long mac_addr_dlpi( const char *dev, int unit, u_char *addr){
1320 int fd;
1321 u_char mac_addr[25];
1323 if(GOT_ERR != dl_open(dev, unit, &fd)){
1324 if(GOT_ERR != dl_bind(fd, INSAP, mac_addr)){
1325 bcopy( mac_addr, addr, 6);
1326 return 0;
1329 close(fd);
1331 return -1;
1334 /* Kompf 2000-2003 */
1335 #endif
1338 /* resolve host name or die (TODO: move this to netutils.c!) */
1339 void resolve_host(const char *in,struct in_addr *out){
1340 struct addrinfo hints, *ai;
1342 memset(&hints,0,sizeof(hints));
1343 hints.ai_family=PF_INET;
1344 if (getaddrinfo(in,NULL,&hints,&ai) != 0)
1345 usage_va(_("Invalid hostname/address - %s"),optarg);
1347 memcpy(out,&((struct sockaddr_in *)ai->ai_addr)->sin_addr,sizeof(*out));
1348 freeaddrinfo(ai);
1352 /* parse MAC address string, return 6 bytes (unterminated) or NULL */
1353 unsigned char *mac_aton(const char *string){
1354 static unsigned char result[6];
1355 char tmp[3];
1356 unsigned i, j;
1358 for(i=0, j=0; string[i] != '\0' && j < sizeof(result); i++){
1359 /* ignore ':' and any other non-hex character */
1360 if(!isxdigit(string[i]) || !isxdigit(string[i+1]))
1361 continue;
1362 tmp[0]=string[i];
1363 tmp[1]=string[i+1];
1364 tmp[2]='\0';
1365 result[j]=strtol(tmp,(char **)NULL,16);
1366 i++;
1367 j++;
1370 return (j==6) ? result : NULL;
1374 void print_hardware_address(const unsigned char *address){
1375 int i;
1377 printf(_("Hardware address: "));
1378 for (i=0; i<5; i++)
1379 printf("%2.2x:", address[i]);
1380 printf("%2.2x", address[i]);
1381 putchar('\n');
1385 /* print usage help */
1386 void print_help(void){
1388 print_revision(progname,revision);
1390 printf("Copyright (c) 2001-2004 Ethan Galstad (nagios@nagios.org)\n");
1391 printf (COPYRIGHT, copyright, email);
1393 printf("%s\n", _("This plugin tests the availability of DHCP servers on a network."));
1395 printf ("\n\n");
1397 print_usage();
1399 printf (_(UT_HELP_VRSN));
1400 printf (_(UT_EXTRA_OPTS));
1402 printf (_(UT_VERBOSE));
1404 printf (" %s\n", "-s, --serverip=IPADDRESS");
1405 printf (" %s\n", _("IP address of DHCP server that we must hear from"));
1406 printf (" %s\n", "-r, --requestedip=IPADDRESS");
1407 printf (" %s\n", _("IP address that should be offered by at least one DHCP server"));
1408 printf (" %s\n", "-t, --timeout=INTEGER");
1409 printf (" %s\n", _("Seconds to wait for DHCPOFFER before timeout occurs"));
1410 printf (" %s\n", "-i, --interface=STRING");
1411 printf (" %s\n", _("Interface to to use for listening (i.e. eth0)"));
1412 printf (" %s\n", "-m, --mac=STRING");
1413 printf (" %s\n", _("MAC address to use in the DHCP request"));
1414 printf (" %s\n", "-u, --unicast");
1415 printf (" %s\n", _("Unicast testing: mimic a DHCP relay, requires -s"));
1417 #ifdef NP_EXTRA_OPTS
1418 printf ("\n");
1419 printf ("%s\n", _("Notes:"));
1420 printf (_(UT_EXTRA_OPTS_NOTES));
1421 #endif
1423 printf (_(UT_SUPPORT));
1424 return;
1428 void
1429 print_usage(void){
1431 printf (_("Usage:"));
1432 printf (" %s [-v] [-u] [-s serverip] [-r requestedip] [-t timeout]\n",progname);
1433 printf (" [-i interface] [-m mac]\n");
1435 return;