1.4.15 prep
[monitoring-plugins.git] / plugins-root / check_dhcp.c
blob2a1875c405431048c3099a5ec8834ffd72599dcd
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 /* end of options (0 is really just a pad, but bail out anyway) */
843 if((int)offer_packet->options[x]==-1 || (int)offer_packet->options[x]==0)
844 break;
846 /* get option type */
847 option_type=offer_packet->options[x++];
849 /* get option length */
850 option_length=offer_packet->options[x++];
852 if(verbose)
853 printf("Option: %d (0x%02X)\n",option_type,option_length);
855 /* get option data */
856 switch(option_type){
857 case DHCP_OPTION_LEASE_TIME:
858 memcpy(&dhcp_lease_time, &offer_packet->options[x],sizeof(dhcp_lease_time));
859 dhcp_lease_time = ntohl(dhcp_lease_time);
860 break;
861 case DHCP_OPTION_RENEWAL_TIME:
862 memcpy(&dhcp_renewal_time, &offer_packet->options[x],sizeof(dhcp_renewal_time));
863 dhcp_renewal_time = ntohl(dhcp_renewal_time);
864 break;
865 case DHCP_OPTION_REBINDING_TIME:
866 memcpy(&dhcp_rebinding_time, &offer_packet->options[x],sizeof(dhcp_rebinding_time));
867 dhcp_rebinding_time = ntohl(dhcp_rebinding_time);
868 break;
869 case DHCP_OPTION_SERVER_IDENTIFIER:
870 memcpy(&serv_ident.s_addr, &offer_packet->options[x],sizeof(serv_ident.s_addr));
871 break;
874 /* skip option data we're ignoring */
875 if(option_type!=DHCP_OPTION_REBINDING_TIME)
876 x+=option_length;
879 if(verbose){
880 if(dhcp_lease_time==DHCP_INFINITE_TIME)
881 printf(_("Lease Time: Infinite\n"));
882 else
883 printf(_("Lease Time: %lu seconds\n"),(unsigned long)dhcp_lease_time);
884 if(dhcp_renewal_time==DHCP_INFINITE_TIME)
885 printf(_("Renewal Time: Infinite\n"));
886 else
887 printf(_("Renewal Time: %lu seconds\n"),(unsigned long)dhcp_renewal_time);
888 if(dhcp_rebinding_time==DHCP_INFINITE_TIME)
889 printf(_("Rebinding Time: Infinite\n"));
890 printf(_("Rebinding Time: %lu seconds\n"),(unsigned long)dhcp_rebinding_time);
893 new_offer=(dhcp_offer *)malloc(sizeof(dhcp_offer));
895 if(new_offer==NULL)
896 return ERROR;
899 * RFC 2131 (2.) says: "DHCP clarifies the interpretation of the
900 * 'siaddr' field as the address of the server to use in the next step
901 * of the client's bootstrap process. A DHCP server may return its own
902 * address in the 'siaddr' field, if the server is prepared to supply
903 * the next bootstrap service (e.g., delivery of an operating system
904 * executable image). A DHCP server always returns its own address in
905 * the 'server identifier' option." 'serv_ident' is the 'server
906 * identifier' option, 'source' is the 'siaddr' field or (if 'siaddr'
907 * wasn't available) the IP address we received the DHCPOFFER from. If
908 * 'serv_ident' isn't available for some reason, we use 'source'.
910 new_offer->server_address=serv_ident.s_addr?serv_ident:source;
911 new_offer->offered_address=offer_packet->yiaddr;
912 new_offer->lease_time=dhcp_lease_time;
913 new_offer->renewal_time=dhcp_renewal_time;
914 new_offer->rebinding_time=dhcp_rebinding_time;
917 if(verbose){
918 printf(_("Added offer from server @ %s"),inet_ntoa(new_offer->server_address));
919 printf(_(" of IP address %s\n"),inet_ntoa(new_offer->offered_address));
922 /* add new offer to head of list */
923 new_offer->next=dhcp_offer_list;
924 dhcp_offer_list=new_offer;
926 return OK;
930 /* frees memory allocated to DHCP OFFER list */
931 int free_dhcp_offer_list(void){
932 dhcp_offer *this_offer;
933 dhcp_offer *next_offer;
935 for(this_offer=dhcp_offer_list;this_offer!=NULL;this_offer=next_offer){
936 next_offer=this_offer->next;
937 free(this_offer);
940 return OK;
944 /* frees memory allocated to requested server list */
945 int free_requested_server_list(void){
946 requested_server *this_server;
947 requested_server *next_server;
949 for(this_server=requested_server_list;this_server!=NULL;this_server=next_server){
950 next_server=this_server->next;
951 free(this_server);
954 return OK;
958 /* gets state and plugin output to return */
959 int get_results(void){
960 dhcp_offer *temp_offer;
961 requested_server *temp_server;
962 int result;
963 u_int32_t max_lease_time=0;
965 received_requested_address=FALSE;
967 /* checks responses from requested servers */
968 requested_responses=0;
969 if(requested_servers>0){
971 for(temp_server=requested_server_list;temp_server!=NULL;temp_server=temp_server->next){
973 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
975 /* get max lease time we were offered */
976 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
977 max_lease_time=temp_offer->lease_time;
979 /* see if we got the address we requested */
980 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
981 received_requested_address=TRUE;
983 /* see if the servers we wanted a response from talked to us or not */
984 if(!memcmp(&temp_offer->server_address,&temp_server->server_address,sizeof(temp_server->server_address))){
985 if(verbose){
986 printf(_("DHCP Server Match: Offerer=%s"),inet_ntoa(temp_offer->server_address));
987 printf(_(" Requested=%s"),inet_ntoa(temp_server->server_address));
988 if(temp_server->answered)
989 printf(_(" (duplicate)"));
990 printf(_("\n"));
992 if(temp_server->answered == FALSE){
993 requested_responses++;
994 temp_server->answered=TRUE;
1002 /* else check and see if we got our requested address from any server */
1003 else{
1005 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
1007 /* get max lease time we were offered */
1008 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
1009 max_lease_time=temp_offer->lease_time;
1011 /* see if we got the address we requested */
1012 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
1013 received_requested_address=TRUE;
1017 result=STATE_OK;
1018 if(valid_responses==0)
1019 result=STATE_CRITICAL;
1020 else if(requested_servers>0 && requested_responses==0)
1021 result=STATE_CRITICAL;
1022 else if(requested_responses<requested_servers)
1023 result=STATE_WARNING;
1024 else if(request_specific_address==TRUE && received_requested_address==FALSE)
1025 result=STATE_WARNING;
1027 if(result==0) /* garrett honeycutt 2005 */
1028 printf("OK: ");
1029 else if(result==1)
1030 printf("WARNING: ");
1031 else if(result==2)
1032 printf("CRITICAL: ");
1033 else if(result==3)
1034 printf("UNKNOWN: ");
1036 /* we didn't receive any DHCPOFFERs */
1037 if(dhcp_offer_list==NULL){
1038 printf(_("No DHCPOFFERs were received.\n"));
1039 return result;
1042 printf(_("Received %d DHCPOFFER(s)"),valid_responses);
1044 if(requested_servers>0)
1045 printf(_(", %s%d of %d requested servers responded"),((requested_responses<requested_servers) && requested_responses>0)?"only ":"",requested_responses,requested_servers);
1047 if(request_specific_address==TRUE)
1048 printf(_(", requested address (%s) was %soffered"),inet_ntoa(requested_address),(received_requested_address==TRUE)?"":_("not "));
1050 printf(_(", max lease time = "));
1051 if(max_lease_time==DHCP_INFINITE_TIME)
1052 printf(_("Infinity"));
1053 else
1054 printf("%lu sec",(unsigned long)max_lease_time);
1056 printf(".\n");
1058 return result;
1062 /* process command-line arguments */
1063 int process_arguments(int argc, char **argv){
1064 int c;
1066 if(argc<1)
1067 return ERROR;
1069 c=0;
1070 while((c+=(call_getopt(argc-c,&argv[c])))<argc){
1073 if(is_option(argv[c]))
1074 continue;
1078 return validate_arguments();
1083 int call_getopt(int argc, char **argv){
1084 int c=0;
1085 int i=0;
1087 int option_index = 0;
1088 static struct option long_options[] =
1090 {"serverip", required_argument,0,'s'},
1091 {"requestedip", required_argument,0,'r'},
1092 {"timeout", required_argument,0,'t'},
1093 {"interface", required_argument,0,'i'},
1094 {"mac", required_argument,0,'m'},
1095 {"unicast", no_argument, 0,'u'},
1096 {"verbose", no_argument, 0,'v'},
1097 {"version", no_argument, 0,'V'},
1098 {"help", no_argument, 0,'h'},
1099 {0,0,0,0}
1102 while(1){
1103 c=getopt_long(argc,argv,"+hVvt:s:r:t:i:m:u",long_options,&option_index);
1105 i++;
1107 if(c==-1||c==EOF||c==1)
1108 break;
1110 switch(c){
1111 case 'w':
1112 case 'r':
1113 case 't':
1114 case 'i':
1115 i++;
1116 break;
1117 default:
1118 break;
1121 switch(c){
1123 case 's': /* DHCP server address */
1124 resolve_host(optarg,&dhcp_ip);
1125 add_requested_server(dhcp_ip);
1126 break;
1128 case 'r': /* address we are requested from DHCP servers */
1129 resolve_host(optarg,&requested_address);
1130 request_specific_address=TRUE;
1131 break;
1133 case 't': /* timeout */
1136 if(is_intnonneg(optarg))
1138 if(atoi(optarg)>0)
1139 dhcpoffer_timeout=atoi(optarg);
1141 else
1142 usage("Time interval must be a nonnegative integer\n");
1144 break;
1146 case 'm': /* MAC address */
1148 if((user_specified_mac=mac_aton(optarg)) == NULL)
1149 usage("Cannot parse MAC address.\n");
1150 if(verbose)
1151 print_hardware_address(user_specified_mac);
1153 break;
1155 case 'i': /* interface name */
1157 strncpy(network_interface_name,optarg,sizeof(network_interface_name)-1);
1158 network_interface_name[sizeof(network_interface_name)-1]='\x0';
1160 break;
1162 case 'u': /* unicast testing */
1163 unicast=1;
1164 break;
1166 case 'V': /* version */
1167 print_revision(progname, NP_VERSION);
1168 exit(STATE_OK);
1170 case 'h': /* help */
1171 print_help();
1172 exit(STATE_OK);
1174 case 'v': /* verbose */
1175 verbose=1;
1176 break;
1178 case '?': /* help */
1179 usage5 ();
1180 break;
1182 default:
1183 break;
1187 return i;
1191 int validate_arguments(void){
1193 return OK;
1197 #if defined(__sun__) || defined(__solaris__) || defined(__hpux__)
1198 /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */
1200 /* get a message from a stream; return type of message */
1201 static int get_msg(int fd){
1202 int flags = 0;
1203 int res, ret;
1204 ctl_area[0] = 0;
1205 dat_area[0] = 0;
1206 ret = 0;
1207 res = getmsg(fd, &ctl, &dat, &flags);
1209 if(res < 0){
1210 if(errno == EINTR){
1211 return(GOT_INTR);
1213 else{
1214 printf("%s\n", "get_msg FAILED.");
1215 return(GOT_ERR);
1218 if(ctl.len > 0){
1219 ret |= GOT_CTRL;
1221 if(dat.len > 0){
1222 ret |= GOT_DATA;
1225 return(ret);
1228 /* verify that dl_primitive in ctl_area = prim */
1229 static int check_ctrl(int prim){
1230 dl_error_ack_t *err_ack = (dl_error_ack_t *)ctl_area;
1232 if(err_ack->dl_primitive != prim){
1233 printf(_("Error: DLPI stream API failed to get MAC in check_ctrl: %s.\n"), strerror(errno));
1234 exit(STATE_UNKNOWN);
1237 return 0;
1240 /* put a control message on a stream */
1241 static int put_ctrl(int fd, int len, int pri){
1243 ctl.len = len;
1244 if(putmsg(fd, &ctl, 0, pri) < 0){
1245 printf(_("Error: DLPI stream API failed to get MAC in put_ctrl/putmsg(): %s.\n"), strerror(errno));
1246 exit(STATE_UNKNOWN);
1249 return 0;
1252 /* put a control + data message on a stream */
1253 static int put_both(int fd, int clen, int dlen, int pri){
1255 ctl.len = clen;
1256 dat.len = dlen;
1257 if(putmsg(fd, &ctl, &dat, pri) < 0){
1258 printf(_("Error: DLPI stream API failed to get MAC in put_both/putmsg().\n"), strerror(errno));
1259 exit(STATE_UNKNOWN);
1262 return 0;
1265 /* open file descriptor and attach */
1266 static int dl_open(const char *dev, int unit, int *fd){
1267 dl_attach_req_t *attach_req = (dl_attach_req_t *)ctl_area;
1269 if((*fd = open(dev, O_RDWR)) == -1){
1270 printf(_("Error: DLPI stream API failed to get MAC in dl_attach_req/open(%s..): %s.\n"), dev, strerror(errno));
1271 exit(STATE_UNKNOWN);
1273 attach_req->dl_primitive = DL_ATTACH_REQ;
1274 attach_req->dl_ppa = unit;
1275 put_ctrl(*fd, sizeof(dl_attach_req_t), 0);
1276 get_msg(*fd);
1277 return check_ctrl(DL_OK_ACK);
1280 /* send DL_BIND_REQ */
1281 static int dl_bind(int fd, int sap, u_char *addr){
1282 dl_bind_req_t *bind_req = (dl_bind_req_t *)ctl_area;
1283 dl_bind_ack_t *bind_ack = (dl_bind_ack_t *)ctl_area;
1285 bind_req->dl_primitive = DL_BIND_REQ;
1286 bind_req->dl_sap = sap;
1287 bind_req->dl_max_conind = 1;
1288 bind_req->dl_service_mode = DL_CLDLS;
1289 bind_req->dl_conn_mgmt = 0;
1290 bind_req->dl_xidtest_flg = 0;
1291 put_ctrl(fd, sizeof(dl_bind_req_t), 0);
1292 get_msg(fd);
1293 if (GOT_ERR == check_ctrl(DL_BIND_ACK)){
1294 printf(_("Error: DLPI stream API failed to get MAC in dl_bind/check_ctrl(): %s.\n"), strerror(errno));
1295 exit(STATE_UNKNOWN);
1297 bcopy((u_char *)bind_ack + bind_ack->dl_addr_offset, addr,
1298 bind_ack->dl_addr_length);
1300 return 0;
1303 /***********************************************************************
1304 * interface:
1305 * function mac_addr_dlpi - get the mac address of the interface with
1306 * type dev (eg lnc, hme) and unit (0, 1 ..)
1308 * parameter: addr: an array of six bytes, has to be allocated by the caller
1310 * return: 0 if OK, -1 if the address could not be determined
1313 ***********************************************************************/
1315 long mac_addr_dlpi( const char *dev, int unit, u_char *addr){
1316 int fd;
1317 u_char mac_addr[25];
1319 if(GOT_ERR != dl_open(dev, unit, &fd)){
1320 if(GOT_ERR != dl_bind(fd, INSAP, mac_addr)){
1321 bcopy( mac_addr, addr, 6);
1322 return 0;
1325 close(fd);
1327 return -1;
1330 /* Kompf 2000-2003 */
1331 #endif
1334 /* resolve host name or die (TODO: move this to netutils.c!) */
1335 void resolve_host(const char *in,struct in_addr *out){
1336 struct addrinfo hints, *ai;
1338 memset(&hints,0,sizeof(hints));
1339 hints.ai_family=PF_INET;
1340 if (getaddrinfo(in,NULL,&hints,&ai) != 0)
1341 usage_va(_("Invalid hostname/address - %s"),optarg);
1343 memcpy(out,&((struct sockaddr_in *)ai->ai_addr)->sin_addr,sizeof(*out));
1344 freeaddrinfo(ai);
1348 /* parse MAC address string, return 6 bytes (unterminated) or NULL */
1349 unsigned char *mac_aton(const char *string){
1350 static unsigned char result[6];
1351 char tmp[3];
1352 unsigned i, j;
1354 for(i=0, j=0; string[i] != '\0' && j < sizeof(result); i++){
1355 /* ignore ':' and any other non-hex character */
1356 if(!isxdigit(string[i]) || !isxdigit(string[i+1]))
1357 continue;
1358 tmp[0]=string[i];
1359 tmp[1]=string[i+1];
1360 tmp[2]='\0';
1361 result[j]=strtol(tmp,(char **)NULL,16);
1362 i++;
1363 j++;
1366 return (j==6) ? result : NULL;
1370 void print_hardware_address(const unsigned char *address){
1371 int i;
1373 printf(_("Hardware address: "));
1374 for (i=0; i<5; i++)
1375 printf("%2.2x:", address[i]);
1376 printf("%2.2x", address[i]);
1377 putchar('\n');
1381 /* print usage help */
1382 void print_help(void){
1384 print_revision(progname, NP_VERSION);
1386 printf("Copyright (c) 2001-2004 Ethan Galstad (nagios@nagios.org)\n");
1387 printf (COPYRIGHT, copyright, email);
1389 printf("%s\n", _("This plugin tests the availability of DHCP servers on a network."));
1391 printf ("\n\n");
1393 print_usage();
1395 printf (UT_HELP_VRSN);
1396 printf (UT_EXTRA_OPTS);
1398 printf (UT_VERBOSE);
1400 printf (" %s\n", "-s, --serverip=IPADDRESS");
1401 printf (" %s\n", _("IP address of DHCP server that we must hear from"));
1402 printf (" %s\n", "-r, --requestedip=IPADDRESS");
1403 printf (" %s\n", _("IP address that should be offered by at least one DHCP server"));
1404 printf (" %s\n", "-t, --timeout=INTEGER");
1405 printf (" %s\n", _("Seconds to wait for DHCPOFFER before timeout occurs"));
1406 printf (" %s\n", "-i, --interface=STRING");
1407 printf (" %s\n", _("Interface to to use for listening (i.e. eth0)"));
1408 printf (" %s\n", "-m, --mac=STRING");
1409 printf (" %s\n", _("MAC address to use in the DHCP request"));
1410 printf (" %s\n", "-u, --unicast");
1411 printf (" %s\n", _("Unicast testing: mimic a DHCP relay, requires -s"));
1413 printf (UT_SUPPORT);
1414 return;
1418 void
1419 print_usage(void){
1421 printf ("%s\n", _("Usage:"));
1422 printf (" %s [-v] [-u] [-s serverip] [-r requestedip] [-t timeout]\n",progname);
1423 printf (" [-i interface] [-m mac]\n");
1425 return;