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)-1);
317 ifr.ifr_name[sizeof(ifr.ifr_name)-1]='\0';
319 /* try and grab hardware address of requested interface */
320 if(ioctl(sock,SIOCGIFHWADDR,&ifr)<0){
321 printf(_("Error: Could not get hardware address of interface '%s'\n"),interface_name);
322 exit(STATE_UNKNOWN);
323 }
325 memcpy(&client_hardware_address[0],&ifr.ifr_hwaddr.sa_data,6);
327 #elif defined(__bsd__)
328 /* King 2004 see ACKNOWLEDGEMENTS */
330 int mib[6], len;
331 char *buf;
332 unsigned char *ptr;
333 struct if_msghdr *ifm;
334 struct sockaddr_dl *sdl;
336 mib[0] = CTL_NET;
337 mib[1] = AF_ROUTE;
338 mib[2] = 0;
339 mib[3] = AF_LINK;
340 mib[4] = NET_RT_IFLIST;
342 if((mib[5] = if_nametoindex(interface_name)) == 0){
343 printf(_("Error: if_nametoindex error - %s.\n"), strerror(errno));
344 exit(STATE_UNKNOWN);
345 }
347 if(sysctl(mib, 6, NULL, &len, NULL, 0) < 0){
348 printf(_("Error: Couldn't get hardware address from %s. sysctl 1 error - %s.\n"), interface_name, strerror(errno));
349 exit(STATE_UNKNOWN);
350 }
352 if((buf = malloc(len)) == NULL){
353 printf(_("Error: Couldn't get hardware address from interface %s. malloc error - %s.\n"), interface_name, strerror(errno));
354 exit(4);
355 }
357 if(sysctl(mib, 6, buf, &len, NULL, 0) < 0){
358 printf(_("Error: Couldn't get hardware address from %s. sysctl 2 error - %s.\n"), interface_name, strerror(errno));
359 exit(STATE_UNKNOWN);
360 }
362 ifm = (struct if_msghdr *)buf;
363 sdl = (struct sockaddr_dl *)(ifm + 1);
364 ptr = (unsigned char *)LLADDR(sdl);
365 memcpy(&client_hardware_address[0], ptr, 6) ;
366 /* King 2004 */
368 #elif defined(__sun__) || defined(__solaris__)
370 /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */
371 long stat;
372 char dev[20] = "/dev/";
373 char *p;
374 int unit;
376 for(p = interface_name; *p && isalpha(*p); p++)
377 /* no-op */ ;
378 if( p != '\0' ){
379 unit = atoi(p) ;
380 *p = '\0' ;
381 strncat(dev, interface_name, 6) ;
382 }
383 else{
384 printf(_("Error: can't find unit number in interface_name (%s) - expecting TypeNumber eg lnc0.\n"), interface_name);
385 exit(STATE_UNKNOWN);
386 }
387 stat = mac_addr_dlpi(dev, unit, client_hardware_address);
388 if(stat != 0){
389 printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit);
390 exit(STATE_UNKNOWN);
391 }
393 #elif defined(__hpux__)
395 long stat;
396 char dev[20] = "/dev/dlpi" ;
397 int unit = 0;
399 stat = mac_addr_dlpi(dev, unit, client_hardware_address);
400 if(stat != 0){
401 printf(_("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n"), dev, unit);
402 exit(STATE_UNKNOWN);
403 }
404 /* Kompf 2000-2003 */
406 #else
407 printf(_("Error: can't get MAC address for this architecture.\n"));
408 exit(STATE_UNKNOWN);
409 #endif
411 if(verbose){
412 printf(_("Hardware address: "));
413 for (i=0; i<6; ++i)
414 printf("%2.2x", client_hardware_address[i]);
415 printf( "\n");
416 }
418 return OK;
419 }
421 /* determines IP address of the client interface */
422 int get_ip_address(int sock,char *interface_name){
423 #if defined(SIOCGIFADDR)
424 struct ifreq ifr;
426 strncpy((char *)&ifr.ifr_name,interface_name,sizeof(ifr.ifr_name)-1);
427 ifr.ifr_name[sizeof(ifr.ifr_name)-1]='\0';
429 if(ioctl(sock,SIOCGIFADDR,&ifr)<0){
430 printf(_("Error: Cannot determine IP address of interface %s\n"),
431 interface_name);
432 exit(STATE_UNKNOWN);
433 }
435 my_ip=((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
437 #else
438 printf(_("Error: Cannot get interface IP address on this platform.\n"));
439 exit(STATE_UNKNOWN);
440 #endif
442 if(verbose)
443 printf(_("Pretending to be relay client %s\n"),inet_ntoa(my_ip));
445 return OK;
446 }
448 /* sends a DHCPDISCOVER broadcast message in an attempt to find DHCP servers */
449 int send_dhcp_discover(int sock){
450 dhcp_packet discover_packet;
451 struct sockaddr_in sockaddr_broadcast;
452 unsigned short opts;
455 /* clear the packet data structure */
456 bzero(&discover_packet,sizeof(discover_packet));
459 /* boot request flag (backward compatible with BOOTP servers) */
460 discover_packet.op=BOOTREQUEST;
462 /* hardware address type */
463 discover_packet.htype=ETHERNET_HARDWARE_ADDRESS;
465 /* length of our hardware address */
466 discover_packet.hlen=ETHERNET_HARDWARE_ADDRESS_LENGTH;
468 /*
469 * transaction ID is supposed to be random. We won't use the address so
470 * we don't care about high entropy here. time(2) is good enough.
471 */
472 srand(time(NULL));
473 packet_xid=random();
474 discover_packet.xid=htonl(packet_xid);
476 /**** WHAT THE HECK IS UP WITH THIS?!? IF I DON'T MAKE THIS CALL, ONLY ONE SERVER RESPONSE IS PROCESSED!!!! ****/
477 /* downright bizzarre... */
478 ntohl(discover_packet.xid);
480 /*discover_packet.secs=htons(65535);*/
481 discover_packet.secs=0xFF;
483 /*
484 * server needs to know if it should broadcast or unicast its response:
485 * 0x8000L == 32768 == 1 << 15 == broadcast, 0 == unicast
486 */
487 discover_packet.flags = unicast ? 0 : htons(DHCP_BROADCAST_FLAG);
489 /* our hardware address */
490 memcpy(discover_packet.chaddr,client_hardware_address,ETHERNET_HARDWARE_ADDRESS_LENGTH);
492 /* first four bytes of options field is magic cookie (as per RFC 2132) */
493 discover_packet.options[0]='\x63';
494 discover_packet.options[1]='\x82';
495 discover_packet.options[2]='\x53';
496 discover_packet.options[3]='\x63';
498 opts = 4;
499 /* DHCP message type is embedded in options field */
500 discover_packet.options[opts++]=DHCP_OPTION_MESSAGE_TYPE; /* DHCP message type option identifier */
501 discover_packet.options[opts++]='\x01'; /* DHCP message option length in bytes */
502 discover_packet.options[opts++]=DHCPDISCOVER;
504 /* the IP address we're requesting */
505 if(request_specific_address==TRUE){
506 discover_packet.options[opts++]=DHCP_OPTION_REQUESTED_ADDRESS;
507 discover_packet.options[opts++]='\x04';
508 memcpy(&discover_packet.options[opts],&requested_address,sizeof(requested_address));
509 opts += sizeof(requested_address);
510 }
511 discover_packet.options[opts++]=DHCP_OPTION_END;
513 /* unicast fields */
514 if(unicast)
515 discover_packet.giaddr.s_addr = my_ip.s_addr;
517 /* see RFC 1542, 4.1.1 */
518 discover_packet.hops = unicast ? 1 : 0;
520 /* send the DHCPDISCOVER packet to broadcast address */
521 sockaddr_broadcast.sin_family=AF_INET;
522 sockaddr_broadcast.sin_port=htons(DHCP_SERVER_PORT);
523 sockaddr_broadcast.sin_addr.s_addr = unicast ? dhcp_ip.s_addr : INADDR_BROADCAST;
524 bzero(&sockaddr_broadcast.sin_zero,sizeof(sockaddr_broadcast.sin_zero));
527 if(verbose){
528 printf(_("DHCPDISCOVER to %s port %d\n"),inet_ntoa(sockaddr_broadcast.sin_addr),ntohs(sockaddr_broadcast.sin_port));
529 printf("DHCPDISCOVER XID: %u (0x%X)\n",ntohl(discover_packet.xid),ntohl(discover_packet.xid));
530 printf("DHCDISCOVER ciaddr: %s\n",inet_ntoa(discover_packet.ciaddr));
531 printf("DHCDISCOVER yiaddr: %s\n",inet_ntoa(discover_packet.yiaddr));
532 printf("DHCDISCOVER siaddr: %s\n",inet_ntoa(discover_packet.siaddr));
533 printf("DHCDISCOVER giaddr: %s\n",inet_ntoa(discover_packet.giaddr));
534 }
536 /* send the DHCPDISCOVER packet out */
537 send_dhcp_packet(&discover_packet,sizeof(discover_packet),sock,&sockaddr_broadcast);
539 if(verbose)
540 printf("\n\n");
542 return OK;
543 }
548 /* waits for a DHCPOFFER message from one or more DHCP servers */
549 int get_dhcp_offer(int sock){
550 dhcp_packet offer_packet;
551 struct sockaddr_in source;
552 struct sockaddr_in via;
553 int result=OK;
554 int responses=0;
555 int x;
556 time_t start_time;
557 time_t current_time;
559 time(&start_time);
561 /* receive as many responses as we can */
562 for(responses=0,valid_responses=0;;){
564 time(¤t_time);
565 if((current_time-start_time)>=dhcpoffer_timeout)
566 break;
568 if(verbose)
569 printf("\n\n");
571 bzero(&source,sizeof(source));
572 bzero(&via,sizeof(via));
573 bzero(&offer_packet,sizeof(offer_packet));
575 result=OK;
576 result=receive_dhcp_packet(&offer_packet,sizeof(offer_packet),sock,dhcpoffer_timeout,&source);
578 if(result!=OK){
579 if(verbose)
580 printf(_("Result=ERROR\n"));
582 continue;
583 }
584 else{
585 if(verbose)
586 printf(_("Result=OK\n"));
588 responses++;
589 }
591 /* The "source" is either a server or a relay. */
592 /* Save a copy of "source" into "via" even if it's via itself */
593 memcpy(&via,&source,sizeof(source)) ;
595 /* If siaddr is non-zero, set "source" to siaddr */
596 if(offer_packet.siaddr.s_addr != 0L){
597 source.sin_addr.s_addr = offer_packet.siaddr.s_addr ;
598 }
600 if(verbose){
601 printf(_("DHCPOFFER from IP address %s"),inet_ntoa(source.sin_addr));
602 printf(_(" via %s\n"),inet_ntoa(via.sin_addr));
603 printf("DHCPOFFER XID: %u (0x%X)\n",ntohl(offer_packet.xid),ntohl(offer_packet.xid));
604 }
606 /* check packet xid to see if its the same as the one we used in the discover packet */
607 if(ntohl(offer_packet.xid)!=packet_xid){
608 if(verbose)
609 printf(_("DHCPOFFER XID (%u) did not match DHCPDISCOVER XID (%u) - ignoring packet\n"),ntohl(offer_packet.xid),packet_xid);
611 continue;
612 }
614 /* check hardware address */
615 result=OK;
616 if(verbose)
617 printf("DHCPOFFER chaddr: ");
619 for(x=0;x<ETHERNET_HARDWARE_ADDRESS_LENGTH;x++){
620 if(verbose)
621 printf("%02X",(unsigned char)offer_packet.chaddr[x]);
623 if(offer_packet.chaddr[x]!=client_hardware_address[x])
624 result=ERROR;
625 }
626 if(verbose)
627 printf("\n");
629 if(result==ERROR){
630 if(verbose)
631 printf(_("DHCPOFFER hardware address did not match our own - ignoring packet\n"));
633 continue;
634 }
636 if(verbose){
637 printf("DHCPOFFER ciaddr: %s\n",inet_ntoa(offer_packet.ciaddr));
638 printf("DHCPOFFER yiaddr: %s\n",inet_ntoa(offer_packet.yiaddr));
639 printf("DHCPOFFER siaddr: %s\n",inet_ntoa(offer_packet.siaddr));
640 printf("DHCPOFFER giaddr: %s\n",inet_ntoa(offer_packet.giaddr));
641 }
643 add_dhcp_offer(source.sin_addr,&offer_packet);
645 valid_responses++;
646 }
648 if(verbose){
649 printf(_("Total responses seen on the wire: %d\n"),responses);
650 printf(_("Valid responses for this machine: %d\n"),valid_responses);
651 }
653 return OK;
654 }
658 /* sends a DHCP packet */
659 int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in *dest){
660 int result;
662 result=sendto(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)dest,sizeof(*dest));
664 if(verbose)
665 printf(_("send_dhcp_packet result: %d\n"),result);
667 if(result<0)
668 return ERROR;
670 return OK;
671 }
675 /* receives a DHCP packet */
676 int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, struct sockaddr_in *address){
677 struct timeval tv;
678 fd_set readfds;
679 fd_set oobfds;
680 int recv_result;
681 socklen_t address_size;
682 struct sockaddr_in source_address;
683 int nfound;
686 /* wait for data to arrive (up time timeout) */
687 tv.tv_sec=timeout;
688 tv.tv_usec=0;
689 FD_ZERO(&readfds);
690 FD_ZERO(&oobfds);
691 FD_SET(sock,&readfds);
692 FD_SET(sock,&oobfds);
693 nfound = select(sock+1,&readfds,NULL,&oobfds,&tv);
695 /* make sure some data has arrived */
696 if(!FD_ISSET(sock,&readfds)){
697 if(verbose)
698 printf(_("No (more) data received (nfound: %d)\n"), nfound);
699 return ERROR;
700 }
702 else{
704 /* why do we need to peek first? i don't know, its a hack. without it, the source address of the first packet received was
705 not being interpreted correctly. sigh... */
706 bzero(&source_address,sizeof(source_address));
707 address_size=sizeof(source_address);
708 recv_result=recvfrom(sock,(char *)buffer,buffer_size,MSG_PEEK,(struct sockaddr *)&source_address,&address_size);
709 if(verbose)
710 printf("recv_result_1: %d\n",recv_result);
711 recv_result=recvfrom(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)&source_address,&address_size);
712 if(verbose)
713 printf("recv_result_2: %d\n",recv_result);
715 if(recv_result==-1){
716 if(verbose){
717 printf(_("recvfrom() failed, "));
718 printf("errno: (%d) -> %s\n",errno,strerror(errno));
719 }
720 return ERROR;
721 }
722 else{
723 if(verbose){
724 printf(_("receive_dhcp_packet() result: %d\n"),recv_result);
725 printf(_("receive_dhcp_packet() source: %s\n"),inet_ntoa(source_address.sin_addr));
726 }
728 memcpy(address,&source_address,sizeof(source_address));
729 return OK;
730 }
731 }
733 return OK;
734 }
737 /* creates a socket for DHCP communication */
738 int create_dhcp_socket(void){
739 struct sockaddr_in myname;
740 struct ifreq interface;
741 int sock;
742 int flag=1;
744 /* Set up the address we're going to bind to. */
745 bzero(&myname,sizeof(myname));
746 myname.sin_family=AF_INET;
747 /* listen to DHCP server port if we're in unicast mode */
748 myname.sin_port = htons(unicast ? DHCP_SERVER_PORT : DHCP_CLIENT_PORT);
749 myname.sin_addr.s_addr = unicast ? my_ip.s_addr : INADDR_ANY;
750 bzero(&myname.sin_zero,sizeof(myname.sin_zero));
752 /* create a socket for DHCP communications */
753 sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
754 if(sock<0){
755 printf(_("Error: Could not create socket!\n"));
756 exit(STATE_UNKNOWN);
757 }
759 if(verbose)
760 printf("DHCP socket: %d\n",sock);
762 /* set the reuse address flag so we don't get errors when restarting */
763 flag=1;
764 if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char *)&flag,sizeof(flag))<0){
765 printf(_("Error: Could not set reuse address option on DHCP socket!\n"));
766 exit(STATE_UNKNOWN);
767 }
769 /* set the broadcast option - we need this to listen to DHCP broadcast messages */
770 if(setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char *)&flag,sizeof flag)<0){
771 printf(_("Error: Could not set broadcast option on DHCP socket!\n"));
772 exit(STATE_UNKNOWN);
773 }
775 /* bind socket to interface */
776 #if defined(__linux__)
777 strncpy(interface.ifr_ifrn.ifrn_name,network_interface_name,IFNAMSIZ-1);
778 interface.ifr_ifrn.ifrn_name[IFNAMSIZ-1]='\0';
779 if(setsockopt(sock,SOL_SOCKET,SO_BINDTODEVICE,(char *)&interface,sizeof(interface))<0){
780 printf(_("Error: Could not bind socket to interface %s. Check your privileges...\n"),network_interface_name);
781 exit(STATE_UNKNOWN);
782 }
784 #else
785 strncpy(interface.ifr_name,network_interface_name,IFNAMSIZ-1);
786 interface.ifr_name[IFNAMSIZ-1]='\0';
787 #endif
789 /* bind the socket */
790 if(bind(sock,(struct sockaddr *)&myname,sizeof(myname))<0){
791 printf(_("Error: Could not bind to DHCP socket (port %d)! Check your privileges...\n"),DHCP_CLIENT_PORT);
792 exit(STATE_UNKNOWN);
793 }
795 return sock;
796 }
799 /* closes DHCP socket */
800 int close_dhcp_socket(int sock){
802 close(sock);
804 return OK;
805 }
808 /* adds a requested server address to list in memory */
809 int add_requested_server(struct in_addr server_address){
810 requested_server *new_server;
812 new_server=(requested_server *)malloc(sizeof(requested_server));
813 if(new_server==NULL)
814 return ERROR;
816 new_server->server_address=server_address;
817 new_server->answered=FALSE;
819 new_server->next=requested_server_list;
820 requested_server_list=new_server;
822 requested_servers++;
824 if(verbose)
825 printf(_("Requested server address: %s\n"),inet_ntoa(new_server->server_address));
827 return OK;
828 }
833 /* adds a DHCP OFFER to list in memory */
834 int add_dhcp_offer(struct in_addr source,dhcp_packet *offer_packet){
835 dhcp_offer *new_offer;
836 int x;
837 unsigned option_type;
838 unsigned option_length;
839 struct in_addr serv_ident = {0};
841 if(offer_packet==NULL)
842 return ERROR;
844 /* process all DHCP options present in the packet */
845 for(x=4;x<MAX_DHCP_OPTIONS_LENGTH;){
847 /* end of options (0 is really just a pad, but bail out anyway) */
848 if((int)offer_packet->options[x]==-1 || (int)offer_packet->options[x]==0)
849 break;
851 /* get option type */
852 option_type=offer_packet->options[x++];
854 /* get option length */
855 option_length=offer_packet->options[x++];
857 if(verbose)
858 printf("Option: %d (0x%02X)\n",option_type,option_length);
860 /* get option data */
861 switch(option_type){
862 case DHCP_OPTION_LEASE_TIME:
863 memcpy(&dhcp_lease_time, &offer_packet->options[x],sizeof(dhcp_lease_time));
864 dhcp_lease_time = ntohl(dhcp_lease_time);
865 break;
866 case DHCP_OPTION_RENEWAL_TIME:
867 memcpy(&dhcp_renewal_time, &offer_packet->options[x],sizeof(dhcp_renewal_time));
868 dhcp_renewal_time = ntohl(dhcp_renewal_time);
869 break;
870 case DHCP_OPTION_REBINDING_TIME:
871 memcpy(&dhcp_rebinding_time, &offer_packet->options[x],sizeof(dhcp_rebinding_time));
872 dhcp_rebinding_time = ntohl(dhcp_rebinding_time);
873 break;
874 case DHCP_OPTION_SERVER_IDENTIFIER:
875 memcpy(&serv_ident.s_addr, &offer_packet->options[x],sizeof(serv_ident.s_addr));
876 break;
877 }
879 /* skip option data we're ignoring */
880 if(option_type!=DHCP_OPTION_REBINDING_TIME)
881 x+=option_length;
882 }
884 if(verbose){
885 if(dhcp_lease_time==DHCP_INFINITE_TIME)
886 printf(_("Lease Time: Infinite\n"));
887 else
888 printf(_("Lease Time: %lu seconds\n"),(unsigned long)dhcp_lease_time);
889 if(dhcp_renewal_time==DHCP_INFINITE_TIME)
890 printf(_("Renewal Time: Infinite\n"));
891 else
892 printf(_("Renewal Time: %lu seconds\n"),(unsigned long)dhcp_renewal_time);
893 if(dhcp_rebinding_time==DHCP_INFINITE_TIME)
894 printf(_("Rebinding Time: Infinite\n"));
895 printf(_("Rebinding Time: %lu seconds\n"),(unsigned long)dhcp_rebinding_time);
896 }
898 new_offer=(dhcp_offer *)malloc(sizeof(dhcp_offer));
900 if(new_offer==NULL)
901 return ERROR;
903 /*
904 * RFC 2131 (2.) says: "DHCP clarifies the interpretation of the
905 * 'siaddr' field as the address of the server to use in the next step
906 * of the client's bootstrap process. A DHCP server may return its own
907 * address in the 'siaddr' field, if the server is prepared to supply
908 * the next bootstrap service (e.g., delivery of an operating system
909 * executable image). A DHCP server always returns its own address in
910 * the 'server identifier' option." 'serv_ident' is the 'server
911 * identifier' option, 'source' is the 'siaddr' field or (if 'siaddr'
912 * wasn't available) the IP address we received the DHCPOFFER from. If
913 * 'serv_ident' isn't available for some reason, we use 'source'.
914 */
915 new_offer->server_address=serv_ident.s_addr?serv_ident:source;
916 new_offer->offered_address=offer_packet->yiaddr;
917 new_offer->lease_time=dhcp_lease_time;
918 new_offer->renewal_time=dhcp_renewal_time;
919 new_offer->rebinding_time=dhcp_rebinding_time;
922 if(verbose){
923 printf(_("Added offer from server @ %s"),inet_ntoa(new_offer->server_address));
924 printf(_(" of IP address %s\n"),inet_ntoa(new_offer->offered_address));
925 }
927 /* add new offer to head of list */
928 new_offer->next=dhcp_offer_list;
929 dhcp_offer_list=new_offer;
931 return OK;
932 }
935 /* frees memory allocated to DHCP OFFER list */
936 int free_dhcp_offer_list(void){
937 dhcp_offer *this_offer;
938 dhcp_offer *next_offer;
940 for(this_offer=dhcp_offer_list;this_offer!=NULL;this_offer=next_offer){
941 next_offer=this_offer->next;
942 free(this_offer);
943 }
945 return OK;
946 }
949 /* frees memory allocated to requested server list */
950 int free_requested_server_list(void){
951 requested_server *this_server;
952 requested_server *next_server;
954 for(this_server=requested_server_list;this_server!=NULL;this_server=next_server){
955 next_server=this_server->next;
956 free(this_server);
957 }
959 return OK;
960 }
963 /* gets state and plugin output to return */
964 int get_results(void){
965 dhcp_offer *temp_offer;
966 requested_server *temp_server;
967 int result;
968 u_int32_t max_lease_time=0;
970 received_requested_address=FALSE;
972 /* checks responses from requested servers */
973 requested_responses=0;
974 if(requested_servers>0){
976 for(temp_server=requested_server_list;temp_server!=NULL;temp_server=temp_server->next){
978 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
980 /* get max lease time we were offered */
981 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
982 max_lease_time=temp_offer->lease_time;
984 /* see if we got the address we requested */
985 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
986 received_requested_address=TRUE;
988 /* see if the servers we wanted a response from talked to us or not */
989 if(!memcmp(&temp_offer->server_address,&temp_server->server_address,sizeof(temp_server->server_address))){
990 if(verbose){
991 printf(_("DHCP Server Match: Offerer=%s"),inet_ntoa(temp_offer->server_address));
992 printf(_(" Requested=%s"),inet_ntoa(temp_server->server_address));
993 if(temp_server->answered)
994 printf(_(" (duplicate)"));
995 printf(_("\n"));
996 }
997 if(temp_server->answered == FALSE){
998 requested_responses++;
999 temp_server->answered=TRUE;
1000 }
1001 }
1002 }
1003 }
1005 }
1007 /* else check and see if we got our requested address from any server */
1008 else{
1010 for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
1012 /* get max lease time we were offered */
1013 if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
1014 max_lease_time=temp_offer->lease_time;
1016 /* see if we got the address we requested */
1017 if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
1018 received_requested_address=TRUE;
1019 }
1020 }
1022 result=STATE_OK;
1023 if(valid_responses==0)
1024 result=STATE_CRITICAL;
1025 else if(requested_servers>0 && requested_responses==0)
1026 result=STATE_CRITICAL;
1027 else if(requested_responses<requested_servers)
1028 result=STATE_WARNING;
1029 else if(request_specific_address==TRUE && received_requested_address==FALSE)
1030 result=STATE_WARNING;
1032 if(result==0) /* garrett honeycutt 2005 */
1033 printf("OK: ");
1034 else if(result==1)
1035 printf("WARNING: ");
1036 else if(result==2)
1037 printf("CRITICAL: ");
1038 else if(result==3)
1039 printf("UNKNOWN: ");
1041 /* we didn't receive any DHCPOFFERs */
1042 if(dhcp_offer_list==NULL){
1043 printf(_("No DHCPOFFERs were received.\n"));
1044 return result;
1045 }
1047 printf(_("Received %d DHCPOFFER(s)"),valid_responses);
1049 if(requested_servers>0)
1050 printf(_(", %s%d of %d requested servers responded"),((requested_responses<requested_servers) && requested_responses>0)?"only ":"",requested_responses,requested_servers);
1052 if(request_specific_address==TRUE)
1053 printf(_(", requested address (%s) was %soffered"),inet_ntoa(requested_address),(received_requested_address==TRUE)?"":_("not "));
1055 printf(_(", max lease time = "));
1056 if(max_lease_time==DHCP_INFINITE_TIME)
1057 printf(_("Infinity"));
1058 else
1059 printf("%lu sec",(unsigned long)max_lease_time);
1061 printf(".\n");
1063 return result;
1064 }
1067 /* process command-line arguments */
1068 int process_arguments(int argc, char **argv){
1069 int c;
1071 if(argc<1)
1072 return ERROR;
1074 c=0;
1075 while((c+=(call_getopt(argc-c,&argv[c])))<argc){
1077 /*
1078 if(is_option(argv[c]))
1079 continue;
1080 */
1081 }
1083 return validate_arguments();
1084 }
1088 int call_getopt(int argc, char **argv){
1089 int c=0;
1090 int i=0;
1091 struct in_addr ipaddress;
1093 int option_index = 0;
1094 static struct option long_options[] =
1095 {
1096 {"serverip", required_argument,0,'s'},
1097 {"requestedip", required_argument,0,'r'},
1098 {"timeout", required_argument,0,'t'},
1099 {"interface", required_argument,0,'i'},
1100 {"unicast", no_argument, 0,'u'},
1101 {"verbose", no_argument, 0,'v'},
1102 {"version", no_argument, 0,'V'},
1103 {"help", no_argument, 0,'h'},
1104 {0,0,0,0}
1105 };
1107 while(1){
1108 c=getopt_long(argc,argv,"+hVvt:s:r:t:i:u",long_options,&option_index);
1110 i++;
1112 if(c==-1||c==EOF||c==1)
1113 break;
1115 switch(c){
1116 case 'w':
1117 case 'r':
1118 case 't':
1119 case 'i':
1120 i++;
1121 break;
1122 default:
1123 break;
1124 }
1126 switch(c){
1128 case 's': /* DHCP server address */
1129 if(inet_aton(optarg,&ipaddress)){
1130 add_requested_server(ipaddress);
1131 inet_aton(optarg, &dhcp_ip);
1132 if (verbose)
1133 printf("querying %s\n",inet_ntoa(dhcp_ip));
1134 }
1135 /*
1136 else
1137 usage("Invalid server IP address\n");
1138 */
1139 break;
1141 case 'r': /* address we are requested from DHCP servers */
1142 if(inet_aton(optarg,&ipaddress)){
1143 requested_address=ipaddress;
1144 request_specific_address=TRUE;
1145 }
1146 /*
1147 else
1148 usage("Invalid requested IP address\n");
1149 */
1150 break;
1152 case 't': /* timeout */
1154 /*
1155 if(is_intnonneg(optarg))
1156 */
1157 if(atoi(optarg)>0)
1158 dhcpoffer_timeout=atoi(optarg);
1159 /*
1160 else
1161 usage("Time interval must be a nonnegative integer\n");
1162 */
1163 break;
1165 case 'i': /* interface name */
1167 strncpy(network_interface_name,optarg,sizeof(network_interface_name)-1);
1168 network_interface_name[sizeof(network_interface_name)-1]='\x0';
1170 break;
1172 case 'u': /* unicast testing */
1173 unicast=1;
1174 break;
1176 case 'V': /* version */
1177 print_revision(progname,revision);
1178 exit(STATE_OK);
1180 case 'h': /* help */
1181 print_help();
1182 exit(STATE_OK);
1184 case 'v': /* verbose */
1185 verbose=1;
1186 break;
1188 case '?': /* help */
1189 usage5 ();
1190 break;
1192 default:
1193 break;
1194 }
1195 }
1197 return i;
1198 }
1201 int validate_arguments(void){
1203 return OK;
1204 }
1207 #if defined(__sun__) || defined(__solaris__) || defined(__hpux__)
1208 /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */
1210 /* get a message from a stream; return type of message */
1211 static int get_msg(int fd){
1212 int flags = 0;
1213 int res, ret;
1214 ctl_area[0] = 0;
1215 dat_area[0] = 0;
1216 ret = 0;
1217 res = getmsg(fd, &ctl, &dat, &flags);
1219 if(res < 0){
1220 if(errno == EINTR){
1221 return(GOT_INTR);
1222 }
1223 else{
1224 printf("%s\n", "get_msg FAILED.");
1225 return(GOT_ERR);
1226 }
1227 }
1228 if(ctl.len > 0){
1229 ret |= GOT_CTRL;
1230 }
1231 if(dat.len > 0){
1232 ret |= GOT_DATA;
1233 }
1235 return(ret);
1236 }
1238 /* verify that dl_primitive in ctl_area = prim */
1239 static int check_ctrl(int prim){
1240 dl_error_ack_t *err_ack = (dl_error_ack_t *)ctl_area;
1242 if(err_ack->dl_primitive != prim){
1243 printf(_("Error: DLPI stream API failed to get MAC in check_ctrl: %s.\n"), strerror(errno));
1244 exit(STATE_UNKNOWN);
1245 }
1247 return 0;
1248 }
1250 /* put a control message on a stream */
1251 static int put_ctrl(int fd, int len, int pri){
1253 ctl.len = len;
1254 if(putmsg(fd, &ctl, 0, pri) < 0){
1255 printf(_("Error: DLPI stream API failed to get MAC in put_ctrl/putmsg(): %s.\n"), strerror(errno));
1256 exit(STATE_UNKNOWN);
1257 }
1259 return 0;
1260 }
1262 /* put a control + data message on a stream */
1263 static int put_both(int fd, int clen, int dlen, int pri){
1265 ctl.len = clen;
1266 dat.len = dlen;
1267 if(putmsg(fd, &ctl, &dat, pri) < 0){
1268 printf(_("Error: DLPI stream API failed to get MAC in put_both/putmsg().\n"), strerror(errno));
1269 exit(STATE_UNKNOWN);
1270 }
1272 return 0;
1273 }
1275 /* open file descriptor and attach */
1276 static int dl_open(const char *dev, int unit, int *fd){
1277 dl_attach_req_t *attach_req = (dl_attach_req_t *)ctl_area;
1279 if((*fd = open(dev, O_RDWR)) == -1){
1280 printf(_("Error: DLPI stream API failed to get MAC in dl_attach_req/open(%s..): %s.\n"), dev, strerror(errno));
1281 exit(STATE_UNKNOWN);
1282 }
1283 attach_req->dl_primitive = DL_ATTACH_REQ;
1284 attach_req->dl_ppa = unit;
1285 put_ctrl(*fd, sizeof(dl_attach_req_t), 0);
1286 get_msg(*fd);
1287 return check_ctrl(DL_OK_ACK);
1288 }
1290 /* send DL_BIND_REQ */
1291 static int dl_bind(int fd, int sap, u_char *addr){
1292 dl_bind_req_t *bind_req = (dl_bind_req_t *)ctl_area;
1293 dl_bind_ack_t *bind_ack = (dl_bind_ack_t *)ctl_area;
1295 bind_req->dl_primitive = DL_BIND_REQ;
1296 bind_req->dl_sap = sap;
1297 bind_req->dl_max_conind = 1;
1298 bind_req->dl_service_mode = DL_CLDLS;
1299 bind_req->dl_conn_mgmt = 0;
1300 bind_req->dl_xidtest_flg = 0;
1301 put_ctrl(fd, sizeof(dl_bind_req_t), 0);
1302 get_msg(fd);
1303 if (GOT_ERR == check_ctrl(DL_BIND_ACK)){
1304 printf(_("Error: DLPI stream API failed to get MAC in dl_bind/check_ctrl(): %s.\n"), strerror(errno));
1305 exit(STATE_UNKNOWN);
1306 }
1307 bcopy((u_char *)bind_ack + bind_ack->dl_addr_offset, addr,
1308 bind_ack->dl_addr_length);
1310 return 0;
1311 }
1313 /***********************************************************************
1314 * interface:
1315 * function mac_addr_dlpi - get the mac address of the interface with
1316 * type dev (eg lnc, hme) and unit (0, 1 ..)
1317 *
1318 * parameter: addr: an array of six bytes, has to be allocated by the caller
1319 *
1320 * return: 0 if OK, -1 if the address could not be determined
1321 *
1322 *
1323 ***********************************************************************/
1325 long mac_addr_dlpi( const char *dev, int unit, u_char *addr){
1326 int fd;
1327 u_char mac_addr[25];
1329 if(GOT_ERR != dl_open(dev, unit, &fd)){
1330 if(GOT_ERR != dl_bind(fd, INSAP, mac_addr)){
1331 bcopy( mac_addr, addr, 6);
1332 return 0;
1333 }
1334 }
1335 close(fd);
1337 return -1;
1338 }
1340 /* Kompf 2000-2003 */
1341 #endif
1344 /* print usage help */
1345 void print_help(void){
1347 print_revision(progname,revision);
1349 printf("Copyright (c) 2001-2004 Ethan Galstad (nagios@nagios.org)\n");
1350 printf (COPYRIGHT, copyright, email);
1352 printf("%s\n", _("This plugin tests the availability of DHCP servers on a network."));
1354 printf ("\n\n");
1356 print_usage();
1358 printf (_(UT_HELP_VRSN));
1360 printf (_(UT_VERBOSE));
1362 printf (" %s\n", "-s, --serverip=IPADDRESS");
1363 printf (" %s\n", _("IP address of DHCP server that we must hear from"));
1364 printf (" %s\n", "-r, --requestedip=IPADDRESS");
1365 printf (" %s\n", _("IP address that should be offered by at least one DHCP server"));
1366 printf (" %s\n", "-t, --timeout=INTEGER");
1367 printf (" %s\n", _("Seconds to wait for DHCPOFFER before timeout occurs"));
1368 printf (" %s\n", "-i, --interface=STRING");
1369 printf (" %s\n", _("Interface to to use for listening (i.e. eth0)"));
1370 printf (" %s\n", "-u, --unicast");
1371 printf (" %s\n", _("Unicast testing: mimic a DHCP relay, requires -s"));
1373 return;
1374 }
1377 void
1378 print_usage(void){
1380 printf (_("Usage:"));
1381 printf (" %s [-v] [-u] [-s serverip] [-r requestedip] [-t timeout]\n",progname);
1382 printf (" [-i interface]\n");
1384 return;
1385 }