a1d04c18e79522edf615ee3673f3b07137b0a0c8
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-2006 Nagios Plugin Development Team
8 *
9 * Last Modified: $Date$
10 *
11 * Description:
12 *
13 * This file contains the check_dhcp plugin
14 *
15 * This plugin tests the availability of DHCP servers on a network.
16 *
17 *
18 * License Information:
19 *
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 2 of the License, or
23 * (at your option) any later version.
24 *
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.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33 *
34 * $Id$
35 *
36 * ------------------------------------------------------------------------
37 * Unicast mode was originally implemented by Heiti of Boras Kommun with
38 * general improvements as well as usability fixes and "forward"-porting by
39 * Andreas Ericsson of OP5 AB.
40 * ------------------------------------------------------------------------
41 *
42 *****************************************************************************/
44 const char *progname = "check_dhcp";
45 const char *revision = "$Revision$";
46 const char *copyright = "2001-2006";
47 const char *email = "nagiosplug-devel@lists.sourceforge.net";
49 #include "common.h"
50 #include "netutils.h"
51 #include "utils.h"
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <errno.h>
57 #include <unistd.h>
58 #include <sys/time.h>
59 #include <sys/ioctl.h>
60 #include <fcntl.h>
61 #include <getopt.h>
62 #include <sys/socket.h>
63 #include <sys/types.h>
64 #include <netdb.h>
65 #include <netinet/in.h>
66 #include <net/if.h>
67 #include <arpa/inet.h>
68 #if HAVE_SYS_SOCKIO_H
69 #include <sys/sockio.h>
70 #endif
72 #if defined( __linux__ )
74 #include <linux/if_ether.h>
75 #include <features.h>
77 #elif defined (__bsd__)
79 #include <netinet/if_ether.h>
80 #include <sys/param.h>
81 #include <sys/sysctl.h>
82 #include <net/if_dl.h>
84 #elif defined(__sun__) || defined(__solaris__) || defined(__hpux__)
86 #define INSAP 22
87 #define OUTSAP 24
89 #include <signal.h>
90 #include <ctype.h>
91 #include <sys/stropts.h>
92 #include <sys/poll.h>
93 #include <sys/dlpi.h>
95 #define bcopy(source, destination, length) memcpy(destination, source, length)
97 #define AREA_SZ 5000 /* buffer length in bytes */
98 static u_long ctl_area[AREA_SZ];
99 static u_long dat_area[AREA_SZ];
100 static struct strbuf ctl = {AREA_SZ, 0, (char *)ctl_area};
101 static struct strbuf dat = {AREA_SZ, 0, (char *)dat_area};
103 #define GOT_CTRL 1
104 #define GOT_DATA 2
105 #define GOT_BOTH 3
106 #define GOT_INTR 4
107 #define GOT_ERR 128
109 #define u_int8_t uint8_t
110 #define u_int16_t uint16_t
111 #define u_int32_t uint32_t
113 static int get_msg(int);
114 static int check_ctrl(int);
115 static int put_ctrl(int, int, int);
116 static int put_both(int, int, int, int);
117 static int dl_open(const char *, int, int *);
118 static int dl_bind(int, int, u_char *);
119 long mac_addr_dlpi( const char *, int, u_char *);
121 #endif
125 /**** Common definitions ****/
127 #define OK 0
128 #define ERROR -1
130 #define FALSE 0
131 #define TRUE 1
134 /**** DHCP definitions ****/
136 #define MAX_DHCP_CHADDR_LENGTH 16
137 #define MAX_DHCP_SNAME_LENGTH 64
138 #define MAX_DHCP_FILE_LENGTH 128
139 #define MAX_DHCP_OPTIONS_LENGTH 312
142 typedef struct dhcp_packet_struct{
143 u_int8_t op; /* packet type */
144 u_int8_t htype; /* type of hardware address for this machine (Ethernet, etc) */
145 u_int8_t hlen; /* length of hardware address (of this machine) */
146 u_int8_t hops; /* hops */
147 u_int32_t xid; /* random transaction id number - chosen by this machine */
148 u_int16_t secs; /* seconds used in timing */
149 u_int16_t flags; /* flags */
150 struct in_addr ciaddr; /* IP address of this machine (if we already have one) */
151 struct in_addr yiaddr; /* IP address of this machine (offered by the DHCP server) */
152 struct in_addr siaddr; /* IP address of DHCP server */
153 struct in_addr giaddr; /* IP address of DHCP relay */
154 unsigned char chaddr [MAX_DHCP_CHADDR_LENGTH]; /* hardware address of this machine */
155 char sname [MAX_DHCP_SNAME_LENGTH]; /* name of DHCP server */
156 char file [MAX_DHCP_FILE_LENGTH]; /* boot file name (used for diskless booting?) */
157 char options[MAX_DHCP_OPTIONS_LENGTH]; /* options */
158 }dhcp_packet;
161 typedef struct dhcp_offer_struct{
162 struct in_addr server_address; /* address of DHCP server that sent this offer */
163 struct in_addr offered_address; /* the IP address that was offered to us */
164 u_int32_t lease_time; /* lease time in seconds */
165 u_int32_t renewal_time; /* renewal time in seconds */
166 u_int32_t rebinding_time; /* rebinding time in seconds */
167 struct dhcp_offer_struct *next;
168 }dhcp_offer;
171 typedef struct requested_server_struct{
172 struct in_addr server_address;
173 int answered;
174 struct requested_server_struct *next;
175 }requested_server;
178 #define BOOTREQUEST 1
179 #define BOOTREPLY 2
181 #define DHCPDISCOVER 1
182 #define DHCPOFFER 2
183 #define DHCPREQUEST 3
184 #define DHCPDECLINE 4
185 #define DHCPACK 5
186 #define DHCPNACK 6
187 #define DHCPRELEASE 7
189 #define DHCP_OPTION_MESSAGE_TYPE 53
190 #define DHCP_OPTION_HOST_NAME 12
191 #define DHCP_OPTION_BROADCAST_ADDRESS 28
192 #define DHCP_OPTION_REQUESTED_ADDRESS 50
193 #define DHCP_OPTION_LEASE_TIME 51
194 #define DHCP_OPTION_SERVER_IDENTIFIER 54
195 #define DHCP_OPTION_RENEWAL_TIME 58
196 #define DHCP_OPTION_REBINDING_TIME 59
197 #define DHCP_OPTION_END 255
199 #define DHCP_INFINITE_TIME 0xFFFFFFFF
201 #define DHCP_BROADCAST_FLAG 32768
202 #define DHCP_UNICAST_FLAG 0
204 #define DHCP_SERVER_PORT 67
205 #define DHCP_CLIENT_PORT 68
207 #define ETHERNET_HARDWARE_ADDRESS 1 /* used in htype field of dhcp packet */
208 #define ETHERNET_HARDWARE_ADDRESS_LENGTH 6 /* length of Ethernet hardware addresses */
210 u_int8_t unicast = 0; /* unicast mode: mimic a DHCP relay */
211 struct in_addr my_ip; /* our address (required for relay) */
212 struct in_addr dhcp_ip; /* server to query (if in unicast mode) */
213 unsigned char client_hardware_address[MAX_DHCP_CHADDR_LENGTH]="";
215 char network_interface_name[IFNAMSIZ]="eth0";
217 u_int32_t packet_xid=0;
219 u_int32_t dhcp_lease_time=0;
220 u_int32_t dhcp_renewal_time=0;
221 u_int32_t dhcp_rebinding_time=0;
223 int dhcpoffer_timeout=2;
225 dhcp_offer *dhcp_offer_list=NULL;
226 requested_server *requested_server_list=NULL;
228 int valid_responses=0; /* number of valid DHCPOFFERs we received */
229 int requested_servers=0;
230 int requested_responses=0;
232 int request_specific_address=FALSE;
233 int received_requested_address=FALSE;
234 int verbose=0;
235 struct in_addr requested_address;
238 int process_arguments(int, char **);
239 int call_getopt(int, char **);
240 int validate_arguments(void);
241 void print_usage(void);
242 void print_help(void);
244 int get_hardware_address(int,char *);
245 int get_ip_address(int,char *);
247 int send_dhcp_discover(int);
248 int get_dhcp_offer(int);
250 int get_results(void);
252 int add_dhcp_offer(struct in_addr,dhcp_packet *);
253 int free_dhcp_offer_list(void);
254 int free_requested_server_list(void);
256 int create_dhcp_socket(void);
257 int close_dhcp_socket(int);
258 int send_dhcp_packet(void *,int,int,struct sockaddr_in *);
259 int receive_dhcp_packet(void *,int,int,int,struct sockaddr_in *);
263 int main(int argc, char **argv){
264 int dhcp_socket;
265 int result = STATE_UNKNOWN;
267 /* this plugin almost certainly needs root permissions. */
268 np_warn_if_not_root();
270 setlocale (LC_ALL, "");
271 bindtextdomain (PACKAGE, LOCALEDIR);
272 textdomain (PACKAGE);
274 if(process_arguments(argc,argv)!=OK){
275 usage4 (_("Could not parse arguments"));
276 }
278 /* create socket for DHCP communications */
279 dhcp_socket=create_dhcp_socket();
281 /* get hardware address of client machine */
282 get_hardware_address(dhcp_socket,network_interface_name);
284 if(unicast) /* get IP address of client machine */
285 get_ip_address(dhcp_socket,network_interface_name);
287 /* send DHCPDISCOVER packet */
288 send_dhcp_discover(dhcp_socket);
290 /* wait for a DHCPOFFER packet */
291 get_dhcp_offer(dhcp_socket);
293 /* close socket we created */
294 close_dhcp_socket(dhcp_socket);
296 /* determine state/plugin output to return */
297 result=get_results();
299 /* free allocated memory */
300 free_dhcp_offer_list();
301 free_requested_server_list();
303 return result;
304 }
308 /* determines hardware address on client machine */
309 int get_hardware_address(int sock,char *interface_name){
311 int i;
313 #if defined(__linux__)
314 struct ifreq ifr;
316 strncpy((char *)&ifr.ifr_name,interface_name,sizeof(ifr.ifr_name));
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);
322 }
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);
344 }
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);
349 }
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);
354 }
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);
359 }
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) ;
381 }
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);
385 }
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);
390 }
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);
402 }
403 /* Kompf 2000-2003 */
405 #else
406 printf(_("Error: can't get MAC address for this architecture.\n"));
407 exit(STATE_UNKNOWN);
408 #endif
410 if(verbose){
411 printf(_("Hardware address: "));
412 for (i=0; i<6; ++i)
413 printf("%2.2x", client_hardware_address[i]);
414 printf( "\n");
415 }
417 return OK;
418 }
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);
432 }
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;
445 }
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;
467 /* transaction id is supposed to be random */
468 srand(time(NULL));
469 packet_xid=random();
470 discover_packet.xid=htonl(packet_xid);
472 /**** WHAT THE HECK IS UP WITH THIS?!? IF I DON'T MAKE THIS CALL, ONLY ONE SERVER RESPONSE IS PROCESSED!!!! ****/
473 /* downright bizzarre... */
474 ntohl(discover_packet.xid);
476 /*discover_packet.secs=htons(65535);*/
477 discover_packet.secs=0xFF;
479 /*
480 * server needs to know if it should broadcast or unicast its response:
481 * 0x8000L == 32768 == 1 << 15 == broadcast, 0 == unicast
482 */
483 discover_packet.flags = unicast ? 0 : htons(DHCP_BROADCAST_FLAG);
485 /* our hardware address */
486 memcpy(discover_packet.chaddr,client_hardware_address,ETHERNET_HARDWARE_ADDRESS_LENGTH);
488 /* first four bytes of options field is magic cookie (as per RFC 2132) */
489 discover_packet.options[0]='\x63';
490 discover_packet.options[1]='\x82';
491 discover_packet.options[2]='\x53';
492 discover_packet.options[3]='\x63';
494 opts = 4;
495 /* DHCP message type is embedded in options field */
496 discover_packet.options[opts++]=DHCP_OPTION_MESSAGE_TYPE; /* DHCP message type option identifier */
497 discover_packet.options[opts++]='\x01'; /* DHCP message option length in bytes */
498 discover_packet.options[opts++]=DHCPDISCOVER;
500 /* the IP address we're requesting */
501 if(request_specific_address==TRUE){
502 discover_packet.options[opts++]=DHCP_OPTION_REQUESTED_ADDRESS;
503 discover_packet.options[opts++]='\x04';
504 memcpy(&discover_packet.options[opts],&requested_address,sizeof(requested_address));
505 opts += sizeof(requested_address);
506 }
507 discover_packet.options[opts++]=DHCP_OPTION_END;
509 /* unicast fields */
510 if(unicast)
511 discover_packet.giaddr.s_addr = my_ip.s_addr;
513 /* see RFC 1542, 4.1.1 */
514 discover_packet.hops = unicast ? 1 : 0;
516 /* send the DHCPDISCOVER packet to broadcast address */
517 sockaddr_broadcast.sin_family=AF_INET;
518 sockaddr_broadcast.sin_port=htons(DHCP_SERVER_PORT);
519 sockaddr_broadcast.sin_addr.s_addr = unicast ? dhcp_ip.s_addr : INADDR_BROADCAST;
520 bzero(&sockaddr_broadcast.sin_zero,sizeof(sockaddr_broadcast.sin_zero));
523 if(verbose){
524 printf(_("DHCPDISCOVER to %s port %d\n"),inet_ntoa(sockaddr_broadcast.sin_addr),ntohs(sockaddr_broadcast.sin_port));
525 printf("DHCPDISCOVER XID: %lu (0x%X)\n",ntohl(discover_packet.xid),ntohl(discover_packet.xid));
526 printf("DHCDISCOVER ciaddr: %s\n",inet_ntoa(discover_packet.ciaddr));
527 printf("DHCDISCOVER yiaddr: %s\n",inet_ntoa(discover_packet.yiaddr));
528 printf("DHCDISCOVER siaddr: %s\n",inet_ntoa(discover_packet.siaddr));
529 printf("DHCDISCOVER giaddr: %s\n",inet_ntoa(discover_packet.giaddr));
530 }
532 /* send the DHCPDISCOVER packet out */
533 send_dhcp_packet(&discover_packet,sizeof(discover_packet),sock,&sockaddr_broadcast);
535 if(verbose)
536 printf("\n\n");
538 return OK;
539 }
544 /* waits for a DHCPOFFER message from one or more DHCP servers */
545 int get_dhcp_offer(int sock){
546 dhcp_packet offer_packet;
547 struct sockaddr_in source;
548 struct sockaddr_in via;
549 int result=OK;
550 int responses=0;
551 int x;
552 time_t start_time;
553 time_t current_time;
555 time(&start_time);
557 /* receive as many responses as we can */
558 for(responses=0,valid_responses=0;;){
560 time(¤t_time);
561 if((current_time-start_time)>=dhcpoffer_timeout)
562 break;
564 if(verbose)
565 printf("\n\n");
567 bzero(&source,sizeof(source));
568 bzero(&via,sizeof(via));
569 bzero(&offer_packet,sizeof(offer_packet));
571 result=OK;
572 result=receive_dhcp_packet(&offer_packet,sizeof(offer_packet),sock,dhcpoffer_timeout,&source);
574 if(result!=OK){
575 if(verbose)
576 printf(_("Result=ERROR\n"));
578 continue;
579 }
580 else{
581 if(verbose)
582 printf(_("Result=OK\n"));
584 responses++;
585 }
587 /* The "source" is either a server or a relay. */
588 /* Save a copy of "source" into "via" even if it's via itself */
589 memcpy(&via,&source,sizeof(source)) ;
591 /* If siaddr is non-zero, set "source" to siaddr */
592 if(offer_packet.siaddr.s_addr != 0L){
593 source.sin_addr.s_addr = offer_packet.siaddr.s_addr ;
594 }
596 if(verbose){
597 printf(_("DHCPOFFER from IP address %s"),inet_ntoa(source.sin_addr));
598 printf(_(" via %s\n"),inet_ntoa(via.sin_addr));
599 printf("DHCPOFFER XID: %lu (0x%X)\n",ntohl(offer_packet.xid),ntohl(offer_packet.xid));
600 }
602 /* check packet xid to see if its the same as the one we used in the discover packet */
603 if(ntohl(offer_packet.xid)!=packet_xid){
604 if(verbose)
605 printf(_("DHCPOFFER XID (%lu) did not match DHCPDISCOVER XID (%lu) - ignoring packet\n"),ntohl(offer_packet.xid),packet_xid);
607 continue;
608 }
610 /* check hardware address */
611 result=OK;
612 if(verbose)
613 printf("DHCPOFFER chaddr: ");
615 for(x=0;x<ETHERNET_HARDWARE_ADDRESS_LENGTH;x++){
616 if(verbose)
617 printf("%02X",(unsigned char)offer_packet.chaddr[x]);
619 if(offer_packet.chaddr[x]!=client_hardware_address[x])
620 result=ERROR;
621 }
622 if(verbose)
623 printf("\n");
625 if(result==ERROR){
626 if(verbose)
627 printf(_("DHCPOFFER hardware address did not match our own - ignoring packet\n"));
629 continue;
630 }
632 if(verbose){
633 printf("DHCPOFFER ciaddr: %s\n",inet_ntoa(offer_packet.ciaddr));
634 printf("DHCPOFFER yiaddr: %s\n",inet_ntoa(offer_packet.yiaddr));
635 printf("DHCPOFFER siaddr: %s\n",inet_ntoa(offer_packet.siaddr));
636 printf("DHCPOFFER giaddr: %s\n",inet_ntoa(offer_packet.giaddr));
637 }
639 add_dhcp_offer(source.sin_addr,&offer_packet);
641 valid_responses++;
642 }
644 if(verbose){
645 printf(_("Total responses seen on the wire: %d\n"),responses);
646 printf(_("Valid responses for this machine: %d\n"),valid_responses);
647 }
649 return OK;
650 }
654 /* sends a DHCP packet */
655 int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in *dest){
656 int result;
658 result=sendto(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)dest,sizeof(*dest));
660 if(verbose)
661 printf(_("send_dhcp_packet result: %d\n"),result);
663 if(result<0)
664 return ERROR;
666 return OK;
667 }
671 /* receives a DHCP packet */
672 int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, struct sockaddr_in *address){
673 struct timeval tv;
674 fd_set readfds;
675 int recv_result;
676 socklen_t address_size;
677 struct sockaddr_in source_address;
680 /* wait for data to arrive (up time timeout) */
681 tv.tv_sec=timeout;
682 tv.tv_usec=0;
683 FD_ZERO(&readfds);
684 FD_SET(sock,&readfds);
685 select(sock+1,&readfds,NULL,NULL,&tv);
687 /* make sure some data has arrived */
688 if(!FD_ISSET(sock,&readfds)){
689 if(verbose)
690 printf(_("No (more) data received\n"));
691 return ERROR;
692 }
694 else{
696 /* 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
697 not being interpreted correctly. sigh... */
698 bzero(&source_address,sizeof(source_address));
699 address_size=sizeof(source_address);
700 recv_result=recvfrom(sock,(char *)buffer,buffer_size,MSG_PEEK,(struct sockaddr *)&source_address,&address_size);
701 if(verbose)
702 printf("recv_result_1: %d\n",recv_result);
703 recv_result=recvfrom(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)&source_address,&address_size);
704 if(verbose)
705 printf("recv_result_2: %d\n",recv_result);
707 if(recv_result==-1){
708 if(verbose){
709 printf(_("recvfrom() failed, "));
710 printf("errno: (%d) -> %s\n",errno,strerror(errno));
711 }
712 return ERROR;
713 }
714 else{
715 if(verbose){
716 printf(_("receive_dhcp_packet() result: %d\n"),recv_result);
717 printf(_("receive_dhcp_packet() source: %s\n"),inet_ntoa(source_address.sin_addr));
718 }
720 memcpy(address,&source_address,sizeof(source_address));
721 return OK;
722 }
723 }
725 return OK;
726 }
729 /* creates a socket for DHCP communication */
730 int create_dhcp_socket(void){
731 struct sockaddr_in myname;
732 struct ifreq interface;
733 int sock;
734 int flag=1;
736 /* Set up the address we're going to bind to. */
737 bzero(&myname,sizeof(myname));
738 myname.sin_family=AF_INET;
739 /* listen to DHCP server port if we're in unicast mode */
740 myname.sin_port = htons(unicast ? DHCP_SERVER_PORT : DHCP_CLIENT_PORT);
741 myname.sin_addr.s_addr = unicast ? my_ip.s_addr : INADDR_ANY;
742 bzero(&myname.sin_zero,sizeof(myname.sin_zero));
744 /* create a socket for DHCP communications */
745 sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
746 if(sock<0){
747 printf(_("Error: Could not create socket!\n"));
748 exit(STATE_UNKNOWN);
749 }
751 if(verbose)
752 printf("DHCP socket: %d\n",sock);
754 /* set the reuse address flag so we don't get errors when restarting */
755 flag=1;
756 if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char *)&flag,sizeof(flag))<0){
757 printf(_("Error: Could not set reuse address option on DHCP socket!\n"));
758 exit(STATE_UNKNOWN);
759 }
761 /* set the broadcast option - we need this to listen to DHCP broadcast messages */
762 if(setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char *)&flag,sizeof flag)<0){
763 printf(_("Error: Could not set broadcast option on DHCP socket!\n"));
764 exit(STATE_UNKNOWN);
765 }
767 /* bind socket to interface */
768 #if defined(__linux__)
769 strncpy(interface.ifr_ifrn.ifrn_name,network_interface_name,IFNAMSIZ);
770 if(setsockopt(sock,SOL_SOCKET,SO_BINDTODEVICE,(char *)&interface,sizeof(interface))<0){
771 printf(_("Error: Could not bind socket to interface %s. Check your privileges...\n"),network_interface_name);
772 exit(STATE_UNKNOWN);
773 }
775 #else
776 strncpy(interface.ifr_name,network_interface_name,IFNAMSIZ);
777 #endif
779 /* bind the socket */
780 if(bind(sock,(struct sockaddr *)&myname,sizeof(myname))<0){
781 printf(_("Error: Could not bind to DHCP socket (port %d)! Check your privileges...\n"),DHCP_CLIENT_PORT);
782 exit(STATE_UNKNOWN);
783 }
785 return sock;
786 }
789 /* closes DHCP socket */
790 int close_dhcp_socket(int sock){
792 close(sock);
794 return OK;
795 }
798 /* adds a requested server address to list in memory */
799 int add_requested_server(struct in_addr server_address){
800 requested_server *new_server;
802 new_server=(requested_server *)malloc(sizeof(requested_server));
803 if(new_server==NULL)
804 return ERROR;
806 new_server->server_address=server_address;
807 new_server->answered=FALSE;
809 new_server->next=requested_server_list;
810 requested_server_list=new_server;
812 requested_servers++;
814 if(verbose)
815 printf(_("Requested server address: %s\n"),inet_ntoa(new_server->server_address));
817 return OK;
818 }
823 /* adds a DHCP OFFER to list in memory */
824 int add_dhcp_offer(struct in_addr source,dhcp_packet *offer_packet){
825 dhcp_offer *new_offer;
826 int x;
827 unsigned option_type;
828 unsigned option_length;
829 struct in_addr serv_ident = {0};
831 if(offer_packet==NULL)
832 return ERROR;
834 /* process all DHCP options present in the packet */
835 for(x=4;x<MAX_DHCP_OPTIONS_LENGTH;){
837 /* end of options (0 is really just a pad, but bail out anyway) */
838 if((int)offer_packet->options[x]==-1 || (int)offer_packet->options[x]==0)
839 break;
841 /* get option type */
842 option_type=offer_packet->options[x++];
844 /* get option length */
845 option_length=offer_packet->options[x++];
847 if(verbose)
848 printf("Option: %d (0x%02X)\n",option_type,option_length);
850 /* get option data */
851 switch(option_type){
852 case DHCP_OPTION_LEASE_TIME:
853 memcpy(&dhcp_lease_time, &offer_packet->options[x],sizeof(dhcp_lease_time));
854 dhcp_lease_time = ntohl(dhcp_lease_time);
855 break;
856 case DHCP_OPTION_RENEWAL_TIME:
857 memcpy(&dhcp_renewal_time, &offer_packet->options[x],sizeof(dhcp_renewal_time));
858 dhcp_renewal_time = ntohl(dhcp_renewal_time);
859 break;
860 case DHCP_OPTION_REBINDING_TIME:
861 memcpy(&dhcp_rebinding_time, &offer_packet->options[x],sizeof(dhcp_rebinding_time));
862 dhcp_rebinding_time = ntohl(dhcp_rebinding_time);
863 break;
864 case DHCP_OPTION_SERVER_IDENTIFIER:
865 memcpy(&serv_ident.s_addr, &offer_packet->options[x],sizeof(serv_ident.s_addr));
866 break;
867 }
869 /* skip option data we're ignoring */
870 if(option_type!=DHCP_OPTION_REBINDING_TIME)
871 x+=option_length;
872 }
874 if(verbose){
875 if(dhcp_lease_time==DHCP_INFINITE_TIME)
876 printf(_("Lease Time: Infinite\n"));
877 else
878 printf(_("Lease Time: %lu seconds\n"),(unsigned long)dhcp_lease_time);
879 if(dhcp_renewal_time==DHCP_INFINITE_TIME)
880 printf(_("Renewal Time: Infinite\n"));
881 else
882 printf(_("Renewal Time: %lu seconds\n"),(unsigned long)dhcp_renewal_time);
883 if(dhcp_rebinding_time==DHCP_INFINITE_TIME)
884 printf(_("Rebinding Time: Infinite\n"));
885 printf(_("Rebinding Time: %lu seconds\n"),(unsigned long)dhcp_rebinding_time);
886 }
888 new_offer=(dhcp_offer *)malloc(sizeof(dhcp_offer));
890 if(new_offer==NULL)
891 return ERROR;
893 /*
894 * RFC 2131 (2.) says: "DHCP clarifies the interpretation of the
895 * 'siaddr' field as the address of the server to use in the next step
896 * of the client's bootstrap process. A DHCP server may return its own
897 * address in the 'siaddr' field, if the server is prepared to supply
898 * the next bootstrap service (e.g., delivery of an operating system
899 * executable image). A DHCP server always returns its own address in
900 * the 'server identifier' option." 'serv_ident' is the 'server
901 * identifier' option, 'source' is the 'siaddr' field or (if 'siaddr'
902 * wasn't available) the IP address we received the DHCPOFFER from. If
903 * 'serv_ident' isn't available for some reason, we use 'source'.
904 */
905 new_offer->server_address=serv_ident.s_addr?serv_ident:source;
906 new_offer->offered_address=offer_packet->yiaddr;
907 new_offer->lease_time=dhcp_lease_time;
908 new_offer->renewal_time=dhcp_renewal_time;
909 new_offer->rebinding_time=dhcp_rebinding_time;
912 if(verbose){
913 printf(_("Added offer from server @ %s"),inet_ntoa(new_offer->server_address));
914 printf(_(" of IP address %s\n"),inet_ntoa(new_offer->offered_address));
915 }
917 /* add new offer to head of list */
918 new_offer->next=dhcp_offer_list;
919 dhcp_offer_list=new_offer;
921 return OK;
922 }
925 /* frees memory allocated to DHCP OFFER list */
926 int free_dhcp_offer_list(void){
927 dhcp_offer *this_offer;
928 dhcp_offer *next_offer;
930 for(this_offer=dhcp_offer_list;this_offer!=NULL;this_offer=next_offer){
931 next_offer=this_offer->next;
932 free(this_offer);
933 }
935 return OK;
936 }
939 /* frees memory allocated to requested server list */
940 int free_requested_server_list(void){
941 requested_server *this_server;
942 requested_server *next_server;
944 for(this_server=requested_server_list;this_server!=NULL;this_server=next_server){
945 next_server=this_server->next;
946 free(this_server);
947 }
949 return OK;
950 }
953 /* gets state and plugin output to return */
954 int get_results(void){
955 dhcp_offer *temp_offer;
956 requested_server *temp_server;
957 int result;
958 u_int32_t max_lease_time=0;
960 received_requested_address=FALSE;
962 /* checks responses from requested servers */
963 requested_responses=0;
964 if(requested_servers>0){
966 for(temp_server=requested_server_list;temp_server!=NULL;temp_server=temp_server->next){
968 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
970 /* get max lease time we were offered */
971 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
972 max_lease_time=temp_offer->lease_time;
974 /* see if we got the address we requested */
975 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
976 received_requested_address=TRUE;
978 /* see if the servers we wanted a response from talked to us or not */
979 if(!memcmp(&temp_offer->server_address,&temp_server->server_address,sizeof(temp_server->server_address))){
980 if(verbose){
981 printf(_("DHCP Server Match: Offerer=%s"),inet_ntoa(temp_offer->server_address));
982 printf(_(" Requested=%s"),inet_ntoa(temp_server->server_address));
983 if(temp_server->answered)
984 printf(_(" (duplicate)"));
985 printf(_("\n"));
986 }
987 if(temp_server->answered == FALSE){
988 requested_responses++;
989 temp_server->answered=TRUE;
990 }
991 }
992 }
993 }
995 }
997 /* else check and see if we got our requested address from any server */
998 else{
1000 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
1002 /* get max lease time we were offered */
1003 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
1004 max_lease_time=temp_offer->lease_time;
1006 /* see if we got the address we requested */
1007 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
1008 received_requested_address=TRUE;
1009 }
1010 }
1012 result=STATE_OK;
1013 if(valid_responses==0)
1014 result=STATE_CRITICAL;
1015 else if(requested_servers>0 && requested_responses==0)
1016 result=STATE_CRITICAL;
1017 else if(requested_responses<requested_servers)
1018 result=STATE_WARNING;
1019 else if(request_specific_address==TRUE && received_requested_address==FALSE)
1020 result=STATE_WARNING;
1022 if(result==0) /* garrett honeycutt 2005 */
1023 printf("OK: ");
1024 else if(result==1)
1025 printf("WARNING: ");
1026 else if(result==2)
1027 printf("CRITICAL: ");
1028 else if(result==3)
1029 printf("UNKNOWN: ");
1031 /* we didn't receive any DHCPOFFERs */
1032 if(dhcp_offer_list==NULL){
1033 printf(_("No DHCPOFFERs were received.\n"));
1034 return result;
1035 }
1037 printf(_("Received %d DHCPOFFER(s)"),valid_responses);
1039 if(requested_servers>0)
1040 printf(_(", %s%d of %d requested servers responded"),((requested_responses<requested_servers) && requested_responses>0)?"only ":"",requested_responses,requested_servers);
1042 if(request_specific_address==TRUE)
1043 printf(_(", requested address (%s) was %soffered"),inet_ntoa(requested_address),(received_requested_address==TRUE)?"":_("not "));
1045 printf(_(", max lease time = "));
1046 if(max_lease_time==DHCP_INFINITE_TIME)
1047 printf(_("Infinity"));
1048 else
1049 printf("%lu sec",(unsigned long)max_lease_time);
1051 printf(".\n");
1053 return result;
1054 }
1057 /* process command-line arguments */
1058 int process_arguments(int argc, char **argv){
1059 int c;
1061 if(argc<1)
1062 return ERROR;
1064 c=0;
1065 while((c+=(call_getopt(argc-c,&argv[c])))<argc){
1067 /*
1068 if(is_option(argv[c]))
1069 continue;
1070 */
1071 }
1073 return validate_arguments();
1074 }
1078 int call_getopt(int argc, char **argv){
1079 int c=0;
1080 int i=0;
1081 struct in_addr ipaddress;
1083 int option_index = 0;
1084 static struct option long_options[] =
1085 {
1086 {"serverip", required_argument,0,'s'},
1087 {"requestedip", required_argument,0,'r'},
1088 {"timeout", required_argument,0,'t'},
1089 {"interface", required_argument,0,'i'},
1090 {"unicast", no_argument, 0,'u'},
1091 {"verbose", no_argument, 0,'v'},
1092 {"version", no_argument, 0,'V'},
1093 {"help", no_argument, 0,'h'},
1094 {0,0,0,0}
1095 };
1097 while(1){
1098 c=getopt_long(argc,argv,"+hVvt:s:r:t:i:u",long_options,&option_index);
1100 i++;
1102 if(c==-1||c==EOF||c==1)
1103 break;
1105 switch(c){
1106 case 'w':
1107 case 'r':
1108 case 't':
1109 case 'i':
1110 i++;
1111 break;
1112 default:
1113 break;
1114 }
1116 switch(c){
1118 case 's': /* DHCP server address */
1119 if(inet_aton(optarg,&ipaddress)){
1120 add_requested_server(ipaddress);
1121 inet_aton(optarg, &dhcp_ip);
1122 if (verbose)
1123 printf("querying %s\n",inet_ntoa(dhcp_ip));
1124 }
1125 /*
1126 else
1127 usage("Invalid server IP address\n");
1128 */
1129 break;
1131 case 'r': /* address we are requested from DHCP servers */
1132 if(inet_aton(optarg,&ipaddress)){
1133 requested_address=ipaddress;
1134 request_specific_address=TRUE;
1135 }
1136 /*
1137 else
1138 usage("Invalid requested IP address\n");
1139 */
1140 break;
1142 case 't': /* timeout */
1144 /*
1145 if(is_intnonneg(optarg))
1146 */
1147 if(atoi(optarg)>0)
1148 dhcpoffer_timeout=atoi(optarg);
1149 /*
1150 else
1151 usage("Time interval must be a nonnegative integer\n");
1152 */
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,revision);
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;
1184 }
1185 }
1187 return i;
1188 }
1191 int validate_arguments(void){
1193 return OK;
1194 }
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);
1212 }
1213 else{
1214 printf("%s\n", "get_msg FAILED.");
1215 return(GOT_ERR);
1216 }
1217 }
1218 if(ctl.len > 0){
1219 ret |= GOT_CTRL;
1220 }
1221 if(dat.len > 0){
1222 ret |= GOT_DATA;
1223 }
1225 return(ret);
1226 }
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);
1235 }
1237 return 0;
1238 }
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);
1247 }
1249 return 0;
1250 }
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);
1260 }
1262 return 0;
1263 }
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);
1272 }
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);
1278 }
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);
1296 }
1297 bcopy((u_char *)bind_ack + bind_ack->dl_addr_offset, addr,
1298 bind_ack->dl_addr_length);
1300 return 0;
1301 }
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 ..)
1307 *
1308 * parameter: addr: an array of six bytes, has to be allocated by the caller
1309 *
1310 * return: 0 if OK, -1 if the address could not be determined
1311 *
1312 *
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;
1323 }
1324 }
1325 close(fd);
1327 return -1;
1328 }
1330 /* Kompf 2000-2003 */
1331 #endif
1334 /* print usage help */
1335 void print_help(void){
1337 print_revision(progname,revision);
1339 printf("Copyright (c) 2001-2004 Ethan Galstad (nagios@nagios.org)\n");
1340 printf (COPYRIGHT, copyright, email);
1342 printf("%s\n", _("This plugin tests the availability of DHCP servers on a network."));
1344 printf ("\n\n");
1346 print_usage();
1348 printf (_(UT_HELP_VRSN));
1350 printf (_(UT_VERBOSE));
1352 printf (" %s\n", "-s, --serverip=IPADDRESS");
1353 printf (" %s\n", _("IP address of DHCP server that we must hear from"));
1354 printf (" %s\n", "-r, --requestedip=IPADDRESS");
1355 printf (" %s\n", _("IP address that should be offered by at least one DHCP server"));
1356 printf (" %s\n", "-t, --timeout=INTEGER");
1357 printf (" %s\n", _("Seconds to wait for DHCPOFFER before timeout occurs"));
1358 printf (" %s\n", "-i, --interface=STRING");
1359 printf (" %s\n", _("Interface to to use for listening (i.e. eth0)"));
1360 printf (" %s\n", "-u, --unicast");
1361 printf (" %s\n", _("Unicast testing: mimic a DHCP relay, requires -s"));
1363 return;
1364 }
1367 void
1368 print_usage(void){
1370 printf (_("Usage:"));
1371 printf (" %s [-v] [-u] [-s serverip] [-r requestedip] [-t timeout]\n",progname);
1372 printf (" [-i interface]\n");
1374 return;
1375 }