Whitespace and indentation normalization.

This commit is contained in:
Nicholas J. Kain
2010-11-12 14:33:17 -05:00
parent 2262845be6
commit f4a00f3826
10 changed files with 1183 additions and 1198 deletions

5
README
View File

@@ -10,10 +10,7 @@ C99-compliant C compiler (for C99 struct subobject init)
CMake (tested: 2.8) CMake (tested: 2.8)
Tested with glibc 2.2.x and 2.3.x. dietlibc is not compatible. I have not yet Tested with glibc. dietlibc is not compatible. I have not tested uclibc.
tested uclibc.
I may bother to port to other operating systems, but don't count on it.
INTRODUCTION INTRODUCTION
------------ ------------

View File

@@ -1,7 +1,7 @@
/* ifchd.c - interface change daemon /* ifchd.c - interface change daemon
* Time-stamp: <2010-11-12 12:04:25 njk> * Time-stamp: <2010-11-12 14:27:47 njk>
* *
* (C) 2004 Nicholas J. Kain <njk@aerifal.cx> * (C) 2004-2010 Nicholas J. Kain <njkain at gmail dot com>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -16,7 +16,6 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/ */
#include <unistd.h> #include <unistd.h>
@@ -654,7 +653,7 @@ static void dispatch_work(void)
idle_time[i] = time(NULL); idle_time[i] = time(NULL);
memset(buf, '\0', sizeof(buf)); memset(buf, '\0', sizeof(buf));
dispatch_work_read_again: read_again:
ret = (int) read(sks[i], buf, MAX_BUF / 2 - 1); ret = (int) read(sks[i], buf, MAX_BUF / 2 - 1);
/* Check to see if peer closed socket */ /* Check to see if peer closed socket */
@@ -666,7 +665,7 @@ dispatch_work_read_again:
if (ret == -1) { if (ret == -1) {
if (errno == EINTR) if (errno == EINTR)
goto dispatch_work_read_again; goto read_again;
log_line("dispatch_work: read returned %s.\n", strerror(errno)); log_line("dispatch_work: read returned %s.\n", strerror(errno));
close(sks[i]); close(sks[i]);
new_sk(i, -1); new_sk(i, -1);
@@ -747,7 +746,7 @@ int main(int argc, char** argv) {
printf( printf(
"ifchd %s, if change daemon. Licensed under GNU GPL.\n", IFCHD_VERSION); "ifchd %s, if change daemon. Licensed under GNU GPL.\n", IFCHD_VERSION);
printf( printf(
"Copyright (C) 2004 Nicholas J. Kain\n" "Copyright (C) 2004-2010 Nicholas J. Kain\n"
"Usage: ifchd [OPTIONS]\n" "Usage: ifchd [OPTIONS]\n"
" -d, --detach detach from TTY and daemonize\n" " -d, --detach detach from TTY and daemonize\n"
" -n, --nodetach stay attached to TTY\n" " -n, --nodetach stay attached to TTY\n"
@@ -772,7 +771,7 @@ int main(int argc, char** argv) {
printf( printf(
"ifchd %s, if change daemon. Licensed under GNU GPL.\n", IFCHD_VERSION); "ifchd %s, if change daemon. Licensed under GNU GPL.\n", IFCHD_VERSION);
printf( printf(
"Copyright (C) 2004 Nicholas J. Kain\n" "Copyright (C) 2004-2010 Nicholas J. Kain\n"
"This is free software; see the source for copying conditions. There is NO\n" "This is free software; see the source for copying conditions. There is NO\n"
"WARRANTY; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"); "WARRANTY; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);

View File

@@ -1,7 +1,7 @@
/* linux.c - ifchd Linux-specific functions /* linux.c - ifchd Linux-specific functions
* Time-stamp: <2010-11-12 08:45:42 njk> * Time-stamp: <2010-11-12 14:29:32 njk>
* *
* (C) 2004 Nicholas J. Kain <njk@aerifal.cx> * (C) 2004-2010 Nicholas J. Kain <njkain at gmail dot com>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -16,7 +16,6 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/ */
#include <unistd.h> #include <unistd.h>
@@ -59,7 +58,7 @@ void initialize_if_data(void)
{ {
int i; int i;
for (i = 0; i < SOCK_QUEUE; i++) { for (i = 0; i < SOCK_QUEUE; i++) {
clear_if_data(i); clear_if_data(i);
} }
} }
@@ -67,7 +66,7 @@ void initialize_if_data(void)
void add_permitted_if(char *s) void add_permitted_if(char *s)
{ {
if (!s) if (!s)
return; return;
add_to_strlist(&okif, s); add_to_strlist(&okif, s);
} }
@@ -78,15 +77,15 @@ static int is_permitted(char *name)
/* If empty, permit all. */ /* If empty, permit all. */
if (!okif) if (!okif)
return 1; return 1;
if (!name || strlen(name) == 0) if (!name || strlen(name) == 0)
return 0; return 0;
p = okif; p = okif;
while (p) { while (p) {
if (strcmp(name, p->str) == 0) if (strcmp(name, p->str) == 0)
return 1; return 1;
p = p->next; p = p->next;
} }
log_line("attempt to modify interface %s denied\n", name); log_line("attempt to modify interface %s denied\n", name);
return 0; return 0;
@@ -101,24 +100,24 @@ int authorized_peer(int sk, pid_t pid, uid_t uid, gid_t gid)
/* No credentials to verify. */ /* No credentials to verify. */
if ( !(pid || uid || gid) ) if ( !(pid || uid || gid) )
return 1; return 1;
/* Verify that peer has authorized uid/gid/pid. */ /* Verify that peer has authorized uid/gid/pid. */
cl = sizeof(struct ucred); cl = sizeof(struct ucred);
if (getsockopt(sk, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != -1) { if (getsockopt(sk, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != -1) {
if ((pid == 0 || cr.pid == pid) || if ((pid == 0 || cr.pid == pid) ||
(uid == 0 || cr.uid == uid) || (uid == 0 || cr.uid == uid) ||
(gid == 0 || cr.gid == gid)) (gid == 0 || cr.gid == gid))
ret = 1; ret = 1;
} else } else
log_line("getsockopt returned an error: %s\n", strerror(errno)); log_line("getsockopt returned an error: %s\n", strerror(errno));
return ret; return ret;
} }
void perform_interface(int idx, char *str) void perform_interface(int idx, char *str)
{ {
if (!str) if (!str)
return; return;
/* Update interface name. */ /* Update interface name. */
memset(ifnam[idx], '\0', IFNAMSIZ); memset(ifnam[idx], '\0', IFNAMSIZ);
@@ -131,32 +130,32 @@ static int set_if_flag(int idx, short flag)
struct ifreq ifrt; struct ifreq ifrt;
if (!is_permitted(ifnam[idx])) if (!is_permitted(ifnam[idx]))
goto out0; goto out0;
fd = socket(PF_INET, SOCK_DGRAM, 0); fd = socket(PF_INET, SOCK_DGRAM, 0);
if (fd == -1) { if (fd == -1) {
log_line("%s: (set_if_flag) failed to open interface socket: %s\n", log_line("%s: (set_if_flag) failed to open interface socket: %s\n",
ifnam[idx], strerror(errno)); ifnam[idx], strerror(errno));
goto out0; goto out0;
} }
strlcpy(ifrt.ifr_name, ifnam[idx], IFNAMSIZ); strlcpy(ifrt.ifr_name, ifnam[idx], IFNAMSIZ);
if (ioctl(fd, SIOCGIFFLAGS, &ifrt) < 0) { if (ioctl(fd, SIOCGIFFLAGS, &ifrt) < 0) {
log_line("%s: unknown interface: %s\n", ifnam[idx], strerror(errno)); log_line("%s: unknown interface: %s\n", ifnam[idx], strerror(errno));
goto out1; goto out1;
} }
strlcpy(ifrt.ifr_name, ifnam[idx], IFNAMSIZ); strlcpy(ifrt.ifr_name, ifnam[idx], IFNAMSIZ);
ifrt.ifr_flags |= flag; ifrt.ifr_flags |= flag;
if (ioctl(fd, SIOCSIFFLAGS, &ifrt) < 0) { if (ioctl(fd, SIOCSIFFLAGS, &ifrt) < 0) {
log_line("%s: failed to set interface flags: %s\n", log_line("%s: failed to set interface flags: %s\n",
ifnam[idx], strerror(errno)); ifnam[idx], strerror(errno));
goto out1; goto out1;
} }
ret = 0; ret = 0;
out1: out1:
close(fd); close(fd);
out0: out0:
return ret; return ret;
} }
@@ -169,13 +168,13 @@ void perform_ip(int idx, char *str)
struct sockaddr_in sin; struct sockaddr_in sin;
if (!str) if (!str)
return; return;
if (!is_permitted(ifnam[idx])) if (!is_permitted(ifnam[idx]))
return; return;
if (!inet_aton(str, &ipaddr)) if (!inet_aton(str, &ipaddr))
return; return;
if (set_if_flag(idx, (IFF_UP | IFF_RUNNING))) if (set_if_flag(idx, (IFF_UP | IFF_RUNNING)))
return; return;
strlcpy(ifrt.ifr_name, ifnam[idx], IFNAMSIZ); strlcpy(ifrt.ifr_name, ifnam[idx], IFNAMSIZ);
memset(&sin, 0, sizeof(struct sockaddr)); memset(&sin, 0, sizeof(struct sockaddr));
@@ -185,13 +184,13 @@ void perform_ip(int idx, char *str)
fd = socket(PF_INET, SOCK_DGRAM, 0); fd = socket(PF_INET, SOCK_DGRAM, 0);
if (fd == -1) { if (fd == -1) {
log_line("%s: (perform_ip) failed to open interface socket: %s\n", log_line("%s: (perform_ip) failed to open interface socket: %s\n",
ifnam[idx], strerror(errno)); ifnam[idx], strerror(errno));
return; return;
} }
if (ioctl(fd, SIOCSIFADDR, &ifrt) < 0) if (ioctl(fd, SIOCSIFADDR, &ifrt) < 0)
log_line("%s: failed to configure IP: %s\n", log_line("%s: failed to configure IP: %s\n",
ifnam[idx], strerror(errno)); ifnam[idx], strerror(errno));
close(fd); close(fd);
} }
@@ -204,11 +203,11 @@ void perform_subnet(int idx, char *str)
struct sockaddr_in sin; struct sockaddr_in sin;
if (!str) if (!str)
return; return;
if (!is_permitted(ifnam[idx])) if (!is_permitted(ifnam[idx]))
return; return;
if (!inet_aton(str, &subnet)) if (!inet_aton(str, &subnet))
return; return;
strlcpy(ifrt.ifr_name, ifnam[idx], IFNAMSIZ); strlcpy(ifrt.ifr_name, ifnam[idx], IFNAMSIZ);
memset(&sin, 0, sizeof(struct sockaddr)); memset(&sin, 0, sizeof(struct sockaddr));
@@ -218,15 +217,15 @@ void perform_subnet(int idx, char *str)
fd = socket(PF_INET, SOCK_DGRAM, 0); fd = socket(PF_INET, SOCK_DGRAM, 0);
if (fd == -1) { if (fd == -1) {
log_line("%s: (perform_ip) failed to open interface socket: %s\n", log_line("%s: (perform_ip) failed to open interface socket: %s\n",
ifnam[idx], strerror(errno)); ifnam[idx], strerror(errno));
return; return;
} }
if (ioctl(fd, SIOCSIFNETMASK, &ifrt) < 0) { if (ioctl(fd, SIOCSIFNETMASK, &ifrt) < 0) {
sin.sin_addr.s_addr = 0xffffffff; sin.sin_addr.s_addr = 0xffffffff;
if (ioctl(fd, SIOCSIFNETMASK, &ifrt) < 0) if (ioctl(fd, SIOCSIFNETMASK, &ifrt) < 0)
log_line("%s: failed to configure subnet: %s\n", log_line("%s: failed to configure subnet: %s\n",
ifnam[idx], strerror(errno)); ifnam[idx], strerror(errno));
} }
close(fd); close(fd);
} }
@@ -241,11 +240,11 @@ void perform_router(int idx, char *str)
int fd; int fd;
if (!str) if (!str)
return; return;
if (!is_permitted(ifnam[idx])) if (!is_permitted(ifnam[idx]))
return; return;
if (!inet_aton(str, &router)) if (!inet_aton(str, &router))
return; return;
memset(&rt, 0, sizeof(struct rtentry)); memset(&rt, 0, sizeof(struct rtentry));
dest = (struct sockaddr_in *) &rt.rt_dst; dest = (struct sockaddr_in *) &rt.rt_dst;
@@ -265,12 +264,12 @@ void perform_router(int idx, char *str)
fd = socket(PF_INET, SOCK_DGRAM, 0); fd = socket(PF_INET, SOCK_DGRAM, 0);
if (fd == -1) { if (fd == -1) {
log_line("%s: (perform_router) failed to open interface socket: %s\n", log_line("%s: (perform_router) failed to open interface socket: %s\n",
ifnam[idx], strerror(errno)); ifnam[idx], strerror(errno));
return; return;
} }
if (ioctl(fd, SIOCADDRT, &rt)) if (ioctl(fd, SIOCADDRT, &rt))
log_line("%s: failed to set route: %s\n", ifnam[idx], strerror(errno)); log_line("%s: failed to set route: %s\n", ifnam[idx], strerror(errno));
close(fd); close(fd);
} }
@@ -281,9 +280,9 @@ void perform_mtu(int idx, char *str)
struct ifreq ifrt; struct ifreq ifrt;
if (!str) if (!str)
return; return;
if (!is_permitted(ifnam[idx])) if (!is_permitted(ifnam[idx]))
return; return;
mtu = strtol(str, NULL, 10); mtu = strtol(str, NULL, 10);
ifrt.ifr_mtu = mtu; ifrt.ifr_mtu = mtu;
@@ -291,13 +290,13 @@ void perform_mtu(int idx, char *str)
fd = socket(PF_INET, SOCK_DGRAM, 0); fd = socket(PF_INET, SOCK_DGRAM, 0);
if (fd == -1) { if (fd == -1) {
log_line("%s: (perform_mtu) failed to open interface socket: %s\n", log_line("%s: (perform_mtu) failed to open interface socket: %s\n",
ifnam[idx], strerror(errno)); ifnam[idx], strerror(errno));
return; return;
} }
if (ioctl(fd, SIOCSIFMTU, &ifrt) < 0) if (ioctl(fd, SIOCSIFMTU, &ifrt) < 0)
log_line("%s: failed to set MTU (%d): %s\n", ifnam[idx], mtu, log_line("%s: failed to set MTU (%d): %s\n", ifnam[idx], mtu,
strerror(errno)); strerror(errno));
close(fd); close(fd);
} }
@@ -309,11 +308,11 @@ void perform_broadcast(int idx, char *str)
struct sockaddr_in sin; struct sockaddr_in sin;
if (!str) if (!str)
return; return;
if (!is_permitted(ifnam[idx])) if (!is_permitted(ifnam[idx]))
return; return;
if (!inet_aton(str, &broadcast)) if (!inet_aton(str, &broadcast))
return; return;
strlcpy(ifrt.ifr_name, ifnam[idx], IFNAMSIZ); strlcpy(ifrt.ifr_name, ifnam[idx], IFNAMSIZ);
memset(&sin, 0, sizeof(struct sockaddr)); memset(&sin, 0, sizeof(struct sockaddr));
@@ -323,11 +322,11 @@ void perform_broadcast(int idx, char *str)
fd = socket(PF_INET, SOCK_DGRAM, 0); fd = socket(PF_INET, SOCK_DGRAM, 0);
if (fd == -1) { if (fd == -1) {
log_line("%s: (perform_broadcast) failed to open interface socket: %s\n", ifnam[idx], strerror(errno)); log_line("%s: (perform_broadcast) failed to open interface socket: %s\n", ifnam[idx], strerror(errno));
return; return;
} }
if (ioctl(fd, SIOCSIFBRDADDR, &ifrt) < 0) if (ioctl(fd, SIOCSIFBRDADDR, &ifrt) < 0)
log_line("%s: failed to set broadcast: %s\n", log_line("%s: failed to set broadcast: %s\n",
ifnam[idx], strerror(errno)); ifnam[idx], strerror(errno));
close(fd); close(fd);
} }

