check_dhcp: Fix handling of "pad" options
[monitoring-plugins.git] / plugins-root / check_dhcp.c
blobac892747a85cb3a317ff4e30720db0f108d9e118
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 * Description:
11 * This file contains the check_dhcp plugin
13 * This plugin tests the availability of DHCP servers on a network.
15 * Unicast mode was originally implemented by Heiti of Boras Kommun with
16 * general improvements as well as usability fixes and "forward"-porting by
17 * Andreas Ericsson of OP5 AB.
20 * This program is free software: you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation, either version 3 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <http://www.gnu.org/licenses/>.
34 *****************************************************************************/
36 const char *progname = "check_dhcp";
37 const char *copyright = "2001-2007";
38 const char *email = "nagiosplug-devel@lists.sourceforge.net";
40 #include "common.h"
41 #include "netutils.h"
42 #include "utils.h"
44 #include <ctype.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <errno.h>
49 #include <unistd.h>
50 #include <sys/time.h>
51 #include <sys/ioctl.h>
52 #include <fcntl.h>
53 #include <getopt.h>
54 #include <sys/socket.h>
55 #include <sys/types.h>
56 #include <netdb.h>
57 #include <netinet/in.h>
58 #include <net/if.h>
59 #include <arpa/inet.h>
60 #if HAVE_SYS_SOCKIO_H
61 #include <sys/sockio.h>
62 #endif
64 #if defined( __linux__ )
66 #include <linux/if_ether.h>
67 #include <features.h>
69 #elif defined (__bsd__)
71 #include <netinet/if_ether.h>
72 #include <sys/param.h>
73 #include <sys/sysctl.h>
74 #include <net/if_dl.h>
76 #elif defined(__sun__) || defined(__solaris__) || defined(__hpux__)
78 #define INSAP 22
79 #define OUTSAP 24
81 #include <signal.h>
82 #include <ctype.h>
83 #include <sys/stropts.h>
84 #include <sys/poll.h>
85 #include <sys/dlpi.h>
87 #define bcopy(source, destination, length) memcpy(destination, source, length)
89 #define AREA_SZ 5000 /* buffer length in bytes */
90 static u_long ctl_area[AREA_SZ];
91 static u_long dat_area[AREA_SZ];
92 static struct strbuf ctl = {AREA_SZ, 0, (char *)ctl_area};
93 static struct strbuf dat = {AREA_SZ, 0, (char *)dat_area};
95 #define GOT_CTRL 1
96 #define GOT_DATA 2
97 #define GOT_BOTH 3
98 #define GOT_INTR 4
99 #define GOT_ERR 128
101 #define u_int8_t uint8_t
102 #define u_int16_t uint16_t
103 #define u_int32_t uint32_t
105 static int get_msg(int);
106 static int check_ctrl(int);
107 static int put_ctrl(int, int, int);
108 static int put_both(int, int, int, int);
109 static int dl_open(const char *, int, int *);
110 static int dl_bind(int, int, u_char *);
111 long mac_addr_dlpi( const char *, int, u_char *);
113 #endif
117 /**** Common definitions ****/
119 #define OK 0
120 #define ERROR -1
122 #define FALSE 0
123 #define TRUE 1
126 /**** DHCP definitions ****/
128 #define MAX_DHCP_CHADDR_LENGTH 16
129 #define MAX_DHCP_SNAME_LENGTH 64
130 #define MAX_DHCP_FILE_LENGTH 128
131 #define MAX_DHCP_OPTIONS_LENGTH 312
134 typedef struct dhcp_packet_struct{
135 u_int8_t op; /* packet type */
136 u_int8_t htype; /* type of hardware address for this machine (Ethernet, etc) */
137 u_int8_t hlen; /* length of hardware address (of this machine) */
138 u_int8_t hops; /* hops */
139 u_int32_t xid; /* random transaction id number - chosen by this machine */
140 u_int16_t secs; /* seconds used in timing */
141 u_int16_t flags; /* flags */
142 struct in_addr ciaddr; /* IP address of this machine (if we already have one) */
143 struct in_addr yiaddr; /* IP address of this machine (offered by the DHCP server) */
144 struct in_addr siaddr; /* IP address of DHCP server */
145 struct in_addr giaddr; /* IP address of DHCP relay */
146 unsigned char chaddr [MAX_DHCP_CHADDR_LENGTH]; /* hardware address of this machine */
147 char sname [MAX_DHCP_SNAME_LENGTH]; /* name of DHCP server */
148 char file [MAX_DHCP_FILE_LENGTH]; /* boot file name (used for diskless booting?) */
149 char options[MAX_DHCP_OPTIONS_LENGTH]; /* options */
150 }dhcp_packet;
153 typedef struct dhcp_offer_struct{
154 struct in_addr server_address; /* address of DHCP server that sent this offer */
155 struct in_addr offered_address; /* the IP address that was offered to us */
156 u_int32_t lease_time; /* lease time in seconds */
157 u_int32_t renewal_time; /* renewal time in seconds */
158 u_int32_t rebinding_time; /* rebinding time in seconds */
159 struct dhcp_offer_struct *next;
160 }dhcp_offer;
163 typedef struct requested_server_struct{
164 struct in_addr server_address;
165 int answered;
166 struct requested_server_struct *next;
167 }requested_server;
170 #define BOOTREQUEST 1
171 #define BOOTREPLY 2
173 #define DHCPDISCOVER 1
174 #define DHCPOFFER 2
175 #define DHCPREQUEST 3
176 #define DHCPDECLINE 4
177 #define DHCPACK 5
178 #define DHCPNACK 6
179 #define DHCPRELEASE 7
181 #define DHCP_OPTION_MESSAGE_TYPE 53
182 #define DHCP_OPTION_HOST_NAME 12
183 #define DHCP_OPTION_BROADCAST_ADDRESS 28
184 #define DHCP_OPTION_REQUESTED_ADDRESS 50
185 #define DHCP_OPTION_LEASE_TIME 51
186 #define DHCP_OPTION_SERVER_IDENTIFIER 54
187 #define DHCP_OPTION_RENEWAL_TIME 58
188 #define DHCP_OPTION_REBINDING_TIME 59
189 #define DHCP_OPTION_END 255
191 #define DHCP_INFINITE_TIME 0xFFFFFFFF
193 #define DHCP_BROADCAST_FLAG 32768
195 #define DHCP_SERVER_PORT 67
196 #define DHCP_CLIENT_PORT 68
198 #define ETHERNET_HARDWARE_ADDRESS 1 /* used in htype field of dhcp packet */
199 #define ETHERNET_HARDWARE_ADDRESS_LENGTH 6 /* length of Ethernet hardware addresses */
201 u_int8_t unicast = 0; /* unicast mode: mimic a DHCP relay */
202 struct in_addr my_ip; /* our address (required for relay) */
203 struct in_addr dhcp_ip; /* server to query (if in unicast mode) */
204 unsigned char client_hardware_address[MAX_DHCP_CHADDR_LENGTH]="";
205 unsigned char *user_specified_mac=NULL;
207 char network_interface_name[IFNAMSIZ]="eth0";
209 u_int32_t packet_xid=0;
211 u_int32_t dhcp_lease_time=0;
212 u_int32_t dhcp_renewal_time=0;
213 u_int32_t dhcp_rebinding_time=0;
215 int dhcpoffer_timeout=2;
217 dhcp_offer *dhcp_offer_list=NULL;
218 requested_server *requested_server_list=NULL;
220 int valid_responses=0; /* number of valid DHCPOFFERs we received */
221 int requested_servers=0;
222 int requested_responses=0;
224 int request_specific_address=FALSE;
225 int received_requested_address=FALSE;
226 int verbose=0;
227 struct in_addr requested_address;
230 int process_arguments(int, char **);
231 int call_getopt(int, char **);
232 int validate_arguments(void);
233 void print_usage(void);
234 void print_help(void);
236 void resolve_host(const char *in,struct in_addr *out);
237 unsigned char *mac_aton(const char *);
238 void print_hardware_address(const unsigned char *);
239 int get_hardware_address(int,char *);
240 int get_ip_address(int,char *);
242 int send_dhcp_discover(int);
243 int get_dhcp_offer(int);
245 int get_results(void);
247 int add_dhcp_offer(struct in_addr,dhcp_packet *);
248 int free_dhcp_offer_list(void);
249 int free_requested_server_list(void);
251 int create_dhcp_socket(void);
252 int close_dhcp_socket(int);
253 int send_dhcp_packet(void *,int,int,struct sockaddr_in *);
254 int receive_dhcp_packet(void *,int,int,int,struct sockaddr_in *);
258 int main(int argc, char **argv){
259 int dhcp_socket;
260 int result = STATE_UNKNOWN;
262 setlocale (LC_ALL, "");
263 bindtextdomain (PACKAGE, LOCALEDIR);
264 textdomain (PACKAGE);
266 /* Parse extra opts if any */
267 argv=np_extra_opts(&argc, argv, progname);
269 if(process_arguments(argc,argv)!=OK){
270 usage4 (_("Could not parse arguments"));
273 /* this plugin almost certainly needs root permissions. */
274 np_warn_if_not_root();
276 /* create socket for DHCP communications */
277 dhcp_socket=create_dhcp_socket();
279 /* get hardware address of client machine */
280 if(user_specified_mac!=NULL)
281 memcpy(client_hardware_address,user_specified_mac,6);
282 else
283 get_hardware_address(dhcp_socket,network_interface_name);
285 if(unicast) /* get IP address of client machine */
286 get_ip_address(dhcp_socket,network_interface_name);
288 /* send DHCPDISCOVER packet */
289 send_dhcp_discover(dhcp_socket);
291 /* wait for a DHCPOFFER packet */
292 get_dhcp_offer(dhcp_socket);
294 /* close socket we created */
295 close_dhcp_socket(dhcp_socket);
297 /* determine state/plugin output to return */
298 result=get_results();
300 /* free allocated memory */
301 free_dhcp_offer_list();
302 free_requested_server_list();
304 return result;
309 /* determines hardware address on client machine */
310 int get_hardware_address(int sock,char *interface_name){
312 #if defined(__linux__)
313 struct ifreq ifr;
315 strncpy((char *)&ifr.ifr_name,interface_name,sizeof(ifr.ifr_name)-1);
316 ifr.ifr_name[sizeof(ifr.ifr_name)-1]='\0';
318 /* try and grab hardware address of requested interface */
319 if(ioctl(sock,SIOCGIFHWADDR,&ifr)<0){
320 printf(_("Error: Could not get hardware address of interface '%s'\n"),interface_name);
321 exit(STATE_UNKNOWN);
324 memcpy(&client_hardware_address[0],&ifr.ifr_hwaddr.sa_data,6);
326 #elif defined(__bsd__)
327 /* King 2004 see ACKNOWLEDGEMENTS */
329 int mib[6], len;
330 char *buf;
331 unsigned char *ptr;
332 struct if_msghdr *ifm;
333 struct sockaddr_dl *sdl;
335 mib[0] = CTL_NET;
336 mib[1] = AF_ROUTE;
337 mib[2] = 0;
338 mib[3] = AF_LINK;
339 mib[4] = NET_RT_IFLIST;
341 if((mib[5] = if_nametoindex(interface_name)) == 0){
342 printf(_("Error: if_nametoindex error - %s.\n"), strerror(errno));
343 exit(STATE_UNKNOWN);
346 if(sysctl(mib, 6, NULL, &len, NULL, 0) < 0){
347 printf(_("Error: Couldn't get hardware address from %s. sysctl 1 error - %s.\n"), interface_name, strerror(errno));
348 exit(STATE_UNKNOWN);
351 if((buf = malloc(len)) == NULL){
352 printf(_("Error: Couldn't get hardware address from interface %s. malloc error - %s.\n"), interface_name, strerror(errno));
353 exit(4);
356 if(sysctl(mib, 6, buf, &len, NULL, 0) < 0){
357 printf(_("Error: Couldn't get hardware address from %s. sysctl 2 error - %s.\n"), interface_name, strerror(errno));
358 exit(STATE_UNKNOWN);
361 ifm = (struct if_msghdr *)buf;
362 sdl = (struct sockaddr_dl *)(ifm + 1);
363 ptr = (unsigned char *)LLADDR(sdl);
364 memcpy(&client_hardware_address[0], ptr, 6) ;
365 /* King 2004 */
367 #elif defined(__sun__) || defined(__solaris__)
369 /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */
370 long stat;
371 char dev[20] = "/dev/";
372 char *p;
373 int unit;
375 for(p = interface_name; *p && isalpha(*p); p++)
376 /* no-op */ ;
377 if( p != '\0' ){
378 unit = atoi(p) ;
379 *p = '\0' ;
380 strncat(dev, interface_name, 6) ;
382 else{
383 printf(_("Error: can't find unit number in interface_name (%s) - expecting TypeNumber eg lnc0.\n"), interface_name);
384 exit(STATE_UNKNOWN);
386 stat = mac_addr_dlpi(dev, unit, client_hardware_address);
387 if(stat != 0){
388 printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit);
389 exit(STATE_UNKNOWN);
392 #elif defined(__hpux__)
394 long stat;
395 char dev[20] = "/dev/dlpi" ;
396 int unit = 0;
398 stat = mac_addr_dlpi(dev, unit, client_hardware_address);
399 if(stat != 0){
400 printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit);
401 exit(STATE_UNKNOWN);
403 /* Kompf 2000-2003 */
405 #else
406 printf(_("Error: can't get MAC address for this architecture. Use the --mac option.\n"));
407 exit(STATE_UNKNOWN);
408 #endif
410 if(verbose)
411 print_hardware_address(client_hardware_address);
413 return OK;
416 /* determines IP address of the client interface */
417 int get_ip_address(int sock,char *interface_name){
418 #if defined(SIOCGIFADDR)
419 struct ifreq ifr;
421 strncpy((char *)&ifr.ifr_name,interface_name,sizeof(ifr.ifr_name)-1);
422 ifr.ifr_name[sizeof(ifr.ifr_name)-1]='\0';
424 if(ioctl(sock,SIOCGIFADDR,&ifr)<0){
425 printf(_("Error: Cannot determine IP address of interface %s\n"),
426 interface_name);
427 exit(STATE_UNKNOWN);
430 my_ip=((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
432 #else
433 printf(_("Error: Cannot get interface IP address on this platform.\n"));
434 exit(STATE_UNKNOWN);
435 #endif
437 if(verbose)
438 printf(_("Pretending to be relay client %s\n"),inet_ntoa(my_ip));
440 return OK;
443 /* sends a DHCPDISCOVER broadcast message in an attempt to find DHCP servers */
444 int send_dhcp_discover(int sock){
445 dhcp_packet discover_packet;
446 struct sockaddr_in sockaddr_broadcast;
447 unsigned short opts;
450 /* clear the packet data structure */
451 bzero(&discover_packet,sizeof(discover_packet));
454 /* boot request flag (backward compatible with BOOTP servers) */
455 discover_packet.op=BOOTREQUEST;
457 /* hardware address type */
458 discover_packet.htype=ETHERNET_HARDWARE_ADDRESS;
460 /* length of our hardware address */
461 discover_packet.hlen=ETHERNET_HARDWARE_ADDRESS_LENGTH;
464 * transaction ID is supposed to be random. We won't use the address so
465 * we don't care about high entropy here. time(2) is good enough.
467 srand(time(NULL));
468 packet_xid=random();
469 discover_packet.xid=htonl(packet_xid);
471 /**** WHAT THE HECK IS UP WITH THIS?!? IF I DON'T MAKE THIS CALL, ONLY ONE SERVER RESPONSE IS PROCESSED!!!! ****/
472 /* downright bizzarre... */
473 ntohl(discover_packet.xid);
475 /*discover_packet.secs=htons(65535);*/
476 discover_packet.secs=0xFF;
479 * server needs to know if it should broadcast or unicast its response:
480 * 0x8000L == 32768 == 1 << 15 == broadcast, 0 == unicast
482 discover_packet.flags = unicast ? 0 : htons(DHCP_BROADCAST_FLAG);
484 /* our hardware address */
485 memcpy(discover_packet.chaddr,client_hardware_address,ETHERNET_HARDWARE_ADDRESS_LENGTH);
487 /* first four bytes of options field is magic cookie (as per RFC 2132) */
488 discover_packet.options[0]='\x63';
489 discover_packet.options[1]='\x82';
490 discover_packet.options[2]='\x53';
491 discover_packet.options[3]='\x63';
493 opts = 4;
494 /* DHCP message type is embedded in options field */
495 discover_packet.options[opts++]=DHCP_OPTION_MESSAGE_TYPE; /* DHCP message type option identifier */
496 discover_packet.options[opts++]='\x01'; /* DHCP message option length in bytes */
497 discover_packet.options[opts++]=DHCPDISCOVER;
499 /* the IP address we're requesting */
500 if(request_specific_address==TRUE){
501 discover_packet.options[opts++]=DHCP_OPTION_REQUESTED_ADDRESS;
502 discover_packet.options[opts++]='\x04';
503 memcpy(&discover_packet.options[opts],&requested_address,sizeof(requested_address));
504 opts += sizeof(requested_address);
506 discover_packet.options[opts++]=DHCP_OPTION_END;
508 /* unicast fields */
509 if(unicast)
510 discover_packet.giaddr.s_addr = my_ip.s_addr;
512 /* see RFC 1542, 4.1.1 */
513 discover_packet.hops = unicast ? 1 : 0;
515 /* send the DHCPDISCOVER packet to broadcast address */
516 sockaddr_broadcast.sin_family=AF_INET;
517 sockaddr_broadcast.sin_port=htons(DHCP_SERVER_PORT);
518 sockaddr_broadcast.sin_addr.s_addr = unicast ? dhcp_ip.s_addr : INADDR_BROADCAST;
519 bzero(&sockaddr_broadcast.sin_zero,sizeof(sockaddr_broadcast.sin_zero));
522 if(verbose){
523 printf(_("DHCPDISCOVER to %s port %d\n"),inet_ntoa(sockaddr_broadcast.sin_addr),ntohs(sockaddr_broadcast.sin_port));
524 printf("DHCPDISCOVER XID: %u (0x%X)\n",ntohl(discover_packet.xid),ntohl(discover_packet.xid));
525 printf("DHCDISCOVER ciaddr: %s\n",inet_ntoa(discover_packet.ciaddr));
526 printf("DHCDISCOVER yiaddr: %s\n",inet_ntoa(discover_packet.yiaddr));
527 printf("DHCDISCOVER siaddr: %s\n",inet_ntoa(discover_packet.siaddr));
528 printf("DHCDISCOVER giaddr: %s\n",inet_ntoa(discover_packet.giaddr));
531 /* send the DHCPDISCOVER packet out */
532 send_dhcp_packet(&discover_packet,sizeof(discover_packet),sock,&sockaddr_broadcast);
534 if(verbose)
535 printf("\n\n");
537 return OK;
543 /* waits for a DHCPOFFER message from one or more DHCP servers */
544 int get_dhcp_offer(int sock){
545 dhcp_packet offer_packet;
546 struct sockaddr_in source;
547 struct sockaddr_in via;
548 int result=OK;
549 int responses=0;
550 int x;
551 time_t start_time;
552 time_t current_time;
554 time(&start_time);
556 /* receive as many responses as we can */
557 for(responses=0,valid_responses=0;;){
559 time(&current_time);
560 if((current_time-start_time)>=dhcpoffer_timeout)
561 break;
563 if(verbose)
564 printf("\n\n");
566 bzero(&source,sizeof(source));
567 bzero(&via,sizeof(via));
568 bzero(&offer_packet,sizeof(offer_packet));
570 result=OK;
571 result=receive_dhcp_packet(&offer_packet,sizeof(offer_packet),sock,dhcpoffer_timeout,&source);
573 if(result!=OK){
574 if(verbose)
575 printf(_("Result=ERROR\n"));
577 continue;
579 else{
580 if(verbose)
581 printf(_("Result=OK\n"));
583 responses++;
586 /* The "source" is either a server or a relay. */
587 /* Save a copy of "source" into "via" even if it's via itself */
588 memcpy(&via,&source,sizeof(source)) ;
590 /* If siaddr is non-zero, set "source" to siaddr */
591 if(offer_packet.siaddr.s_addr != 0L){
592 source.sin_addr.s_addr = offer_packet.siaddr.s_addr ;
595 if(verbose){
596 printf(_("DHCPOFFER from IP address %s"),inet_ntoa(source.sin_addr));
597 printf(_(" via %s\n"),inet_ntoa(via.sin_addr));
598 printf("DHCPOFFER XID: %u (0x%X)\n",ntohl(offer_packet.xid),ntohl(offer_packet.xid));
601 /* check packet xid to see if its the same as the one we used in the discover packet */
602 if(ntohl(offer_packet.xid)!=packet_xid){
603 if(verbose)
604 printf(_("DHCPOFFER XID (%u) did not match DHCPDISCOVER XID (%u) - ignoring packet\n"),ntohl(offer_packet.xid),packet_xid);
606 continue;
609 /* check hardware address */
610 result=OK;
611 if(verbose)
612 printf("DHCPOFFER chaddr: ");
614 for(x=0;x<ETHERNET_HARDWARE_ADDRESS_LENGTH;x++){
615 if(verbose)
616 printf("%02X",(unsigned char)offer_packet.chaddr[x]);
618 if(offer_packet.chaddr[x]!=client_hardware_address[x])
619 result=ERROR;
621 if(verbose)
622 printf("\n");
624 if(result==ERROR){
625 if(verbose)
626 printf(_("DHCPOFFER hardware address did not match our own - ignoring packet\n"));
628 continue;
631 if(verbose){
632 printf("DHCPOFFER ciaddr: %s\n",inet_ntoa(offer_packet.ciaddr));
633 printf("DHCPOFFER yiaddr: %s\n",inet_ntoa(offer_packet.yiaddr));
634 printf("DHCPOFFER siaddr: %s\n",inet_ntoa(offer_packet.siaddr));
635 printf("DHCPOFFER giaddr: %s\n",inet_ntoa(offer_packet.giaddr));
638 add_dhcp_offer(source.sin_addr,&offer_packet);
640 valid_responses++;
643 if(verbose){
644 printf(_("Total responses seen on the wire: %d\n"),responses);
645 printf(_("Valid responses for this machine: %d\n"),valid_responses);
648 return OK;
653 /* sends a DHCP packet */
654 int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in *dest){
655 int result;
657 result=sendto(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)dest,sizeof(*dest));
659 if(verbose)
660 printf(_("send_dhcp_packet result: %d\n"),result);
662 if(result<0)
663 return ERROR;
665 return OK;
670 /* receives a DHCP packet */
671 int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, struct sockaddr_in *address){
672 struct timeval tv;
673 fd_set readfds;
674 fd_set oobfds;
675 int recv_result;
676 socklen_t address_size;
677 struct sockaddr_in source_address;
678 int nfound;
681 /* wait for data to arrive (up time timeout) */
682 tv.tv_sec=timeout;
683 tv.tv_usec=0;
684 FD_ZERO(&readfds);
685 FD_ZERO(&oobfds);
686 FD_SET(sock,&readfds);
687 FD_SET(sock,&oobfds);
688 nfound = select(sock+1,&readfds,NULL,&oobfds,&tv);
690 /* make sure some data has arrived */
691 if(!FD_ISSET(sock,&readfds)){
692 if(verbose)
693 printf(_("No (more) data received (nfound: %d)\n"), nfound);
694 return ERROR;
697 else{
699 /* 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
700 not being interpreted correctly. sigh... */
701 bzero(&source_address,sizeof(source_address));
702 address_size=sizeof(source_address);
703 recv_result=recvfrom(sock,(char *)buffer,buffer_size,MSG_PEEK,(struct sockaddr *)&source_address,&address_size);
704 if(verbose)
705 printf("recv_result_1: %d\n",recv_result);
706 recv_result=recvfrom(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)&source_address,&address_size);
707 if(verbose)
708 printf("recv_result_2: %d\n",recv_result);
710 if(recv_result==-1){
711 if(verbose){
712 printf(_("recvfrom() failed, "));
713 printf("errno: (%d) -> %s\n",errno,strerror(errno));
715 return ERROR;
717 else{
718 if(verbose){
719 printf(_("receive_dhcp_packet() result: %d\n"),recv_result);
720 printf(_("receive_dhcp_packet() source: %s\n"),inet_ntoa(source_address.sin_addr));
723 memcpy(address,&source_address,sizeof(source_address));
724 return OK;
728 return OK;
732 /* creates a socket for DHCP communication */
733 int create_dhcp_socket(void){
734 struct sockaddr_in myname;
735 struct ifreq interface;
736 int sock;
737 int flag=1;
739 /* Set up the address we're going to bind to. */
740 bzero(&myname,sizeof(myname));
741 myname.sin_family=AF_INET;
742 /* listen to DHCP server port if we're in unicast mode */
743 myname.sin_port = htons(unicast ? DHCP_SERVER_PORT : DHCP_CLIENT_PORT);
744 myname.sin_addr.s_addr = unicast ? my_ip.s_addr : INADDR_ANY;
745 bzero(&myname.sin_zero,sizeof(myname.sin_zero));
747 /* create a socket for DHCP communications */
748 sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
749 if(sock<0){
750 printf(_("Error: Could not create socket!\n"));
751 exit(STATE_UNKNOWN);
754 if(verbose)
755 printf("DHCP socket: %d\n",sock);
757 /* set the reuse address flag so we don't get errors when restarting */
758 flag=1;
759 if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char *)&flag,sizeof(flag))<0){
760 printf(_("Error: Could not set reuse address option on DHCP socket!\n"));
761 exit(STATE_UNKNOWN);
764 /* set the broadcast option - we need this to listen to DHCP broadcast messages */
765 if(!unicast && setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char *)&flag,sizeof flag)<0){
766 printf(_("Error: Could not set broadcast option on DHCP socket!\n"));
767 exit(STATE_UNKNOWN);
770 /* bind socket to interface */
771 #if defined(__linux__)
772 strncpy(interface.ifr_ifrn.ifrn_name,network_interface_name,IFNAMSIZ-1);
773 interface.ifr_ifrn.ifrn_name[IFNAMSIZ-1]='\0';
774 if(setsockopt(sock,SOL_SOCKET,SO_BINDTODEVICE,(char *)&interface,sizeof(interface))<0){
775 printf(_("Error: Could not bind socket to interface %s. Check your privileges...\n"),network_interface_name);
776 exit(STATE_UNKNOWN);
779 #else
780 strncpy(interface.ifr_name,network_interface_name,IFNAMSIZ-1);
781 interface.ifr_name[IFNAMSIZ-1]='\0';
782 #endif
784 /* bind the socket */
785 if(bind(sock,(struct sockaddr *)&myname,sizeof(myname))<0){
786 printf(_("Error: Could not bind to DHCP socket (port %d)! Check your privileges...\n"),DHCP_CLIENT_PORT);
787 exit(STATE_UNKNOWN);
790 return sock;
794 /* closes DHCP socket */
795 int close_dhcp_socket(int sock){
797 close(sock);
799 return OK;
803 /* adds a requested server address to list in memory */
804 int add_requested_server(struct in_addr server_address){
805 requested_server *new_server;
807 new_server=(requested_server *)malloc(sizeof(requested_server));
808 if(new_server==NULL)
809 return ERROR;
811 new_server->server_address=server_address;
812 new_server->answered=FALSE;
814 new_server->next=requested_server_list;
815 requested_server_list=new_server;
817 requested_servers++;
819 if(verbose)
820 printf(_("Requested server address: %s\n"),inet_ntoa(new_server->server_address));
822 return OK;
828 /* adds a DHCP OFFER to list in memory */
829 int add_dhcp_offer(struct in_addr source,dhcp_packet *offer_packet){
830 dhcp_offer *new_offer;
831 int x;
832 unsigned option_type;
833 unsigned option_length;
834 struct in_addr serv_ident = {0};
836 if(offer_packet==NULL)
837 return ERROR;
839 /* process all DHCP options present in the packet */
840 for(x=4;x<MAX_DHCP_OPTIONS_LENGTH;){
842 if((int)offer_packet->options[x]==-1)
843 break;
845 /* get option type */
846 option_type=offer_packet->options[x++];
848 /* get option length */
849 option_length=offer_packet->options[x++];
851 if(verbose)
852 printf("Option: %d (0x%02X)\n",option_type,option_length);
854 /* get option data */
855 switch(option_type){
856 case DHCP_OPTION_LEASE_TIME:
857 memcpy(&dhcp_lease_time, &offer_packet->options[x],sizeof(dhcp_lease_time));
858 dhcp_lease_time = ntohl(dhcp_lease_time);
859 break;
860 case DHCP_OPTION_RENEWAL_TIME:
861 memcpy(&dhcp_renewal_time, &offer_packet->options[x],sizeof(dhcp_renewal_time));
862 dhcp_renewal_time = ntohl(dhcp_renewal_time);
863 break;
864 case DHCP_OPTION_REBINDING_TIME:
865 memcpy(&dhcp_rebinding_time, &offer_packet->options[x],sizeof(dhcp_rebinding_time));
866 dhcp_rebinding_time = ntohl(dhcp_rebinding_time);
867 break;
868 case DHCP_OPTION_SERVER_IDENTIFIER:
869 memcpy(&serv_ident.s_addr, &offer_packet->options[x],sizeof(serv_ident.s_addr));
870 break;
873 /* skip option data we're ignoring */
874 if(option_type==0) /* "pad" option, see RFC 2132 (3.1) */
875 x+=1;
876 else
877 x+=option_length;
880 if(verbose){
881 if(dhcp_lease_time==DHCP_INFINITE_TIME)
882 printf(_("Lease Time: Infinite\n"));
883 else
884 printf(_("Lease Time: %lu seconds\n"),(unsigned long)dhcp_lease_time);
885 if(dhcp_renewal_time==DHCP_INFINITE_TIME)
886 printf(_("Renewal Time: Infinite\n"));
887 else
888 printf(_("Renewal Time: %lu seconds\n"),(unsigned long)dhcp_renewal_time);
889 if(dhcp_rebinding_time==DHCP_INFINITE_TIME)
890 printf(_("Rebinding Time: Infinite\n"));
891 printf(_("Rebinding Time: %lu seconds\n"),(unsigned long)dhcp_rebinding_time);
894 new_offer=(dhcp_offer *)malloc(sizeof(dhcp_offer));
896 if(new_offer==NULL)
897 return ERROR;
900 * RFC 2131 (2.) says: "DHCP clarifies the interpretation of the
901 * 'siaddr' field as the address of the server to use in the next step
902 * of the client's bootstrap process. A DHCP server may return its own
903 * address in the 'siaddr' field, if the server is prepared to supply
904 * the next bootstrap service (e.g., delivery of an operating system
905 * executable image). A DHCP server always returns its own address in
906 * the 'server identifier' option." 'serv_ident' is the 'server
907 * identifier' option, 'source' is the 'siaddr' field or (if 'siaddr'
908 * wasn't available) the IP address we received the DHCPOFFER from. If
909 * 'serv_ident' isn't available for some reason, we use 'source'.
911 new_offer->server_address=serv_ident.s_addr?serv_ident:source;
912 new_offer->offered_address=offer_packet->yiaddr;
913 new_offer->lease_time=dhcp_lease_time;
914 new_offer->renewal_time=dhcp_renewal_time;
915 new_offer->rebinding_time=dhcp_rebinding_time;
918 if(verbose){
919 printf(_("Added offer from server @ %s"),inet_ntoa(new_offer->server_address));
920 printf(_(" of IP address %s\n"),inet_ntoa(new_offer->offered_address));
923 /* add new offer to head of list */
924 new_offer->next=dhcp_offer_list;
925 dhcp_offer_list=new_offer;
927 return OK;
931 /* frees memory allocated to DHCP OFFER list */
932 int free_dhcp_offer_list(void){
933 dhcp_offer *this_offer;
934 dhcp_offer *next_offer;
936 for(this_offer=dhcp_offer_list;this_offer!=NULL;this_offer=next_offer){
937 next_offer=this_offer->next;
938 free(this_offer);
941 return OK;
945 /* frees memory allocated to requested server list */
946 int free_requested_server_list(void){
947 requested_server *this_server;
948 requested_server *next_server;
950 for(this_server=requested_server_list;this_server!=NULL;this_server=next_server){
951 next_server=this_server->next;
952 free(this_server);
955 return OK;
959 /* gets state and plugin output to return */
960 int get_results(void){
961 dhcp_offer *temp_offer;
962 requested_server *temp_server;
963 int result;
964 u_int32_t max_lease_time=0;
966 received_requested_address=FALSE;
968 /* checks responses from requested servers */
969 requested_responses=0;
970 if(requested_servers>0){
972 for(temp_server=requested_server_list;temp_server!=NULL;temp_server=temp_server->next){
974 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
976 /* get max lease time we were offered */
977 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
978 max_lease_time=temp_offer->lease_time;
980 /* see if we got the address we requested */
981 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
982 received_requested_address=TRUE;
984 /* see if the servers we wanted a response from talked to us or not */
985 if(!memcmp(&temp_offer->server_address,&temp_server->server_address,sizeof(temp_server->server_address))){
986 if(verbose){
987 printf(_("DHCP Server Match: Offerer=%s"),inet_ntoa(temp_offer->server_address));
988 printf(_(" Requested=%s"),inet_ntoa(temp_server->server_address));
989 if(temp_server->answered)
990 printf(_(" (duplicate)"));
991 printf(_("\n"));
993 if(temp_server->answered == FALSE){
994 requested_responses++;
995 temp_server->answered=TRUE;
1003 /* else check and see if we got our requested address from any server */
1004 else{
1006 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
1008 /* get max lease time we were offered */
1009 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
1010 max_lease_time=temp_offer->lease_time;
1012 /* see if we got the address we requested */
1013 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
1014 received_requested_address=TRUE;
1018 result=STATE_OK;
1019 if(valid_responses==0)
1020 result=STATE_CRITICAL;
1021 else if(requested_servers>0 && requested_responses==0)
1022 result=STATE_CRITICAL;
1023 else if(requested_responses<requested_servers)
1024 result=STATE_WARNING;
1025 else if(request_specific_address==TRUE && received_requested_address==FALSE)
1026 result=STATE_WARNING;
1028 if(result==0) /* garrett honeycutt 2005 */
1029 printf("OK: ");
1030 else if(result==1)
1031 printf("WARNING: ");
1032 else if(result==2)
1033 printf("CRITICAL: ");
1034 else if(result==3)
1035 printf("UNKNOWN: ");
1037 /* we didn't receive any DHCPOFFERs */
1038 if(dhcp_offer_list==NULL){
1039 printf(_("No DHCPOFFERs were received.\n"));
1040 return result;
1043 printf(_("Received %d DHCPOFFER(s)"),valid_responses);
1045 if(requested_servers>0)
1046 printf(_(", %s%d of %d requested servers responded"),((requested_responses<requested_servers) && requested_responses>0)?"only ":"",requested_responses,requested_servers);
1048 if(request_specific_address==TRUE)
1049 printf(_(", requested address (%s) was %soffered"),inet_ntoa(requested_address),(received_requested_address==TRUE)?"":_("not "));
1051 printf(_(", max lease time = "));
1052 if(max_lease_time==DHCP_INFINITE_TIME)
1053 printf(_("Infinity"));
1054 else
1055 printf("%lu sec",(unsigned long)max_lease_time);
1057 printf(".\n");
1059 return result;
1063 /* process command-line arguments */
1064 int process_arguments(int argc, char **argv){
1065 int c;
1067 if(argc<1)
1068 return ERROR;
1070 c=0;
1071 while((c+=(call_getopt(argc-c,&argv[c])))<argc){
1074 if(is_option(argv[c]))
1075 continue;
1079 return validate_arguments();
1084 int call_getopt(int argc, char **argv){
1085 int c=0;
1086 int i=0;
1088 int option_index = 0;
1089 static struct option long_options[] =
1091 {"serverip", required_argument,0,'s'},
1092 {"requestedip", required_argument,0,'r'},
1093 {"timeout", required_argument,0,'t'},
1094 {"interface", required_argument,0,'i'},
1095 {"mac", required_argument,0,'m'},
1096 {"unicast", no_argument, 0,'u'},
1097 {"verbose", no_argument, 0,'v'},
1098 {"version", no_argument, 0,'V'},
1099 {"help", no_argument, 0,'h'},
1100 {0,0,0,0}
1103 while(1){
1104 c=getopt_long(argc,argv,"+hVvt:s:r:t:i:m:u",long_options,&option_index);
1106 i++;
1108 if(c==-1||c==EOF||c==1)
1109 break;
1111 switch(c){
1112 case 'w':
1113 case 'r':
1114 case 't':
1115 case 'i':
1116 i++;
1117 break;
1118 default:
1119 break;
1122 switch(c){
1124 case 's': /* DHCP server address */
1125 resolve_host(optarg,&dhcp_ip);
1126 add_requested_server(dhcp_ip);
1127 break;
1129 case 'r': /* address we are requested from DHCP servers */
1130 resolve_host(optarg,&requested_address);
1131 request_specific_address=TRUE;
1132 break;
1134 case 't': /* timeout */
1137 if(is_intnonneg(optarg))
1139 if(atoi(optarg)>0)
1140 dhcpoffer_timeout=atoi(optarg);
1142 else
1143 usage("Time interval must be a nonnegative integer\n");
1145 break;
1147 case 'm': /* MAC address */
1149 if((user_specified_mac=mac_aton(optarg)) == NULL)
1150 usage("Cannot parse MAC address.\n");
1151 if(verbose)
1152 print_hardware_address(user_specified_mac);
1154 break;
1156 case 'i': /* interface name */
1158 strncpy(network_interface_name,optarg,sizeof(network_interface_name)-1);
1159 network_interface_name[sizeof(network_interface_name)-1]='\x0';
1161 break;
1163 case 'u': /* unicast testing */
1164 unicast=1;
1165 break;
1167 case 'V': /* version */
1168 print_revision(progname, NP_VERSION);
1169 exit(STATE_OK);
1171 case 'h': /* help */
1172 print_help();
1173 exit(STATE_OK);
1175 case 'v': /* verbose */
1176 verbose=1;
1177 break;
1179 case '?': /* help */
1180 usage5 ();
1181 break;
1183 default:
1184 break;
1188 return i;
1192 int validate_arguments(void){
1194 return OK;
1198 #if defined(__sun__) || defined(__solaris__) || defined(__hpux__)
1199 /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */
1201 /* get a message from a stream; return type of message */
1202 static int get_msg(int fd){
1203 int flags = 0;
1204 int res, ret;
1205 ctl_area[0] = 0;
1206 dat_area[0] = 0;
1207 ret = 0;
1208 res = getmsg(fd, &ctl, &dat, &flags);
1210 if(res < 0){
1211 if(errno == EINTR){
1212 return(GOT_INTR);
1214 else{
1215 printf("%s\n", "get_msg FAILED.");
1216 return(GOT_ERR);
1219 if(ctl.len > 0){
1220 ret |= GOT_CTRL;
1222 if(dat.len > 0){
1223 ret |= GOT_DATA;
1226 return(ret);
1229 /* verify that dl_primitive in ctl_area = prim */
1230 static int check_ctrl(int prim){
1231 dl_error_ack_t *err_ack = (dl_error_ack_t *)ctl_area;
1233 if(err_ack->dl_primitive != prim){
1234 printf(_("Error: DLPI stream API failed to get MAC in check_ctrl: %s.\n"), strerror(errno));
1235 exit(STATE_UNKNOWN);
1238 return 0;
1241 /* put a control message on a stream */
1242 static int put_ctrl(int fd, int len, int pri){
1244 ctl.len = len;
1245 if(putmsg(fd, &ctl, 0, pri) < 0){
1246 printf(_("Error: DLPI stream API failed to get MAC in put_ctrl/putmsg(): %s.\n"), strerror(errno));
1247 exit(STATE_UNKNOWN);
1250 return 0;
1253 /* put a control + data message on a stream */
1254 static int put_both(int fd, int clen, int dlen, int pri){
1256 ctl.len = clen;
1257 dat.len = dlen;
1258 if(putmsg(fd, &ctl, &dat, pri) < 0){
1259 printf(_("Error: DLPI stream API failed to get MAC in put_both/putmsg().\n"), strerror(errno));
1260 exit(STATE_UNKNOWN);
1263 return 0;
1266 /* open file descriptor and attach */
1267 static int dl_open(const char *dev, int unit, int *fd){
1268 dl_attach_req_t *attach_req = (dl_attach_req_t *)ctl_area;
1270 if((*fd = open(dev, O_RDWR)) == -1){
1271 printf(_("Error: DLPI stream API failed to get MAC in dl_attach_req/open(%s..): %s.\n"), dev, strerror(errno));
1272 exit(STATE_UNKNOWN);
1274 attach_req->dl_primitive = DL_ATTACH_REQ;
1275 attach_req->dl_ppa = unit;
1276 put_ctrl(*fd, sizeof(dl_attach_req_t), 0);
1277 get_msg(*fd);
1278 return check_ctrl(DL_OK_ACK);
1281 /* send DL_BIND_REQ */
1282 static int dl_bind(int fd, int sap, u_char *addr){
1283 dl_bind_req_t *bind_req = (dl_bind_req_t *)ctl_area;
1284 dl_bind_ack_t *bind_ack = (dl_bind_ack_t *)ctl_area;
1286 bind_req->dl_primitive = DL_BIND_REQ;
1287 bind_req->dl_sap = sap;
1288 bind_req->dl_max_conind = 1;
1289 bind_req->dl_service_mode = DL_CLDLS;
1290 bind_req->dl_conn_mgmt = 0;
1291 bind_req->dl_xidtest_flg = 0;
1292 put_ctrl(fd, sizeof(dl_bind_req_t), 0);
1293 get_msg(fd);
1294 if (GOT_ERR == check_ctrl(DL_BIND_ACK)){
1295 printf(_("Error: DLPI stream API failed to get MAC in dl_bind/check_ctrl(): %s.\n"), strerror(errno));
1296 exit(STATE_UNKNOWN);
1298 bcopy((u_char *)bind_ack + bind_ack->dl_addr_offset, addr,
1299 bind_ack->dl_addr_length);
1301 return 0;
1304 /***********************************************************************
1305 * interface:
1306 * function mac_addr_dlpi - get the mac address of the interface with
1307 * type dev (eg lnc, hme) and unit (0, 1 ..)
1309 * parameter: addr: an array of six bytes, has to be allocated by the caller
1311 * return: 0 if OK, -1 if the address could not be determined
1314 ***********************************************************************/
1316 long mac_addr_dlpi( const char *dev, int unit, u_char *addr){
1317 int fd;
1318 u_char mac_addr[25];
1320 if(GOT_ERR != dl_open(dev, unit, &fd)){
1321 if(GOT_ERR != dl_bind(fd, INSAP, mac_addr)){
1322 bcopy( mac_addr, addr, 6);
1323 return 0;
1326 close(fd);
1328 return -1;
1331 /* Kompf 2000-2003 */
1332 #endif
1335 /* resolve host name or die (TODO: move this to netutils.c!) */
1336 void resolve_host(const char *in,struct in_addr *out){
1337 struct addrinfo hints, *ai;
1339 memset(&hints,0,sizeof(hints));
1340 hints.ai_family=PF_INET;
1341 if (getaddrinfo(in,NULL,&hints,&ai) != 0)
1342 usage_va(_("Invalid hostname/address - %s"),optarg);
1344 memcpy(out,&((struct sockaddr_in *)ai->ai_addr)->sin_addr,sizeof(*out));
1345 freeaddrinfo(ai);
1349 /* parse MAC address string, return 6 bytes (unterminated) or NULL */
1350 unsigned char *mac_aton(const char *string){
1351 static unsigned char result[6];
1352 char tmp[3];
1353 unsigned i, j;
1355 for(i=0, j=0; string[i] != '\0' && j < sizeof(result); i++){
1356 /* ignore ':' and any other non-hex character */
1357 if(!isxdigit(string[i]) || !isxdigit(string[i+1]))
1358 continue;
1359 tmp[0]=string[i];
1360 tmp[1]=string[i+1];
1361 tmp[2]='\0';
1362 result[j]=strtol(tmp,(char **)NULL,16);
1363 i++;
1364 j++;
1367 return (j==6) ? result : NULL;
1371 void print_hardware_address(const unsigned char *address){
1372 int i;
1374 printf(_("Hardware address: "));
1375 for (i=0; i<5; i++)
1376 printf("%2.2x:", address[i]);
1377 printf("%2.2x", address[i]);
1378 putchar('\n');
1382 /* print usage help */
1383 void print_help(void){
1385 print_revision(progname, NP_VERSION);
1387 printf("Copyright (c) 2001-2004 Ethan Galstad (nagios@nagios.org)\n");
1388 printf (COPYRIGHT, copyright, email);
1390 printf("%s\n", _("This plugin tests the availability of DHCP servers on a network."));
1392 printf ("\n\n");
1394 print_usage();
1396 printf (UT_HELP_VRSN);
1397 printf (UT_EXTRA_OPTS);
1399 printf (UT_VERBOSE);
1401 printf (" %s\n", "-s, --serverip=IPADDRESS");
1402 printf (" %s\n", _("IP address of DHCP server that we must hear from"));
1403 printf (" %s\n", "-r, --requestedip=IPADDRESS");
1404 printf (" %s\n", _("IP address that should be offered by at least one DHCP server"));
1405 printf (" %s\n", "-t, --timeout=INTEGER");
1406 printf (" %s\n", _("Seconds to wait for DHCPOFFER before timeout occurs"));
1407 printf (" %s\n", "-i, --interface=STRING");
1408 printf (" %s\n", _("Interface to to use for listening (i.e. eth0)"));
1409 printf (" %s\n", "-m, --mac=STRING");
1410 printf (" %s\n", _("MAC address to use in the DHCP request"));
1411 printf (" %s\n", "-u, --unicast");
1412 printf (" %s\n", _("Unicast testing: mimic a DHCP relay, requires -s"));
1414 printf (UT_SUPPORT);
1415 return;
1419 void
1420 print_usage(void){
1422 printf ("%s\n", _("Usage:"));
1423 printf (" %s [-v] [-u] [-s serverip] [-r requestedip] [-t timeout]\n",progname);
1424 printf (" [-i interface] [-m mac]\n");
1426 return;