View File

@@ -1,7 +1,7 @@
/* linux.h - ifchd Linux-specific functions include /* linux.h - ifchd Linux-specific functions include
* Time-stamp: <2010-11-12 09:03:29 njk> * Time-stamp: <2010-11-12 14:31:33 njk>
* *
* (C) 2004 Nicholas J. Kain <njk@aerifal.cx> * (C) 2004-2010 Nicholas J. Kain <njkain at gmail dot com>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -16,11 +16,10 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/ */
#ifndef NJK_IFCHD_LINUX_H_ #ifndef NJK_IFCHD_LINUX_H_
#define NJK_IFCHD_LINUX_H_ 1 #define NJK_IFCHD_LINUX_H_
void clear_if_data(int idx); void clear_if_data(int idx);
void initialize_if_data(void); void initialize_if_data(void);
void add_permitted_if(char *s); void add_permitted_if(char *s);

View File

@@ -2,6 +2,7 @@
* *
* Packet generation and dispatching functions for the DHCP client. * Packet generation and dispatching functions for the DHCP client.
* *
* Nicholas J. Kain <njkain at gmail dot com> 2004-2010
* Russ Dill <Russ.Dill@asu.edu> July 2001 * Russ Dill <Russ.Dill@asu.edu> July 2001
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
@@ -18,7 +19,7 @@
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/ */
#include <string.h> #include <string.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <features.h> #include <features.h>
@@ -43,256 +44,246 @@
/* Create a random xid */ /* Create a random xid */
unsigned long random_xid(void) unsigned long random_xid(void)
{ {
static int initialized; static int initialized;
if (!initialized) { if (!initialized) {
int fd; int fd;
unsigned long seed; unsigned long seed;
fd = open("/dev/urandom", O_RDONLY); fd = open("/dev/urandom", O_RDONLY);
if (fd == -1 || read(fd, &seed, sizeof(seed)) < 0) { if (fd == -1 || read(fd, &seed, sizeof(seed)) < 0) {
log_warning("Could not load seed from /dev/urandom: %s", log_warning("Could not load seed from /dev/urandom: %s",
strerror(errno)); strerror(errno));
seed = time(0); seed = time(0);
} }
if (fd != -1) if (fd != -1)
close(fd); close(fd);
srand(seed); srand(seed);
initialized++; initialized++;
} }
return rand(); return rand();
} }
/* initialize a packet with the proper defaults */ /* initialize a packet with the proper defaults */
static void init_packet(struct dhcpMessage *packet, char type) static void init_packet(struct dhcpMessage *packet, char type)
{ {
struct vendor { struct vendor {
char vendor; char vendor;
char length; char length;
char str[sizeof("ndhc")]; char str[sizeof("ndhc")];
} vendor_id = { DHCP_VENDOR, sizeof("ndhc") - 1, "ndhc"}; } vendor_id = { DHCP_VENDOR, sizeof("ndhc") - 1, "ndhc"};
init_header(packet, type);
memcpy(packet->chaddr, client_config.arp, 6);
add_option_string(packet->options, client_config.clientid);
if (client_config.hostname)
add_option_string(packet->options, client_config.hostname);
add_option_string(packet->options, (unsigned char *)&vendor_id);
}
init_header(packet, type);
memcpy(packet->chaddr, client_config.arp, 6);
add_option_string(packet->options, client_config.clientid);
if (client_config.hostname)
add_option_string(packet->options, client_config.hostname);
add_option_string(packet->options, (unsigned char *)&vendor_id);
}
/* Add a paramater request list for stubborn DHCP servers. Pull the data /* Add a paramater request list for stubborn DHCP servers. Pull the data
* from the struct in options.c. Don't do bounds checking here because it * from the struct in options.c. Don't do bounds checking here because it
* goes towards the head of the packet. */ * goes towards the head of the packet. */
static void add_requests(struct dhcpMessage *packet) static void add_requests(struct dhcpMessage *packet)
{ {
int end = end_option(packet->options); int end = end_option(packet->options);
int i, len = 0; int i, len = 0;
packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
for (i = 0; options[i].code; i++)
if (options[i].flags & OPTION_REQ)
packet->options[end + OPT_DATA + len++] = options[i].code;
packet->options[end + OPT_LEN] = len;
packet->options[end + OPT_DATA + len] = DHCP_END;
packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
for (i = 0; options[i].code; i++)
if (options[i].flags & OPTION_REQ)
packet->options[end + OPT_DATA + len++] = options[i].code;
packet->options[end + OPT_LEN] = len;
packet->options[end + OPT_DATA + len] = DHCP_END;
} }
/* Broadcast a DHCP discover packet to the network, with an optionally /* Broadcast a DHCP discover packet to the network, with an optionally
* requested IP */ * requested IP */
int send_discover(unsigned long xid, unsigned long requested) int send_discover(unsigned long xid, unsigned long requested)
{ {
struct dhcpMessage packet; struct dhcpMessage packet;
init_packet(&packet, DHCPDISCOVER); init_packet(&packet, DHCPDISCOVER);
packet.xid = xid; packet.xid = xid;
if (requested) if (requested)
add_simple_option(packet.options, DHCP_REQUESTED_IP, requested); add_simple_option(packet.options, DHCP_REQUESTED_IP, requested);
add_requests(&packet); add_requests(&packet);
log_line("Sending discover..."); log_line("Sending discover...");
return raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST, return raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST,
SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex); SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex);
} }
/* Broadcasts a DHCP request message */ /* Broadcasts a DHCP request message */
int send_selecting(unsigned long xid, unsigned long server, int send_selecting(unsigned long xid, unsigned long server,
unsigned long requested) unsigned long requested)
{ {
struct dhcpMessage packet; struct dhcpMessage packet;
struct in_addr addr; struct in_addr addr;
init_packet(&packet, DHCPREQUEST); init_packet(&packet, DHCPREQUEST);
packet.xid = xid; packet.xid = xid;
add_simple_option(packet.options, DHCP_REQUESTED_IP, requested); add_simple_option(packet.options, DHCP_REQUESTED_IP, requested);
add_simple_option(packet.options, DHCP_SERVER_ID, server); add_simple_option(packet.options, DHCP_SERVER_ID, server);
add_requests(&packet); add_requests(&packet);
addr.s_addr = requested; addr.s_addr = requested;
log_line("Sending select for %s...", inet_ntoa(addr)); log_line("Sending select for %s...", inet_ntoa(addr));
return raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST, return raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST,
SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex); SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex);
} }
/* Unicasts or broadcasts a DHCP renew message */ /* Unicasts or broadcasts a DHCP renew message */
int send_renew(unsigned long xid, unsigned long server, unsigned long ciaddr) int send_renew(unsigned long xid, unsigned long server, unsigned long ciaddr)
{ {
struct dhcpMessage packet; struct dhcpMessage packet;
int ret = 0; int ret = 0;
init_packet(&packet, DHCPREQUEST); init_packet(&packet, DHCPREQUEST);
packet.xid = xid; packet.xid = xid;
packet.ciaddr = ciaddr; packet.ciaddr = ciaddr;
add_requests(&packet);
log_line("Sending renew...");
if (server)
ret = kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT);
else
ret = raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST,
SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex);
return ret;
}
add_requests(&packet);
log_line("Sending renew...");
if (server)
ret = kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT);
else
ret = raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST,
SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex);
return ret;
}
/* Unicasts a DHCP release message */ /* Unicasts a DHCP release message */
int send_release(unsigned long server, unsigned long ciaddr) int send_release(unsigned long server, unsigned long ciaddr)
{ {
struct dhcpMessage packet; struct dhcpMessage packet;
init_packet(&packet, DHCPRELEASE); init_packet(&packet, DHCPRELEASE);
packet.xid = random_xid(); packet.xid = random_xid();
packet.ciaddr = ciaddr; packet.ciaddr = ciaddr;
add_simple_option(packet.options, DHCP_REQUESTED_IP, ciaddr);
add_simple_option(packet.options, DHCP_SERVER_ID, server);
log_line("Sending release..."); add_simple_option(packet.options, DHCP_REQUESTED_IP, ciaddr);
return kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT); add_simple_option(packet.options, DHCP_SERVER_ID, server);
log_line("Sending release...");
return kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT);
} }
/* return -1 on errors that are fatal for the socket, /* return -1 on errors that are fatal for the socket,
* -2 for those that aren't */ * -2 for those that aren't */
int get_raw_packet(struct dhcpMessage *payload, int fd) int get_raw_packet(struct dhcpMessage *payload, int fd)
{ {
struct udp_dhcp_packet packet; struct udp_dhcp_packet packet;
uint32_t source, dest; uint32_t source, dest;
uint16_t check; uint16_t check;
ssize_t len = 0; ssize_t len = 0;
const ssize_t wanted = sizeof(struct iphdr) + sizeof(struct udphdr); const ssize_t wanted = sizeof(struct iphdr) + sizeof(struct udphdr);
memset(&packet, 0, sizeof(struct udp_dhcp_packet)); memset(&packet, 0, sizeof(struct udp_dhcp_packet));
while (len < wanted) { while (len < wanted) {
ssize_t r = read(fd, &packet + len, ssize_t r = read(fd, &packet + len,
sizeof(struct udp_dhcp_packet) - len); sizeof(struct udp_dhcp_packet) - len);
if (r == 0) if (r == 0)
break; break;
if (r == -1) { if (r == -1) {
if (errno == EINTR) if (errno == EINTR)
continue; continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) { if (errno == EAGAIN || errno == EWOULDBLOCK) {
log_line("EAGAIN or EWOULDBLOCK hit"); log_line("EAGAIN or EWOULDBLOCK hit");
break; break;
} }
log_line("couldn't read on raw listening socket -- ignoring"); log_line("couldn't read on raw listening socket -- ignoring");
usleep(500000); /* possible down interface, looping condition */ usleep(500000); /* possible down interface, looping condition */
return -1; return -1;
} }
len += r; len += r;
} }
if (len == 0) { if (len == 0) {
usleep(50000); usleep(50000);
return -2; return -2;
} }
log_line("len: %d wanted: %d", len, wanted); log_line("len: %d wanted: %d", len, wanted);
if (len < wanted) { if (len < wanted) {
log_line("Message too short to contain IP + UDP headers, ignoring"); log_line("Message too short to contain IP + UDP headers, ignoring");
sleep(1); sleep(1);
return -2; return -2;
} }
if (len < ntohs(packet.ip.tot_len)) {
log_line("Truncated packet");
return -2;
}
/* ignore any extra garbage bytes */
len = ntohs(packet.ip.tot_len);
/* Make sure its the right packet for us, and that it passes
* sanity checks */
if (packet.ip.protocol != IPPROTO_UDP) {
log_line("IP header is not UDP");
sleep(1);
return -2;
}
if (packet.ip.version != IPVERSION) {
log_line("IP version is not IPv4");
sleep(1);
return -2;
}
if (packet.ip.ihl != sizeof(packet.ip) >> 2) {
log_line("IP header length incorrect");
sleep(1);
return -2;
}
if (packet.udp.dest != htons(CLIENT_PORT)) {
log_line("UDP destination port incorrect");
sleep(1);
return -2;
}
if (len > (int)sizeof(struct udp_dhcp_packet)) {
log_line("Data longer than that of a IP+UDP+DHCP message");
sleep(1);
return -2;
}
if (ntohs(packet.udp.len) != (short)(len - sizeof(packet.ip))) {
log_line("UDP header length incorrect");
sleep(1);
return -2;
}
/* check IP checksum */ if (len < ntohs(packet.ip.tot_len)) {
check = packet.ip.check; log_line("Truncated packet");
packet.ip.check = 0; return -2;
if (check != checksum(&(packet.ip), sizeof(packet.ip))) { }
log_line("bad IP header checksum, ignoring");
return -1;
}
/* verify the UDP checksum by replacing the header with a psuedo header */
source = packet.ip.saddr;
dest = packet.ip.daddr;
check = packet.udp.check;
packet.udp.check = 0;
memset(&packet.ip, 0, sizeof(packet.ip));
packet.ip.protocol = IPPROTO_UDP; /* ignore any extra garbage bytes */
packet.ip.saddr = source; len = ntohs(packet.ip.tot_len);
packet.ip.daddr = dest;
packet.ip.tot_len = packet.udp.len; /* cheat on the psuedo-header */ /* Make sure its the right packet for us, and that it passes
if (check && check != checksum(&packet, len)) { * sanity checks */
log_error("packet with bad UDP checksum received, ignoring"); if (packet.ip.protocol != IPPROTO_UDP) {
return -2; log_line("IP header is not UDP");
} sleep(1);
return -2;
memcpy(payload, &(packet.data), }
len - (sizeof(packet.ip) + sizeof(packet.udp))); if (packet.ip.version != IPVERSION) {
log_line("IP version is not IPv4");
if (ntohl(payload->cookie) != DHCP_MAGIC) { sleep(1);
log_error("received bogus message (bad magic) -- ignoring"); return -2;
return -2; }
} if (packet.ip.ihl != sizeof(packet.ip) >> 2) {
log_line("oooooh!!! got some!"); log_line("IP header length incorrect");
return len - (sizeof(packet.ip) + sizeof(packet.udp)); sleep(1);
return -2;
}
if (packet.udp.dest != htons(CLIENT_PORT)) {
log_line("UDP destination port incorrect");
sleep(1);
return -2;
}
if (len > (int)sizeof(struct udp_dhcp_packet)) {
log_line("Data longer than that of a IP+UDP+DHCP message");
sleep(1);
return -2;
}
if (ntohs(packet.udp.len) != (short)(len - sizeof(packet.ip))) {
log_line("UDP header length incorrect");
sleep(1);
return -2;
}
/* check IP checksum */
check = packet.ip.check;
packet.ip.check = 0;
if (check != checksum(&(packet.ip), sizeof(packet.ip))) {
log_line("bad IP header checksum, ignoring");
return -1;
}
/* verify the UDP checksum by replacing the header with a psuedo header */
source = packet.ip.saddr;
dest = packet.ip.daddr;
check = packet.udp.check;
packet.udp.check = 0;
memset(&packet.ip, 0, sizeof(packet.ip));
packet.ip.protocol = IPPROTO_UDP;
packet.ip.saddr = source;
packet.ip.daddr = dest;
packet.ip.tot_len = packet.udp.len; /* cheat on the psuedo-header */
if (check && check != checksum(&packet, len)) {
log_error("packet with bad UDP checksum received, ignoring");
return -2;
}
memcpy(payload, &(packet.data),
len - (sizeof(packet.ip) + sizeof(packet.udp)));
if (ntohl(payload->cookie) != DHCP_MAGIC) {
log_error("received bogus message (bad magic) -- ignoring");
return -2;
}
log_line("oooooh!!! got some!");
return len - (sizeof(packet.ip) + sizeof(packet.udp));
} }

View File

@@ -2,8 +2,8 @@
* *
* ndhc DHCP client * ndhc DHCP client
* *
* Nicholas J. Kain <njkain at gmail dot com> 2004-2010
* Russ Dill <Russ.Dill@asu.edu> July 2001 * Russ Dill <Russ.Dill@asu.edu> July 2001
* Nicholas Kain <njk@-N0SPaM-.kain.us> 2004
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -19,7 +19,7 @@
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/ */
#include <stdio.h> #include <stdio.h>
#include <sys/time.h> #include <sys/time.h>
#include <sys/types.h> #include <sys/types.h>
@@ -60,28 +60,28 @@ static int state, packet_num, fd, listen_mode;
static sig_atomic_t pending_exit, pending_renew, pending_release; static sig_atomic_t pending_exit, pending_renew, pending_release;
enum { enum {
LISTEN_NONE, LISTEN_NONE,
LISTEN_KERNEL, LISTEN_KERNEL,
LISTEN_RAW LISTEN_RAW
}; };
struct client_config_t client_config = { struct client_config_t client_config = {
/* Default options. */ /* Default options. */
.abort_if_no_lease = 0, .abort_if_no_lease = 0,
.foreground = 0, .foreground = 0,
.quit_after_lease = 0, .quit_after_lease = 0,
.background_if_no_lease = 0, .background_if_no_lease = 0,
.interface = "eth0", .interface = "eth0",
.script = "none", .script = "none",
.clientid = NULL, .clientid = NULL,
.hostname = NULL, .hostname = NULL,
.ifindex = 0, .ifindex = 0,
.arp = "\0", .arp = "\0",
}; };
static void show_usage(void) static void show_usage(void)
{ {
printf( printf(
"Usage: ndhc [OPTIONS]\n\n" "Usage: ndhc [OPTIONS]\n\n"
" -c, --clientid=CLIENTID Client identifier\n" " -c, --clientid=CLIENTID Client identifier\n"
" -H, --hostname=HOSTNAME Client hostname\n" " -H, --hostname=HOSTNAME Client hostname\n"
@@ -97,495 +97,494 @@ static void show_usage(void)
" -u, --user Change privileges to this user\n" " -u, --user Change privileges to this user\n"
" -C, --chroot Directory to which udhcp should chroot\n" " -C, --chroot Directory to which udhcp should chroot\n"
" -v, --version Display version\n" " -v, --version Display version\n"
); );
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }
/* just a little helper */ /* just a little helper */
static void change_mode(int new_mode) static void change_mode(int new_mode)
{ {
log_line("entering %s listen mode", log_line("entering %s listen mode",
new_mode ? (new_mode == 1 ? "kernel" : "raw") : "none"); new_mode ? (new_mode == 1 ? "kernel" : "raw") : "none");
close(fd); close(fd);
fd = -1; fd = -1;
listen_mode = new_mode; listen_mode = new_mode;
} }
/* perform a renew */ /* perform a renew */
static void perform_renew(void) static void perform_renew(void)
{ {
log_line("Performing a DHCP renew..."); log_line("Performing a DHCP renew...");
switch (state) { switch (state) {
case BOUND: case BOUND:
change_mode(LISTEN_KERNEL); change_mode(LISTEN_KERNEL);
case RENEWING: case RENEWING:
case REBINDING: case REBINDING:
state = RENEW_REQUESTED; state = RENEW_REQUESTED;
break; break;
case RENEW_REQUESTED: /* impatient are we? fine, square 1 */ case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
run_script(NULL, SCRIPT_DECONFIG); run_script(NULL, SCRIPT_DECONFIG);
case REQUESTING: case REQUESTING:
case RELEASED: case RELEASED:
change_mode(LISTEN_RAW); change_mode(LISTEN_RAW);
state = INIT_SELECTING; state = INIT_SELECTING;
break; break;
case INIT_SELECTING: case INIT_SELECTING:
break; break;
} }
/* start things over */ /* start things over */
packet_num = 0; packet_num = 0;
/* Kill any timeouts because the user wants this to hurry along */ /* Kill any timeouts because the user wants this to hurry along */
timeout = 0; timeout = 0;
} }
/* perform a release */ /* perform a release */
static void perform_release(void) static void perform_release(void)
{ {
char buf[32]; char buf[32];
struct in_addr temp_addr; struct in_addr temp_addr;
memset(buf, '\0', sizeof buf); memset(buf, '\0', sizeof buf);
/* send release packet */ /* send release packet */
if (state == BOUND || state == RENEWING || state == REBINDING) { if (state == BOUND || state == RENEWING || state == REBINDING) {
temp_addr.s_addr = server_addr; temp_addr.s_addr = server_addr;
snprintf(buf, sizeof buf, "%s", inet_ntoa(temp_addr)); snprintf(buf, sizeof buf, "%s", inet_ntoa(temp_addr));
temp_addr.s_addr = requested_ip; temp_addr.s_addr = requested_ip;
log_line("Unicasting a release of %s to %s.", log_line("Unicasting a release of %s to %s.",
inet_ntoa(temp_addr), buf); inet_ntoa(temp_addr), buf);
send_release(server_addr, requested_ip); /* unicast */ send_release(server_addr, requested_ip); /* unicast */
run_script(NULL, SCRIPT_DECONFIG); run_script(NULL, SCRIPT_DECONFIG);
} }
log_line("Entering released state."); log_line("Entering released state.");
change_mode(LISTEN_NONE); change_mode(LISTEN_NONE);
state = RELEASED; state = RELEASED;
timeout = 0x7fffffff; timeout = 0x7fffffff;
} }
static void signal_handler(int sig) static void signal_handler(int sig)
{ {
switch (sig) { switch (sig) {
case SIGUSR1: case SIGUSR1:
pending_renew = 1; pending_renew = 1;
break; break;
case SIGUSR2: case SIGUSR2:
pending_release = 1; pending_release = 1;
break; break;
case SIGTERM: case SIGTERM:
pending_exit = 1; pending_exit = 1;
break; break;
} }
} }
static void background(void) static void background(void)
{ {
if (daemon(0, 0) == -1) { if (daemon(0, 0) == -1) {
perror("fork"); perror("fork");
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }
client_config.foreground = 1; /* Do not fork again. */ client_config.foreground = 1; /* Do not fork again. */
} }
static void handle_timeout(void) static void handle_timeout(void)
{ {
time_t now = time(0); time_t now = time(0);
/* timeout dropped to zero */ /* timeout dropped to zero */
switch (state) { switch (state) {
case INIT_SELECTING: case INIT_SELECTING:
if (packet_num < 3) { if (packet_num < 3) {
if (packet_num == 0) if (packet_num == 0)
xid = random_xid(); xid = random_xid();
/* send discover packet */ /* send discover packet */
send_discover(xid, requested_ip); /* broadcast */ send_discover(xid, requested_ip); /* broadcast */
timeout = now + ((packet_num == 2) ? 4 : 2); timeout = now + ((packet_num == 2) ? 4 : 2);
packet_num++; packet_num++;
} else { } else {
if (client_config.background_if_no_lease) { if (client_config.background_if_no_lease) {
log_line("No lease, going to background."); log_line("No lease, going to background.");
background(); background();
} else if (client_config.abort_if_no_lease) { } else if (client_config.abort_if_no_lease) {
log_line("No lease, failing."); log_line("No lease, failing.");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
/* wait to try again */ /* wait to try again */
packet_num = 0; packet_num = 0;
timeout = now + 60; timeout = now + 60;
} }
break; break;
case RENEW_REQUESTED: case RENEW_REQUESTED:
case REQUESTING: case REQUESTING:
if (packet_num < 3) { if (packet_num < 3) {
/* send request packet */ /* send request packet */
if (state == RENEW_REQUESTED) if (state == RENEW_REQUESTED)
/* unicast */ /* unicast */
send_renew(xid, server_addr, requested_ip); send_renew(xid, server_addr, requested_ip);
else else
/* broadcast */ /* broadcast */
send_selecting(xid, server_addr, requested_ip); send_selecting(xid, server_addr, requested_ip);
timeout = now + ((packet_num == 2) ? 10 : 2); timeout = now + ((packet_num == 2) ? 10 : 2);
packet_num++; packet_num++;
} else { } else {
/* timed out, go back to init state */ /* timed out, go back to init state */
if (state == RENEW_REQUESTED) if (state == RENEW_REQUESTED)
run_script(NULL, SCRIPT_DECONFIG); run_script(NULL, SCRIPT_DECONFIG);
state = INIT_SELECTING; state = INIT_SELECTING;
timeout = now; timeout = now;
packet_num = 0; packet_num = 0;
change_mode(LISTEN_RAW); change_mode(LISTEN_RAW);
} }
break; break;
case BOUND: case BOUND:
/* Lease is starting to run out, time to enter renewing state */ /* Lease is starting to run out, time to enter renewing state */
state = RENEWING; state = RENEWING;
change_mode(LISTEN_KERNEL); change_mode(LISTEN_KERNEL);
log_line("Entering renew state."); log_line("Entering renew state.");
/* fall right through */ /* fall right through */
case RENEWING: case RENEWING:
/* Either set a new T1, or enter REBINDING state */ /* Either set a new T1, or enter REBINDING state */
if ((t2 - t1) <= (lease / 14400 + 1)) { if ((t2 - t1) <= (lease / 14400 + 1)) {
/* timed out, enter rebinding state */ /* timed out, enter rebinding state */
state = REBINDING; state = REBINDING;
timeout = now + (t2 - t1); timeout = now + (t2 - t1);
log_line("Entering rebinding state."); log_line("Entering rebinding state.");
} else { } else {
/* send a request packet */ /* send a request packet */
send_renew(xid, server_addr, requested_ip); /* unicast */ send_renew(xid, server_addr, requested_ip); /* unicast */
t1 = ((t2 - t1) >> 1) + t1; t1 = ((t2 - t1) >> 1) + t1;
timeout = t1 + start; timeout = t1 + start;
} }
break; break;
case REBINDING: case REBINDING:
/* Either set a new T2, or enter INIT state */ /* Either set a new T2, or enter INIT state */
if ((lease - t2) <= (lease / 14400 + 1)) { if ((lease - t2) <= (lease / 14400 + 1)) {
/* timed out, enter init state */ /* timed out, enter init state */
state = INIT_SELECTING; state = INIT_SELECTING;
log_line("Lease lost, entering init state."); log_line("Lease lost, entering init state.");
run_script(NULL, SCRIPT_DECONFIG); run_script(NULL, SCRIPT_DECONFIG);
timeout = now; timeout = now;
packet_num = 0; packet_num = 0;
change_mode(LISTEN_RAW); change_mode(LISTEN_RAW);
} else { } else {
/* send a request packet */ /* send a request packet */
send_renew(xid, 0, requested_ip); /* broadcast */ send_renew(xid, 0, requested_ip); /* broadcast */
t2 = ((lease - t2) >> 1) + t2; t2 = ((lease - t2) >> 1) + t2;
timeout = t2 + start; timeout = t2 + start;
} }
break; break;
case RELEASED: case RELEASED:
/* yah, I know, *you* say it would never happen */ /* yah, I know, *you* say it would never happen */
timeout = 0x7fffffff; timeout = 0x7fffffff;
break; break;
} }
} }
static void handle_packet(void) static void handle_packet(void)
{ {
unsigned char *temp = NULL, *message = NULL; unsigned char *temp = NULL, *message = NULL;
int len; int len;
time_t now = time(0); time_t now = time(0);
struct in_addr temp_addr; struct in_addr temp_addr;
struct dhcpMessage packet; struct dhcpMessage packet;
log_line("got a packet");
if (listen_mode == LISTEN_KERNEL) log_line("got a packet");
len = get_packet(&packet, fd);
else
len = get_raw_packet(&packet, fd);
if (len == -1 && errno != EINTR) { if (listen_mode == LISTEN_KERNEL)
log_error("error on read, %s, reopening socket.", len = get_packet(&packet, fd);
strerror(errno)); else
change_mode(listen_mode); /* just close and reopen */ len = get_raw_packet(&packet, fd);
}
if (len < 0) if (len == -1 && errno != EINTR) {
return; log_error("error on read, %s, reopening socket.",
strerror(errno));
change_mode(listen_mode); /* just close and reopen */
}
if (packet.xid != xid) { if (len < 0)
log_line("Ignoring XID %lx (our xid is %lx).", return;
(unsigned long) packet.xid, xid);
return;
}
if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) { if (packet.xid != xid) {
log_line("couldnt get option from packet -- ignoring"); log_line("Ignoring XID %lx (our xid is %lx).",
return; (unsigned long) packet.xid, xid);
} return;
}
switch (state) { if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) {
case INIT_SELECTING: log_line("couldnt get option from packet -- ignoring");
/* Must be a DHCPOFFER to one of our xid's */ return;
if (*message == DHCPOFFER) { }
if ((temp = get_option(&packet, DHCP_SERVER_ID))) {
memcpy(&server_addr, temp, 4);
xid = packet.xid;
requested_ip = packet.yiaddr;
/* enter requesting state */ switch (state) {
state = REQUESTING; case INIT_SELECTING:
timeout = now; /* Must be a DHCPOFFER to one of our xid's */
packet_num = 0; if (*message == DHCPOFFER) {
} else { if ((temp = get_option(&packet, DHCP_SERVER_ID))) {
log_line("No server ID in message"); memcpy(&server_addr, temp, 4);
} xid = packet.xid;
} requested_ip = packet.yiaddr;
break;
case RENEW_REQUESTED:
case REQUESTING:
case RENEWING:
case REBINDING:
if (*message == DHCPACK) {
if (!(temp = get_option(&packet, DHCP_LEASE_TIME))) {
log_line("No lease time received, assuming 1h.");
lease = 60 * 60;
} else {
memcpy(&lease, temp, 4);
lease = ntohl(lease);
}
/* enter bound state */ /* enter requesting state */
t1 = lease >> 1; state = REQUESTING;
timeout = now;
packet_num = 0;
} else {
log_line("No server ID in message");
}
}
break;
case RENEW_REQUESTED:
case REQUESTING:
case RENEWING:
case REBINDING:
if (*message == DHCPACK) {
if (!(temp = get_option(&packet, DHCP_LEASE_TIME))) {
log_line("No lease time received, assuming 1h.");
lease = 60 * 60;
} else {
memcpy(&lease, temp, 4);
lease = ntohl(lease);
}
/* little fixed point for n * .875 */ /* enter bound state */
t2 = (lease * 0x7) >> 3; t1 = lease >> 1;
temp_addr.s_addr = packet.yiaddr;
log_line("Lease of %s obtained, lease time %ld.",
inet_ntoa(temp_addr), lease);
start = now;
timeout = t1 + start;
requested_ip = packet.yiaddr;
run_script(&packet,
((state == RENEWING || state == REBINDING)
? SCRIPT_RENEW : SCRIPT_BOUND));
state = BOUND; /* little fixed point for n * .875 */
change_mode(LISTEN_NONE); t2 = (lease * 0x7) >> 3;
if (client_config.quit_after_lease) temp_addr.s_addr = packet.yiaddr;
exit(EXIT_SUCCESS); log_line("Lease of %s obtained, lease time %ld.",
if (!client_config.foreground) inet_ntoa(temp_addr), lease);
background(); start = now;
timeout = t1 + start;
requested_ip = packet.yiaddr;
run_script(&packet,
((state == RENEWING || state == REBINDING)
? SCRIPT_RENEW : SCRIPT_BOUND));
} else if (*message == DHCPNAK) { state = BOUND;
/* return to init state */ change_mode(LISTEN_NONE);
log_line("Received DHCP NAK."); if (client_config.quit_after_lease)
run_script(&packet, SCRIPT_NAK); exit(EXIT_SUCCESS);
if (state != REQUESTING) if (!client_config.foreground)
run_script(NULL, SCRIPT_DECONFIG); background();
state = INIT_SELECTING;
timeout = now; } else if (*message == DHCPNAK) {
requested_ip = 0; /* return to init state */
packet_num = 0; log_line("Received DHCP NAK.");
change_mode(LISTEN_RAW); run_script(&packet, SCRIPT_NAK);
sleep(3); /* avoid excessive network traffic */ if (state != REQUESTING)
} run_script(NULL, SCRIPT_DECONFIG);
break; state = INIT_SELECTING;
case BOUND: timeout = now;
case RELEASED: requested_ip = 0;
default: packet_num = 0;
break; change_mode(LISTEN_RAW);
} sleep(3); /* avoid excessive network traffic */
}
break;
case BOUND:
case RELEASED:
default:
break;
}
} }
static int do_work(void) static int do_work(void)
{ {
struct timeval tv; struct timeval tv;
fd_set rfds; fd_set rfds;
for (;;) { for (;;) {
/* Handle signals asynchronously. */ /* Handle signals asynchronously. */
if (pending_renew) if (pending_renew)
perform_renew(); perform_renew();
if (pending_release) if (pending_release)
perform_release(); perform_release();
if (pending_exit) { if (pending_exit) {
log_line("Received SIGTERM. Exiting gracefully."); log_line("Received SIGTERM. Exiting gracefully.");
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }
tv.tv_sec = timeout - time(0); tv.tv_sec = timeout - time(0);
tv.tv_usec = 0; tv.tv_usec = 0;
if (listen_mode != LISTEN_NONE && fd < 0) { if (listen_mode != LISTEN_NONE && fd < 0) {
if (listen_mode == LISTEN_KERNEL) if (listen_mode == LISTEN_KERNEL)
fd = listen_socket(INADDR_ANY, CLIENT_PORT, fd = listen_socket(INADDR_ANY, CLIENT_PORT,
client_config.interface); client_config.interface);
else else
fd = raw_socket(client_config.ifindex); fd = raw_socket(client_config.ifindex);
if (fd < 0) { if (fd < 0) {
log_error("FATAL: couldn't listen on socket: %s.", log_error("FATAL: couldn't listen on socket: %s.",
strerror(errno)); strerror(errno));
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
if (tv.tv_sec <= 0) { if (tv.tv_sec <= 0) {
handle_timeout(); handle_timeout();
continue; continue;
} }
FD_ZERO(&rfds); FD_ZERO(&rfds);
if (fd >= 0) if (fd >= 0)
FD_SET(fd, &rfds); FD_SET(fd, &rfds);
if (select(fd + 1, &rfds, NULL, NULL, &tv) == -1) { if (select(fd + 1, &rfds, NULL, NULL, &tv) == -1) {
switch (errno) { switch (errno) {
case EBADF: case EBADF:
fd = -1; fd = -1;
default: default:
log_error("Error: \"%s\" on select!", log_error("Error: \"%s\" on select!",
strerror(errno)); strerror(errno));
case EINTR: /* Signal received, go back to top. */ case EINTR: /* Signal received, go back to top. */
continue; continue;
} }
} }
if (listen_mode != LISTEN_NONE && FD_ISSET(fd, &rfds)) if (listen_mode != LISTEN_NONE && FD_ISSET(fd, &rfds))
handle_packet(); handle_packet();
} }
} }
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
char chroot_dir[255]; char chroot_dir[255];
int c, len; int c, len;
struct passwd *pwd; struct passwd *pwd;
uid_t uid = 0; uid_t uid = 0;
gid_t gid = 0; gid_t gid = 0;
static struct option arg_options[] = { static struct option arg_options[] = {
{"clientid", required_argument, 0, 'c'}, {"clientid", required_argument, 0, 'c'},
{"foreground", no_argument, 0, 'f'}, {"foreground", no_argument, 0, 'f'},
{"background", no_argument, 0, 'b'}, {"background", no_argument, 0, 'b'},
{"hostname", required_argument, 0, 'H'}, {"hostname", required_argument, 0, 'H'},
{"hostname", required_argument, 0, 'h'}, {"hostname", required_argument, 0, 'h'},
{"interface", required_argument, 0, 'i'}, {"interface", required_argument, 0, 'i'},
{"now", no_argument, 0, 'n'}, {"now", no_argument, 0, 'n'},
{"quit", no_argument, 0, 'q'}, {"quit", no_argument, 0, 'q'},
{"request", required_argument, 0, 'r'}, {"request", required_argument, 0, 'r'},
{"version", no_argument, 0, 'v'}, {"version", no_argument, 0, 'v'},
{"user", required_argument, 0, 'u'}, {"user", required_argument, 0, 'u'},
{"chroot", required_argument, 0, 'C'}, {"chroot", required_argument, 0, 'C'},
{"help", no_argument, 0, '?'}, {"help", no_argument, 0, '?'},
{0, 0, 0, 0} {0, 0, 0, 0}
}; };
/* get options */ /* get options */
while (1) { while (1) {
int option_index = 0; int option_index = 0;
c = getopt_long(argc, argv, "c:fbH:h:i:np:qr:u:C:v", arg_options, c = getopt_long(argc, argv, "c:fbH:h:i:np:qr:u:C:v", arg_options,
&option_index); &option_index);
if (c == -1) break; if (c == -1) break;
switch (c) {
case 'c':
len = strlen(optarg) > 255 ? 255 : strlen(optarg);
if (client_config.clientid)
free(client_config.clientid);
client_config.clientid = xmalloc(len + 1);
client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
client_config.clientid[OPT_LEN] = len;
strlcpy((char *)client_config.clientid + OPT_DATA, optarg,
len + 1 - (OPT_DATA - OPT_CODE));
break;
case 'f':
client_config.foreground = 1;
break;
case 'b':
client_config.background_if_no_lease = 1;
break;
case 'h':
case 'H':
len = strlen(optarg) > 255 ? 255 : strlen(optarg);
if (client_config.hostname)
free(client_config.hostname);
client_config.hostname = xmalloc(len + 1);
client_config.hostname[OPT_CODE] = DHCP_HOST_NAME;
client_config.hostname[OPT_LEN] = len;
strlcpy((char*)client_config.hostname + OPT_DATA, optarg,
len + 1 - (OPT_DATA - OPT_CODE));
break;
case 'i':
client_config.interface = optarg;
break;
case 'n':
client_config.abort_if_no_lease = 1;
break;
case 'q':
client_config.quit_after_lease = 1;
break;
case 'r':
requested_ip = inet_addr(optarg);
break;
case 'u':
pwd = getpwnam(optarg);
if (pwd) {
uid = (int)pwd->pw_uid;
gid = (int)pwd->pw_gid;
} else {
printf("Bad username provided.\n");
exit(EXIT_FAILURE);
}
break;
case 'C':
strlcpy(chroot_dir, optarg, sizeof chroot_dir);
break;
case 'v':
printf("ndhc, version " VERSION "\n\n");
exit(EXIT_SUCCESS);
break;
default:
show_usage();
}
}
log_line("ndhc client " VERSION " started."); switch (c) {
case 'c':
len = strlen(optarg) > 255 ? 255 : strlen(optarg);
if (client_config.clientid)
free(client_config.clientid);
client_config.clientid = xmalloc(len + 1);
client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
client_config.clientid[OPT_LEN] = len;
strlcpy((char *)client_config.clientid + OPT_DATA, optarg,
len + 1 - (OPT_DATA - OPT_CODE));
break;
case 'f':
client_config.foreground = 1;
break;
case 'b':
client_config.background_if_no_lease = 1;
break;
case 'h':
case 'H':
len = strlen(optarg) > 255 ? 255 : strlen(optarg);
if (client_config.hostname)
free(client_config.hostname);
client_config.hostname = xmalloc(len + 1);
client_config.hostname[OPT_CODE] = DHCP_HOST_NAME;
client_config.hostname[OPT_LEN] = len;
strlcpy((char*)client_config.hostname + OPT_DATA, optarg,
len + 1 - (OPT_DATA - OPT_CODE));
break;
case 'i':
client_config.interface = optarg;
break;
case 'n':
client_config.abort_if_no_lease = 1;
break;
case 'q':
client_config.quit_after_lease = 1;
break;
case 'r':
requested_ip = inet_addr(optarg);
break;
case 'u':
pwd = getpwnam(optarg);
if (pwd) {
uid = (int)pwd->pw_uid;
gid = (int)pwd->pw_gid;
} else {
printf("Bad username provided.\n");
exit(EXIT_FAILURE);
}
break;
case 'C':
strlcpy(chroot_dir, optarg, sizeof chroot_dir);
break;
case 'v':
printf("ndhc, version " VERSION "\n\n");
exit(EXIT_SUCCESS);
break;
default:
show_usage();
}
}
if (read_interface(client_config.interface, &client_config.ifindex, log_line("ndhc client " VERSION " started.");
NULL, client_config.arp) < 0)
exit(EXIT_FAILURE);
if (!client_config.clientid) {
client_config.clientid = xmalloc(6 + 3);
client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
client_config.clientid[OPT_LEN] = 7;
client_config.clientid[OPT_DATA] = 1;
memcpy(client_config.clientid + 3, client_config.arp, 6);
}
/* setup signal handlers */ if (read_interface(client_config.interface, &client_config.ifindex,
signal(SIGUSR1, signal_handler); NULL, client_config.arp) < 0)
signal(SIGUSR2, signal_handler); exit(EXIT_FAILURE);
signal(SIGTERM, signal_handler);
if (chdir(chroot_dir)) { if (!client_config.clientid) {
printf("Failed to chdir(%s)!\n", chroot_dir); client_config.clientid = xmalloc(6 + 3);
exit(EXIT_FAILURE); client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
} client_config.clientid[OPT_LEN] = 7;
client_config.clientid[OPT_DATA] = 1;
memcpy(client_config.clientid + 3, client_config.arp, 6);
}
if (chroot(chroot_dir)) { /* setup signal handlers */
printf("Failed to chroot(%s)!\n", chroot_dir); signal(SIGUSR1, signal_handler);
exit(EXIT_FAILURE); signal(SIGUSR2, signal_handler);
} signal(SIGTERM, signal_handler);
set_cap(uid, gid, if (chdir(chroot_dir)) {
"cap_net_bind_service,cap_net_broadcast,cap_net_raw=ep"); printf("Failed to chdir(%s)!\n", chroot_dir);
drop_root(uid, gid); exit(EXIT_FAILURE);
}
state = INIT_SELECTING;
run_script(NULL, SCRIPT_DECONFIG);
change_mode(LISTEN_RAW);
do_work(); if (chroot(chroot_dir)) {
printf("Failed to chroot(%s)!\n", chroot_dir);
return EXIT_SUCCESS; exit(EXIT_FAILURE);
}
set_cap(uid, gid,
"cap_net_bind_service,cap_net_broadcast,cap_net_raw=ep");
drop_root(uid, gid);
state = INIT_SELECTING;
run_script(NULL, SCRIPT_DECONFIG);
change_mode(LISTEN_RAW);
do_work();
return EXIT_SUCCESS;
} }

View File

@@ -1,9 +1,9 @@
/* /*
* options.c -- DHCP server option packet tools * options.c -- DHCP server option packet tools
* Rewrite by Russ Dill <Russ.Dill@asu.edu> July 2001 * Rewrite by Russ Dill <Russ.Dill@asu.edu> July 2001
* Fixes and hardening: Nicholas Kain <njk@-n0xZpam-.kain.us> * Fixes and hardening: Nicholas J. Kain <njkain at gmail dot com>
*/ */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@@ -16,47 +16,47 @@
/* supported options are easily added here */ /* supported options are easily added here */
struct dhcp_option options[] = { struct dhcp_option options[] = {
/* name[10] flags code */ /* name[10] flags code */
{"subnet", OPTION_IP | OPTION_REQ, 0x01}, {"subnet" , OPTION_IP | OPTION_REQ, 0x01},
{"timezone", OPTION_S32, 0x02}, {"timezone" , OPTION_S32, 0x02},
{"router", OPTION_IP | OPTION_LIST | OPTION_REQ, 0x03}, {"router" , OPTION_IP | OPTION_LIST | OPTION_REQ, 0x03},
{"timesvr", OPTION_IP | OPTION_LIST, 0x04}, {"timesvr" , OPTION_IP | OPTION_LIST, 0x04},
{"namesvr", OPTION_IP | OPTION_LIST, 0x05}, {"namesvr" , OPTION_IP | OPTION_LIST, 0x05},
{"dns", OPTION_IP | OPTION_LIST | OPTION_REQ, 0x06}, {"dns" , OPTION_IP | OPTION_LIST | OPTION_REQ, 0x06},
{"logsvr", OPTION_IP | OPTION_LIST, 0x07}, {"logsvr" , OPTION_IP | OPTION_LIST, 0x07},
{"cookiesvr", OPTION_IP | OPTION_LIST, 0x08}, {"cookiesvr", OPTION_IP | OPTION_LIST, 0x08},
{"lprsvr", OPTION_IP | OPTION_LIST, 0x09}, {"lprsvr" , OPTION_IP | OPTION_LIST, 0x09},
{"hostname", OPTION_STRING | OPTION_REQ, 0x0c}, {"hostname" , OPTION_STRING | OPTION_REQ, 0x0c},
{"bootsize", OPTION_U16, 0x0d}, {"bootsize" , OPTION_U16, 0x0d},
{"domain", OPTION_STRING | OPTION_REQ, 0x0f}, {"domain" , OPTION_STRING | OPTION_REQ, 0x0f},
{"swapsvr", OPTION_IP, 0x10}, {"swapsvr" , OPTION_IP, 0x10},
{"rootpath", OPTION_STRING, 0x11}, {"rootpath" , OPTION_STRING, 0x11},
{"ipttl", OPTION_U8, 0x17}, {"ipttl" , OPTION_U8, 0x17},
{"mtu", OPTION_U16, 0x1a}, {"mtu" , OPTION_U16, 0x1a},
{"broadcast", OPTION_IP | OPTION_REQ, 0x1c}, {"broadcast", OPTION_IP | OPTION_REQ, 0x1c},
{"ntpsrv", OPTION_IP | OPTION_LIST, 0x2a}, {"ntpsrv" , OPTION_IP | OPTION_LIST, 0x2a},
{"wins", OPTION_IP | OPTION_LIST, 0x2c}, {"wins" , OPTION_IP | OPTION_LIST, 0x2c},
{"requestip", OPTION_IP, 0x32}, {"requestip", OPTION_IP, 0x32},
{"lease", OPTION_U32, 0x33}, {"lease" , OPTION_U32, 0x33},
{"dhcptype", OPTION_U8, 0x35}, {"dhcptype" , OPTION_U8, 0x35},
{"serverid", OPTION_IP, 0x36}, {"serverid" , OPTION_IP, 0x36},
{"message", OPTION_STRING, 0x38}, {"message" , OPTION_STRING, 0x38},
{"tftp", OPTION_STRING, 0x42}, {"tftp" , OPTION_STRING, 0x42},
{"bootfile", OPTION_STRING, 0x43}, {"bootfile" , OPTION_STRING, 0x43},
{"", 0x00, 0x00} {"" , 0x00, 0x00}
}; };
/* Lengths of the different option types */ /* Lengths of the different option types */
int option_lengths[] = { int option_lengths[] = {
[OPTION_IP] = 4, [OPTION_IP] = 4,
[OPTION_IP_PAIR] = 8, [OPTION_IP_PAIR] = 8,
[OPTION_BOOLEAN] = 1, [OPTION_BOOLEAN] = 1,
[OPTION_STRING] = 1, [OPTION_STRING] = 1,
[OPTION_U8] = 1, [OPTION_U8] = 1,
[OPTION_U16] = 2, [OPTION_U16] = 2,
[OPTION_S16] = 2, [OPTION_S16] = 2,
[OPTION_U32] = 4, [OPTION_U32] = 4,
[OPTION_S32] = 4 [OPTION_S32] = 4
}; };
@@ -66,7 +66,7 @@ unsigned char *get_option(struct dhcpMessage *packet, int code)
int i = 0, length = 308; int i = 0, length = 308;
unsigned char *optionptr; unsigned char *optionptr;
int over = 0, done = 0, curr = OPTION_FIELD; int over = 0, done = 0, curr = OPTION_FIELD;
optionptr = packet->options; optionptr = packet->options;
while (!done) { while (!done) {
if (i >= length) { if (i >= length) {
@@ -79,7 +79,7 @@ unsigned char *get_option(struct dhcpMessage *packet, int code)
return NULL; return NULL;
} }
return optionptr + i + 2; return optionptr + i + 2;
} }
switch (optionptr[i + OPT_CODE]) { switch (optionptr[i + OPT_CODE]) {
case DHCP_PADDING: case DHCP_PADDING:
i++; i++;
@@ -114,7 +114,7 @@ unsigned char *get_option(struct dhcpMessage *packet, int code)
/* return the position of the 'end' option */ /* return the position of the 'end' option */
int end_option(unsigned char *optionptr) int end_option(unsigned char *optionptr)
{ {
int i = 0; int i = 0;
@@ -133,11 +133,11 @@ int end_option(unsigned char *optionptr)
int add_option_string(unsigned char *optionptr, unsigned char *string) int add_option_string(unsigned char *optionptr, unsigned char *string)
{ {
int end = end_option(optionptr); int end = end_option(optionptr);
/* end position + string length + option code/length + end option */ /* end position + string length + option code/length + end option */
if (end + string[OPT_LEN] + 2 + 1 >= 308) { if (end + string[OPT_LEN] + 2 + 1 >= 308) {
log_error("Option 0x%02x did not fit into the packet!", log_error("Option 0x%02x did not fit into the packet!",
string[OPT_CODE]); string[OPT_CODE]);
return 0; return 0;
} }
log_line("adding option 0x%02x", string[OPT_CODE]); log_line("adding option 0x%02x", string[OPT_CODE]);
@@ -147,16 +147,16 @@ int add_option_string(unsigned char *optionptr, unsigned char *string)
} }
int add_simple_option(unsigned char *optionptr, unsigned char code, int add_simple_option(unsigned char *optionptr, unsigned char code,
uint32_t data) uint32_t data)
{ {
int i, length = 0; int i, length = 0;
unsigned char option[2 + 4]; unsigned char option[2 + 4];
for (i = 0; options[i].code; i++) for (i = 0; options[i].code; i++)
if (options[i].code == code) { if (options[i].code == code) {
length = option_lengths[options[i].flags & TYPE_MASK]; length = option_lengths[options[i].flags & TYPE_MASK];
} }
option[OPT_CODE] = code; option[OPT_CODE] = code;
option[OPT_LEN] = (unsigned char)length; option[OPT_LEN] = (unsigned char)length;
@@ -189,7 +189,7 @@ struct option_set *find_option(struct option_set *opt_list, char code)
/* add an option to the opt_list */ /* add an option to the opt_list */
void attach_option(struct option_set **opt_list, struct dhcp_option *option, void attach_option(struct option_set **opt_list, struct dhcp_option *option,
char *buffer, int length) char *buffer, int length)
{ {
struct option_set *existing, *new, **curr; struct option_set *existing, *new, **curr;
@@ -199,29 +199,29 @@ void attach_option(struct option_set **opt_list, struct dhcp_option *option,
option->name); option->name);
if (option->flags & OPTION_LIST) { if (option->flags & OPTION_LIST) {
if (existing->data[OPT_LEN] + length <= 255) { if (existing->data[OPT_LEN] + length <= 255) {
existing->data = realloc(existing->data, existing->data = realloc(existing->data,
existing->data[OPT_LEN] + length + 2); existing->data[OPT_LEN] + length + 2);
memcpy(existing->data + existing->data[OPT_LEN] + 2, buffer, memcpy(existing->data + existing->data[OPT_LEN] + 2, buffer,
length); length);
existing->data[OPT_LEN] += length; existing->data[OPT_LEN] += length;
} /* else, ignore the data; we could put this in a second option } /* else, ignore the data; we could put this in a second option
in the future */ in the future */
} /* else, ignore the new data */ } /* else, ignore the new data */
} else { } else {
log_line("Attaching option %s to list", option->name); log_line("Attaching option %s to list", option->name);
/* make a new option */ /* make a new option */
new = xmalloc(sizeof(struct option_set)); new = xmalloc(sizeof(struct option_set));
new->data = xmalloc(length + 2); new->data = xmalloc(length + 2);
new->data[OPT_CODE] = option->code; new->data[OPT_CODE] = option->code;
new->data[OPT_LEN] = length; new->data[OPT_LEN] = length;
memcpy(new->data + 2, buffer, length); memcpy(new->data + 2, buffer, length);
curr = opt_list; curr = opt_list;
while (*curr && (*curr)->data[OPT_CODE] < option->code) while (*curr && (*curr)->data[OPT_CODE] < option->code)
curr = &(*curr)->next; curr = &(*curr)->next;
new->next = *curr; new->next = *curr;
*curr = new; *curr = new;
} }
} }

View File

@@ -13,191 +13,186 @@
#include "dhcpd.h" #include "dhcpd.h"
#include "options.h" #include "options.h"
void init_header(struct dhcpMessage *packet, char type) void init_header(struct dhcpMessage *packet, char type)
{ {
memset(packet, 0, sizeof(struct dhcpMessage)); memset(packet, 0, sizeof(struct dhcpMessage));
switch (type) { switch (type) {
case DHCPDISCOVER: case DHCPDISCOVER:
case DHCPREQUEST: case DHCPREQUEST:
case DHCPRELEASE: case DHCPRELEASE:
case DHCPINFORM: case DHCPINFORM:
packet->op = BOOTREQUEST; packet->op = BOOTREQUEST;
break; break;
case DHCPOFFER: case DHCPOFFER:
case DHCPACK: case DHCPACK:
case DHCPNAK: case DHCPNAK:
packet->op = BOOTREPLY; packet->op = BOOTREPLY;
} }
packet->htype = ETH_10MB; packet->htype = ETH_10MB;
packet->hlen = ETH_10MB_LEN; packet->hlen = ETH_10MB_LEN;
packet->cookie = htonl(DHCP_MAGIC); packet->cookie = htonl(DHCP_MAGIC);
packet->options[0] = DHCP_END; packet->options[0] = DHCP_END;
add_simple_option(packet->options, DHCP_MESSAGE_TYPE, type); add_simple_option(packet->options, DHCP_MESSAGE_TYPE, type);
} }
/* read a packet from socket fd, return -1 on read error, -2 on packet error */ /* read a packet from socket fd, return -1 on read error, -2 on packet error */
int get_packet(struct dhcpMessage *packet, int fd) int get_packet(struct dhcpMessage *packet, int fd)
{ {
int bytes; int bytes;
int i; int i;
const char broken_vendors[][8] = { const char broken_vendors[][8] = {
"MSFT 98", "MSFT 98",
"" ""
}; };
unsigned char *vendor; unsigned char *vendor;
memset(packet, 0, sizeof(struct dhcpMessage)); memset(packet, 0, sizeof(struct dhcpMessage));
bytes = read(fd, packet, sizeof(struct dhcpMessage)); bytes = read(fd, packet, sizeof(struct dhcpMessage));
if (bytes < 0) { if (bytes < 0) {
log_line("couldn't read on listening socket, ignoring"); log_line("couldn't read on listening socket, ignoring");
return -1; return -1;
} }
if (ntohl(packet->cookie) != DHCP_MAGIC) { if (ntohl(packet->cookie) != DHCP_MAGIC) {
log_error("received bogus message, ignoring."); log_error("received bogus message, ignoring.");
return -2; return -2;
}
log_line("Received a packet");
if (packet->op == BOOTREQUEST
&& (vendor = get_option(packet, DHCP_VENDOR)))
{
for (i = 0; broken_vendors[i][0]; i++) {
if (vendor[OPT_LEN - 2] == (unsigned char)strlen(broken_vendors[i])
&& !strncmp((char *)vendor, broken_vendors[i],
vendor[OPT_LEN - 2]))
{
log_line("broken client (%s), forcing broadcast",
broken_vendors[i]);
packet->flags |= htons(BROADCAST_FLAG);
}
} }
log_line("Received a packet"); }
return bytes;
if (packet->op == BOOTREQUEST
&& (vendor = get_option(packet, DHCP_VENDOR)))
{
for (i = 0; broken_vendors[i][0]; i++) {
if (vendor[OPT_LEN - 2] == (unsigned char)strlen(broken_vendors[i])
&& !strncmp((char *)vendor, broken_vendors[i],
vendor[OPT_LEN - 2]))
{
log_line("broken client (%s), forcing broadcast",
broken_vendors[i]);
packet->flags |= htons(BROADCAST_FLAG);
}
}
}
return bytes;
} }
uint16_t checksum(void *addr, int count) uint16_t checksum(void *addr, int count)
{ {
/* Compute Internet Checksum for "count" bytes /* Compute Internet Checksum for "count" bytes
* beginning at location "addr". * beginning at location "addr".
*/ */
register int32_t sum = 0; register int32_t sum = 0;
uint16_t *source = (uint16_t *)addr; uint16_t *source = (uint16_t *)addr;
while (count > 1) { while (count > 1) {
sum += *source++; sum += *source++;
count -= 2; count -= 2;
} }
/* Add left-over byte, if any */ /* Add left-over byte, if any */
if (count > 0) { if (count > 0) {
/* Make sure that the left-over byte is added correctly both /* Make sure that the left-over byte is added correctly both
* with little and big endian hosts */ * with little and big endian hosts */
uint16_t tmp = 0; uint16_t tmp = 0;
*(unsigned char *) (&tmp) = * (unsigned char *) source; *(unsigned char *) (&tmp) = * (unsigned char *) source;
sum += tmp; sum += tmp;
} }
/* Fold 32-bit sum to 16 bits */ /* Fold 32-bit sum to 16 bits */
while (sum >> 16) while (sum >> 16)
sum = (sum & 0xffff) + (sum >> 16); sum = (sum & 0xffff) + (sum >> 16);
return ~sum; return ~sum;
} }
/* Constuct a ip/udp header for a packet, and specify the source and dest /* Constuct a ip/udp header for a packet, and specify the source and dest
* hardware address */ * hardware address */
int raw_packet(struct dhcpMessage *payload, uint32_t source_ip, int raw_packet(struct dhcpMessage *payload, uint32_t source_ip,
int source_port, uint32_t dest_ip, int dest_port, int source_port, uint32_t dest_ip, int dest_port,
unsigned char *dest_arp, int ifindex) unsigned char *dest_arp, int ifindex)
{ {
int fd, result = -1; int fd, result = -1;
struct sockaddr_ll dest; struct sockaddr_ll dest;
struct udp_dhcp_packet packet; struct udp_dhcp_packet packet;
if ((fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) { if ((fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) {
log_error("socket call failed: %s", strerror(errno)); log_error("socket call failed: %s", strerror(errno));
goto out; goto out;
} }
memset(&dest, 0, sizeof(dest));
memset(&packet, 0, sizeof(packet));
dest.sll_family = AF_PACKET;
dest.sll_protocol = htons(ETH_P_IP);
dest.sll_ifindex = ifindex;
dest.sll_halen = 6;
memcpy(dest.sll_addr, dest_arp, 6);
if (bind(fd, (struct sockaddr *)&dest, sizeof(struct sockaddr_ll)) < 0) {
log_error("bind call failed: %s", strerror(errno));
goto out_fd;
}
packet.ip.protocol = IPPROTO_UDP; memset(&dest, 0, sizeof(dest));
packet.ip.saddr = source_ip; memset(&packet, 0, sizeof(packet));
packet.ip.daddr = dest_ip;
packet.udp.source = htons(source_port);
packet.udp.dest = htons(dest_port);
/* cheat on the psuedo-header */
packet.udp.len = htons(sizeof(packet.udp) + sizeof(struct dhcpMessage));
packet.ip.tot_len = packet.udp.len;
memcpy(&(packet.data), payload, sizeof(struct dhcpMessage));
packet.udp.check = checksum(&packet, sizeof(struct udp_dhcp_packet));
packet.ip.tot_len = htons(sizeof(struct udp_dhcp_packet));
packet.ip.ihl = sizeof(packet.ip) >> 2;
packet.ip.version = IPVERSION;
packet.ip.ttl = IPDEFTTL;
packet.ip.check = checksum(&(packet.ip), sizeof(packet.ip));
result = sendto(fd, &packet, sizeof(struct udp_dhcp_packet), 0, dest.sll_family = AF_PACKET;
(struct sockaddr *)&dest, sizeof dest); dest.sll_protocol = htons(ETH_P_IP);
if (result <= 0) { dest.sll_ifindex = ifindex;
log_error("write on socket failed: %s", dest.sll_halen = 6;
strerror(errno)); memcpy(dest.sll_addr, dest_arp, 6);
} if (bind(fd, (struct sockaddr *)&dest, sizeof(struct sockaddr_ll)) < 0) {
out_fd: log_error("bind call failed: %s", strerror(errno));
close(fd); goto out_fd;
out: }
return result;
packet.ip.protocol = IPPROTO_UDP;
packet.ip.saddr = source_ip;
packet.ip.daddr = dest_ip;
packet.udp.source = htons(source_port);
packet.udp.dest = htons(dest_port);
/* cheat on the psuedo-header */
packet.udp.len = htons(sizeof(packet.udp) + sizeof(struct dhcpMessage));
packet.ip.tot_len = packet.udp.len;
memcpy(&(packet.data), payload, sizeof(struct dhcpMessage));
packet.udp.check = checksum(&packet, sizeof(struct udp_dhcp_packet));
packet.ip.tot_len = htons(sizeof(struct udp_dhcp_packet));
packet.ip.ihl = sizeof(packet.ip) >> 2;
packet.ip.version = IPVERSION;
packet.ip.ttl = IPDEFTTL;
packet.ip.check = checksum(&(packet.ip), sizeof(packet.ip));
result = sendto(fd, &packet, sizeof(struct udp_dhcp_packet), 0,
(struct sockaddr *)&dest, sizeof dest);
if (result <= 0) {
log_error("write on socket failed: %s",
strerror(errno));
}
out_fd:
close(fd);
out:
return result;
} }
/* Let the kernel do all the work for packet generation */ /* Let the kernel do all the work for packet generation */
int kernel_packet(struct dhcpMessage *payload, uint32_t source_ip, int kernel_packet(struct dhcpMessage *payload, uint32_t source_ip,
int source_port, uint32_t dest_ip, int dest_port) int source_port, uint32_t dest_ip, int dest_port)
{ {
int n = 1, fd, result = -1; int n = 1, fd, result = -1;
struct sockaddr_in client; struct sockaddr_in client;
if ((fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
goto out;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &n, sizeof(n)) == -1)
goto out_fd;
memset(&client, 0, sizeof(client)); if ((fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
client.sin_family = AF_INET; goto out;
client.sin_port = htons(source_port);
client.sin_addr.s_addr = source_ip;
if (bind(fd, (struct sockaddr *)&client, sizeof(struct sockaddr)) == -1) if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &n, sizeof(n)) == -1)
goto out_fd; goto out_fd;
memset(&client, 0, sizeof(client)); memset(&client, 0, sizeof(client));
client.sin_family = AF_INET; client.sin_family = AF_INET;
client.sin_port = htons(dest_port); client.sin_port = htons(source_port);
client.sin_addr.s_addr = dest_ip; client.sin_addr.s_addr = source_ip;
if (connect(fd, (struct sockaddr *)&client, sizeof(struct sockaddr)) == -1) if (bind(fd, (struct sockaddr *)&client, sizeof(struct sockaddr)) == -1)
goto out_fd; goto out_fd;
result = write(fd, payload, sizeof(struct dhcpMessage)); memset(&client, 0, sizeof(client));
out_fd: client.sin_family = AF_INET;
close(fd); client.sin_port = htons(dest_port);
out: client.sin_addr.s_addr = dest_ip;
return result;
}
if (connect(fd, (struct sockaddr *)&client, sizeof(struct sockaddr)) == -1)
goto out_fd;
result = write(fd, payload, sizeof(struct dhcpMessage));
out_fd:
close(fd);
out:
return result;
}

View File

@@ -3,7 +3,7 @@
* Functions to call the interface change daemon * Functions to call the interface change daemon
* *
* Russ Dill <Russ.Dill@asu.edu> July 2001 * Russ Dill <Russ.Dill@asu.edu> July 2001
* Nicholas Kain <njk@nozspamz.aerifal.cx> 2004 * Nicholas J. Kain <njkain at gmail dot com> 2004-2010
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -40,219 +40,229 @@
#include "log.h" #include "log.h"
#include "script.h" #include "script.h"
static int snprintip(char *dest, size_t size, unsigned char *ip) { static int snprintip(char *dest, size_t size, unsigned char *ip)
if (!dest) return -1; {
return snprintf(dest, size, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); if (!dest) return -1;
return snprintf(dest, size, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
} }
static int sprintip(char *dest, size_t size, char *pre, unsigned char *ip) { static int sprintip(char *dest, size_t size, char *pre, unsigned char *ip)
if (!dest) return -1; {
return snprintf(dest, size, "%s%d.%d.%d.%d", pre, ip[0], ip[1], ip[2], ip[3]); if (!dest) return -1;
return snprintf(dest, size, "%s%d.%d.%d.%d",
pre, ip[0], ip[1], ip[2], ip[3]);
} }
/* Fill dest with the text of option 'option'. */ /* Fill dest with the text of option 'option'. */
static void fill_options(char *dest, unsigned char *option, struct dhcp_option *type_p, unsigned int maxlen) static void fill_options(char *dest, unsigned char *option,
struct dhcp_option *type_p, unsigned int maxlen)
{ {
int type, optlen; int type, optlen;
uint16_t val_u16; uint16_t val_u16;
int16_t val_s16; int16_t val_s16;
uint32_t val_u32; uint32_t val_u32;
int32_t val_s32; int32_t val_s32;
int len = option[OPT_LEN - 2]; int len = option[OPT_LEN - 2];
char *odest; char *odest;
odest = dest;
dest += snprintf(dest, maxlen, "%s=", type_p->name);
type = type_p->flags & TYPE_MASK; odest = dest;
optlen = option_lengths[type];
for(;;) { dest += snprintf(dest, maxlen, "%s=", type_p->name);
switch (type) {
case OPTION_IP_PAIR: type = type_p->flags & TYPE_MASK;
dest += sprintip(dest, maxlen - (dest - odest), "", option); optlen = option_lengths[type];
*(dest++) = '/'; for(;;) {
option += 4; switch (type) {
optlen = 4; case OPTION_IP_PAIR:
case OPTION_IP: /* Works regardless of host byte order. */ dest += sprintip(dest, maxlen - (dest - odest), "", option);
dest += sprintip(dest, maxlen - (dest - odest), "", option); *(dest++) = '/';
break; option += 4;
case OPTION_BOOLEAN: optlen = 4;
dest += snprintf(dest, maxlen - (dest - odest), *option ? "yes " : "no "); case OPTION_IP: /* Works regardless of host byte order. */
break; dest += sprintip(dest, maxlen - (dest - odest), "", option);
case OPTION_U8: break;
dest += snprintf(dest, maxlen - (dest - odest), "%u ", *option); case OPTION_BOOLEAN:
break; dest += snprintf(dest, maxlen - (dest - odest),
case OPTION_U16: *option ? "yes " : "no ");
memcpy(&val_u16, option, 2); break;
dest += snprintf(dest, maxlen - (dest - odest), "%u ", ntohs(val_u16)); case OPTION_U8:
break; dest += snprintf(dest, maxlen - (dest - odest),
case OPTION_S16: "%u ", *option);
memcpy(&val_s16, option, 2); break;
dest += snprintf(dest, maxlen - (dest - odest), "%d ", ntohs(val_s16)); case OPTION_U16:
break; memcpy(&val_u16, option, 2);
case OPTION_U32: dest += snprintf(dest, maxlen - (dest - odest),
memcpy(&val_u32, option, 4); "%u ", ntohs(val_u16));
dest += snprintf(dest, maxlen - (dest - odest), "%lu ", (unsigned long) ntohl(val_u32)); break;
break; case OPTION_S16:
case OPTION_S32: memcpy(&val_s16, option, 2);
memcpy(&val_s32, option, 4); dest += snprintf(dest, maxlen - (dest - odest),
dest += snprintf(dest, maxlen - (dest - odest), "%ld ", (long) ntohl(val_s32)); "%d ", ntohs(val_s16));
break; break;
case OPTION_STRING: case OPTION_U32:
if ( (maxlen - (dest - odest)) < (unsigned)len) return; memcpy(&val_u32, option, 4);
memcpy(dest, option, len); dest += snprintf(dest, maxlen - (dest - odest),
dest[len] = '\0'; "%lu ", (unsigned long) ntohl(val_u32));
return; /* Short circuit this case */ break;
} case OPTION_S32:
option += optlen; memcpy(&val_s32, option, 4);
len -= optlen; dest += snprintf(dest, maxlen - (dest - odest),
if (len <= 0) break; "%ld ", (long) ntohl(val_s32));
} break;
case OPTION_STRING:
if ( (maxlen - (dest - odest)) < (unsigned)len) return;
memcpy(dest, option, len);
dest[len] = '\0';
return; /* Short circuit this case */
}
option += optlen;
len -= optlen;
if (len <= 0) break;
}
} }
static int open_ifch(void) { static int open_ifch(void) {
int sockfd, ret; int sockfd, ret;
struct sockaddr_un address = struct sockaddr_un address = {
{ .sun_family = AF_UNIX,
.sun_family = AF_UNIX, .sun_path = "ifchange"
.sun_path = "ifchange" };
};
sockfd = socket(AF_UNIX, SOCK_STREAM, 0); sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
ret = connect(sockfd, (struct sockaddr *)&address, sizeof(address)); ret = connect(sockfd, (struct sockaddr *)&address, sizeof(address));
if (ret == -1) { if (ret == -1) {
log_error("unable to connect to ifchd!"); log_error("unable to connect to ifchd!");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
return sockfd; return sockfd;
} }
static void sockwrite(int fd, const void *buf, size_t count) static void sockwrite(int fd, const void *buf, size_t count)
{ {
int ret; int ret;
sockwrite_again: sockwrite_again:
ret = write(fd, buf, count); ret = write(fd, buf, count);
if (ret == -1) { if (ret == -1) {
if (errno == EAGAIN) if (errno == EAGAIN)
goto sockwrite_again; goto sockwrite_again;
log_error("error while writing to unix socket!"); log_error("error while writing to unix socket!");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (ret < 0) ret = 0; if (ret < 0) ret = 0;
if ((unsigned int)ret < strlen(buf)) { if ((unsigned int)ret < strlen(buf)) {
log_error("incomplete write!"); log_error("incomplete write!");
} }
log_line("writing: %s", (char *)buf); log_line("writing: %s", (char *)buf);
} }
static void deconfig_if(void) static void deconfig_if(void)
{ {
int sockfd; int sockfd;
char buf[256]; char buf[256];
memset(buf, '\0', sizeof buf);
sockfd = open_ifch();
snprintf(buf, sizeof buf, "interface:%s:",
client_config.interface);
sockwrite(sockfd, buf, strlen(buf));
snprintf(buf, sizeof buf, "ip:0.0.0.0:"); memset(buf, '\0', sizeof buf);
sockwrite(sockfd, buf, strlen(buf));
sockfd = open_ifch();
close(sockfd);
exit(EXIT_SUCCESS); snprintf(buf, sizeof buf, "interface:%s:",
client_config.interface);
sockwrite(sockfd, buf, strlen(buf));
snprintf(buf, sizeof buf, "ip:0.0.0.0:");
sockwrite(sockfd, buf, strlen(buf));
close(sockfd);
exit(EXIT_SUCCESS);
} }
static void translate_option(int sockfd, struct dhcpMessage *packet, int opt) { static void translate_option(int sockfd, struct dhcpMessage *packet, int opt)
char buf[256], buf2[256]; {
unsigned char *p; char buf[256], buf2[256];
int i; unsigned char *p;
int i;
if (!packet) return; if (!packet) return;
memset(buf, '\0', sizeof(buf)); memset(buf, '\0', sizeof(buf));
memset(buf2, '\0', sizeof(buf2)); memset(buf2, '\0', sizeof(buf2));
p = get_option(packet, options[opt].code); p = get_option(packet, options[opt].code);
fill_options(buf2, p, &options[opt], sizeof(buf2) - 1); fill_options(buf2, p, &options[opt], sizeof(buf2) - 1);
snprintf(buf, sizeof buf, "%s:", buf2); snprintf(buf, sizeof buf, "%s:", buf2);
for (i=0; i<256; i++) { for (i=0; i<256; i++) {
if (buf[i] == '\0') break; if (buf[i] == '\0') break;
if (buf[i] == '=') { if (buf[i] == '=') {
buf[i] = ':'; buf[i] = ':';
break; break;
} }
} }
sockwrite(sockfd, buf, strlen(buf)); sockwrite(sockfd, buf, strlen(buf));
} }
static void bound_if(struct dhcpMessage *packet) static void bound_if(struct dhcpMessage *packet)
{ {
int sockfd; int sockfd;
char buf[256], buf2[256]; char buf[256], buf2[256];
char ip[32]; char ip[32];
if (!packet) return;
memset(buf, '\0', sizeof(buf));
memset(ip, '\0', sizeof(ip));
memset(buf2, '\0', sizeof(buf2));
sockfd = open_ifch();
snprintf(buf, sizeof buf, "interface:%s:", client_config.interface); if (!packet) return;
sockwrite(sockfd, buf, strlen(buf));
snprintip(ip, sizeof ip, (unsigned char *) &packet->yiaddr); memset(buf, '\0', sizeof(buf));
snprintf(buf, sizeof buf, "ip:%s:", ip); memset(ip, '\0', sizeof(ip));
sockwrite(sockfd, buf, strlen(buf)); memset(buf2, '\0', sizeof(buf2));
translate_option(sockfd, packet, 0); sockfd = open_ifch();
translate_option(sockfd, packet, 2);
translate_option(sockfd, packet, 5); snprintf(buf, sizeof buf, "interface:%s:", client_config.interface);
translate_option(sockfd, packet, 9); sockwrite(sockfd, buf, strlen(buf));
translate_option(sockfd, packet, 11);
translate_option(sockfd, packet, 15); snprintip(ip, sizeof ip, (unsigned char *) &packet->yiaddr);
translate_option(sockfd, packet, 16); snprintf(buf, sizeof buf, "ip:%s:", ip);
translate_option(sockfd, packet, 17); sockwrite(sockfd, buf, strlen(buf));
close(sockfd); translate_option(sockfd, packet, 0);
exit(EXIT_SUCCESS); translate_option(sockfd, packet, 2);
translate_option(sockfd, packet, 5);
translate_option(sockfd, packet, 9);
translate_option(sockfd, packet, 11);
translate_option(sockfd, packet, 15);
translate_option(sockfd, packet, 16);
translate_option(sockfd, packet, 17);
close(sockfd);
exit(EXIT_SUCCESS);
} }
void run_script(struct dhcpMessage *packet, int mode) void run_script(struct dhcpMessage *packet, int mode)
{ {
int pid; int pid;
pid = fork(); pid = fork();
if (pid) { if (pid) {
waitpid(pid, NULL, 0); waitpid(pid, NULL, 0);
return; return;
} else if (pid == 0) { } else if (pid == 0) {
switch (mode) { switch (mode) {
case SCRIPT_DECONFIG: case SCRIPT_DECONFIG:
deconfig_if(); deconfig_if();
break; break;
case SCRIPT_BOUND: case SCRIPT_BOUND:
bound_if(packet); bound_if(packet);
break; break;
case SCRIPT_RENEW: case SCRIPT_RENEW:
bound_if(packet); bound_if(packet);
break; break;
case SCRIPT_NAK: case SCRIPT_NAK:
deconfig_if(); deconfig_if();
break; break;
default: default:
break; break;
} }
log_error("invalid script mode: %d", mode); log_error("invalid script mode: %d", mode);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }

View File

@@ -1,14 +1,11 @@
/* /*
* socket.c -- DHCP server client/server socket creation * socket.c -- DHCP server client/server socket creation
* *
* udhcp client/server * Copyright (C) 2004-2010 Nicholas J. Kain <njkain at gmail dot com>
* Rewrite by Russ Dill <Russ.Dill@asu.edu> July 2001
* Copyright (C) 1999 Matthew Ramsay <matthewr@moreton.com.au> * Copyright (C) 1999 Matthew Ramsay <matthewr@moreton.com.au>
* Chris Trew <ctrew@moreton.com.au> * Chris Trew <ctrew@moreton.com.au>
* *
* Rewrite by Russ Dill <Russ.Dill@asu.edu> July 2001
*
* Cleanup and fixes, Nicholas Kain <njk@n0sPaM.kain.us> 2004
*
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or * the Free Software Foundation; either version 2 of the License, or
@@ -40,116 +37,115 @@
#include "strl.h" #include "strl.h"
int read_interface(char *interface, int *ifindex, uint32_t *addr, int read_interface(char *interface, int *ifindex, uint32_t *addr,
unsigned char *arp) unsigned char *arp)
{ {
int fd, ret = -1; int fd, ret = -1;
struct ifreq ifr; struct ifreq ifr;
struct sockaddr_in *our_ip; struct sockaddr_in *our_ip;
memset(&ifr, 0, sizeof(struct ifreq)); memset(&ifr, 0, sizeof(struct ifreq));
if((fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) == -1) { if((fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) == -1) {
log_error("socket failed!: %s", strerror(errno)); log_error("socket failed!: %s", strerror(errno));
goto out; goto out;
} }
ifr.ifr_addr.sa_family = AF_INET; ifr.ifr_addr.sa_family = AF_INET;
strlcpy(ifr.ifr_name, interface, IFNAMSIZ); strlcpy(ifr.ifr_name, interface, IFNAMSIZ);
if (addr) { if (addr) {
if (ioctl(fd, SIOCGIFADDR, &ifr)) { if (ioctl(fd, SIOCGIFADDR, &ifr)) {
log_error("Couldn't get IP for %s.", strerror(errno)); log_error("Couldn't get IP for %s.", strerror(errno));
goto out_fd; goto out_fd;
} }
our_ip = (struct sockaddr_in *) &ifr.ifr_addr; our_ip = (struct sockaddr_in *) &ifr.ifr_addr;
*addr = our_ip->sin_addr.s_addr; *addr = our_ip->sin_addr.s_addr;
log_line("%s (our ip) = %s", ifr.ifr_name, log_line("%s (our ip) = %s", ifr.ifr_name,
inet_ntoa(our_ip->sin_addr)); inet_ntoa(our_ip->sin_addr));
} }
if (ioctl(fd, SIOCGIFINDEX, &ifr)) { if (ioctl(fd, SIOCGIFINDEX, &ifr)) {
log_error("SIOCGIFINDEX failed!: %s", strerror(errno)); log_error("SIOCGIFINDEX failed!: %s", strerror(errno));
goto out_fd; goto out_fd;
} }
log_line("adapter index %d", ifr.ifr_ifindex); log_line("adapter index %d", ifr.ifr_ifindex);
*ifindex = ifr.ifr_ifindex; *ifindex = ifr.ifr_ifindex;
if (ioctl(fd, SIOCGIFHWADDR, &ifr)) { if (ioctl(fd, SIOCGIFHWADDR, &ifr)) {
log_error("Couldn't get MAC for %s", strerror(errno)); log_error("Couldn't get MAC for %s", strerror(errno));
goto out_fd; goto out_fd;
} }
memcpy(arp, ifr.ifr_hwaddr.sa_data, 6); memcpy(arp, ifr.ifr_hwaddr.sa_data, 6);
log_line("adapter hardware address %02x:%02x:%02x:%02x:%02x:%02x", log_line("adapter hardware address %02x:%02x:%02x:%02x:%02x:%02x",
arp[0], arp[1], arp[2], arp[3], arp[4], arp[5]); arp[0], arp[1], arp[2], arp[3], arp[4], arp[5]);
ret = 0; ret = 0;
out_fd: out_fd:
close(fd); close(fd);
out: out:
return ret; return ret;
} }
int listen_socket(unsigned int ip, int port, char *inf) int listen_socket(unsigned int ip, int port, char *inf)
{ {
struct ifreq interface; struct ifreq interface;
int fd; int fd;
struct sockaddr_in addr; struct sockaddr_in addr;
int n = 1; int n = 1;
log_line("Opening listen socket on 0x%08x:%d %s", ip, port, inf); log_line("Opening listen socket on 0x%08x:%d %s", ip, port, inf);
if ((fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { if ((fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
log_error("socket call failed: %s", strerror(errno)); log_error("socket call failed: %s", strerror(errno));
goto out; goto out;
} }
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = ip;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof n) == -1) memset(&addr, 0, sizeof(addr));
goto out_fd; addr.sin_family = AF_INET;
if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (char *)&n, sizeof n) == -1) addr.sin_port = htons(port);
goto out_fd; addr.sin_addr.s_addr = ip;
strlcpy(interface.ifr_ifrn.ifrn_name, inf, IFNAMSIZ); if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof n) == -1)
if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, goto out_fd;
(char *)&interface, sizeof interface) < 0) if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (char *)&n, sizeof n) == -1)
goto out_fd; goto out_fd;
if (bind(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) strlcpy(interface.ifr_ifrn.ifrn_name, inf, IFNAMSIZ);
goto out_fd; if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE,
(char *)&interface, sizeof interface) < 0)
return fd; goto out_fd;
out_fd:
close(fd); if (bind(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1)
out: goto out_fd;
return -1;
return fd;
out_fd:
close(fd);
out:
return -1;
} }
int raw_socket(int ifindex) int raw_socket(int ifindex)
{ {
int fd; int fd;
struct sockaddr_ll sock; struct sockaddr_ll sock;
log_line("Opening raw socket on ifindex %d", ifindex); log_line("Opening raw socket on ifindex %d", ifindex);
if ((fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) { if ((fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) {
log_error("socket call failed: %s", strerror(errno)); log_error("socket call failed: %s", strerror(errno));
goto out; goto out;
} }
sock.sll_family = AF_PACKET;
sock.sll_protocol = htons(ETH_P_IP);
sock.sll_ifindex = ifindex;
if (bind(fd, (struct sockaddr *) &sock, sizeof(sock)) < 0) {
log_error("bind call failed: %s", strerror(errno));
goto out_fd;
}
return fd; sock.sll_family = AF_PACKET;
out_fd: sock.sll_protocol = htons(ETH_P_IP);
close(fd); sock.sll_ifindex = ifindex;
out: if (bind(fd, (struct sockaddr *) &sock, sizeof(sock)) < 0) {
return -1; log_error("bind call failed: %s", strerror(errno));
goto out_fd;
}
return fd;
out_fd:
close(fd);
out:
return -1;
} }