busybox/networking/udhcp/dhcprelay.c
<<
>>
Prefs
   1/* vi: set sw=4 ts=4: */
   2/*
   3 * Port to Busybox Copyright (C) 2006 Jesse Dutton <jessedutton@gmail.com>
   4 *
   5 * Licensed under GPLv2, see file LICENSE in this source tree.
   6 *
   7 * DHCP Relay for 'DHCPv4 Configuration of IPSec Tunnel Mode' support
   8 * Copyright (C) 2002 Mario Strasser <mast@gmx.net>,
   9 *                   Zuercher Hochschule Winterthur,
  10 *                   Netbeat AG
  11 * Upstream has GPL v2 or later
  12 */
  13//applet:IF_DHCPRELAY(APPLET(dhcprelay, BB_DIR_USR_SBIN, BB_SUID_DROP))
  14
  15//kbuild:lib-$(CONFIG_DHCPRELAY) += dhcprelay.o
  16
  17//usage:#define dhcprelay_trivial_usage
  18//usage:       "CLIENT_IFACE[,CLIENT_IFACE2]... SERVER_IFACE [SERVER_IP]"
  19//usage:#define dhcprelay_full_usage "\n\n"
  20//usage:       "Relay DHCP requests between clients and server.\n"
  21//usage:       "Without SERVER_IP, requests are broadcast on SERVER_IFACE."
  22
  23#include "common.h"
  24
  25#define SERVER_PORT    67
  26
  27/* lifetime of an xid entry in sec. */
  28#define MAX_LIFETIME   2*60
  29/* select timeout in sec. */
  30#define SELECT_TIMEOUT (MAX_LIFETIME / 8)
  31
  32/* This list holds information about clients. The xid_* functions manipulate this list. */
  33struct xid_item {
  34        unsigned timestamp;
  35        unsigned iface_no;
  36        uint32_t xid;
  37        struct sockaddr_in ip;
  38        struct xid_item *next;
  39} FIX_ALIASING;
  40
  41#define dhcprelay_xid_list (*(struct xid_item*)bb_common_bufsiz1)
  42#define INIT_G() do { setup_common_bufsiz(); } while (0)
  43
  44static struct xid_item *xid_add(uint32_t xid, struct sockaddr_in *ip, unsigned iface_no)
  45{
  46        struct xid_item *item;
  47
  48        /* create new xid entry */
  49        item = xmalloc(sizeof(struct xid_item));
  50
  51        /* add xid entry */
  52        item->ip = *ip;
  53        item->xid = xid;
  54        item->iface_no = iface_no;
  55        item->timestamp = monotonic_sec();
  56        item->next = dhcprelay_xid_list.next;
  57        dhcprelay_xid_list.next = item;
  58
  59        return item;
  60}
  61
  62static void xid_expire(void)
  63{
  64        struct xid_item *item = dhcprelay_xid_list.next;
  65        struct xid_item *last = &dhcprelay_xid_list;
  66        unsigned current_time = monotonic_sec();
  67
  68        while (item != NULL) {
  69                if ((current_time - item->timestamp) > MAX_LIFETIME) {
  70                        last->next = item->next;
  71                        free(item);
  72                        item = last->next;
  73                } else {
  74                        last = item;
  75                        item = item->next;
  76                }
  77        }
  78}
  79
  80static struct xid_item *xid_find(uint32_t xid)
  81{
  82        struct xid_item *item = dhcprelay_xid_list.next;
  83        while (item != NULL) {
  84                if (item->xid == xid) {
  85                        break;
  86                }
  87                item = item->next;
  88        }
  89        return item;
  90}
  91
  92static void xid_del(uint32_t xid)
  93{
  94        struct xid_item *item = dhcprelay_xid_list.next;
  95        struct xid_item *last = &dhcprelay_xid_list;
  96        while (item != NULL) {
  97                if (item->xid == xid) {
  98                        last->next = item->next;
  99                        free(item);
 100                        item = last->next;
 101                } else {
 102                        last = item;
 103                        item = item->next;
 104                }
 105        }
 106}
 107
 108/**
 109 * get_dhcp_packet_type - gets the message type of a dhcp packet
 110 * p - pointer to the dhcp packet
 111 * returns the message type on success, -1 otherwise
 112 */
 113static int get_dhcp_packet_type(struct dhcp_packet *p)
 114{
 115        uint8_t *op;
 116
 117        /* it must be either a BOOTREQUEST or a BOOTREPLY */
 118        if (p->op != BOOTREQUEST && p->op != BOOTREPLY)
 119                return -1;
 120        /* get message type option */
 121        op = udhcp_get_option(p, DHCP_MESSAGE_TYPE);
 122        if (op != NULL)
 123                return op[0];
 124        return -1;
 125}
 126
 127/**
 128 * make_iface_list - parses client/server interface names
 129 * returns array
 130 */
 131static char **make_iface_list(char **client_and_server_ifaces, unsigned *client_number)
 132{
 133        char *s, **iface_list;
 134        unsigned i, cn;
 135
 136        /* get number of items */
 137        cn = 2; /* 1 server iface + at least 1 client one */
 138        s = client_and_server_ifaces[0]; /* list of client ifaces */
 139        while (*s) {
 140                if (*s == ',')
 141                        cn++;
 142                s++;
 143        }
 144        *client_number = cn;
 145
 146        /* create vector of pointers */
 147        iface_list = xzalloc(cn * sizeof(iface_list[0]));
 148
 149        iface_list[0] = client_and_server_ifaces[1]; /* server iface */
 150
 151        i = 1;
 152        s = xstrdup(client_and_server_ifaces[0]); /* list of client ifaces */
 153        goto store_client_iface_name;
 154
 155        while (i < cn) {
 156                if (*s++ == ',') {
 157                        s[-1] = '\0';
 158 store_client_iface_name:
 159                        iface_list[i++] = s;
 160                }
 161        }
 162
 163        return iface_list;
 164}
 165
 166/* Creates listen sockets (in fds) bound to client and server ifaces,
 167 * and returns numerically max fd.
 168 */
 169static unsigned init_sockets(char **iface_list, unsigned num_clients, int *fds)
 170{
 171        unsigned i, n;
 172
 173        n = 0;
 174        for (i = 0; i < num_clients; i++) {
 175                fds[i] = udhcp_listen_socket(/*INADDR_ANY,*/ SERVER_PORT, iface_list[i]);
 176                if (n < fds[i])
 177                        n = fds[i];
 178        }
 179        return n;
 180}
 181
 182static int sendto_ip4(int sock, const void *msg, int msg_len, struct sockaddr_in *to)
 183{
 184        int err;
 185
 186        errno = 0;
 187        err = sendto(sock, msg, msg_len, 0, (struct sockaddr*) to, sizeof(*to));
 188        err -= msg_len;
 189        if (err)
 190                bb_simple_perror_msg("sendto");
 191        return err;
 192}
 193
 194/**
 195 * pass_to_server() - forwards dhcp packets from client to server
 196 * p - packet to send
 197 * client - number of the client
 198 */
 199static void pass_to_server(struct dhcp_packet *p, int packet_len, unsigned from_iface_no, int *fds,
 200                        struct sockaddr_in *client_addr, struct sockaddr_in *server_addr)
 201{
 202        int type;
 203
 204        /* check packet_type */
 205        type = get_dhcp_packet_type(p);
 206//FIXME: the above does not consider packet_len!
 207        if (type != DHCPDISCOVER && type != DHCPREQUEST
 208         && type != DHCPDECLINE && type != DHCPRELEASE
 209         && type != DHCPINFORM
 210        ) {
 211                return;
 212        }
 213
 214        /* create new xid entry */
 215        xid_add(p->xid, client_addr, from_iface_no);
 216//TODO: since we key request/reply pairs on xid values, shouldn't we drop new requests
 217//with xid accidentally matching a xid of one of requests we currently hold
 218//waiting for their replies?
 219
 220        /* forward request to server */
 221        /* note that we send from fds[0] which is bound to SERVER_PORT (67).
 222         * IOW: we send _from_ SERVER_PORT! Although this may look strange,
 223         * RFC 1542 not only allows, but prescribes this for BOOTP relays.
 224         */
 225        sendto_ip4(fds[0], p, packet_len, server_addr);
 226}
 227
 228/**
 229 * pass_to_client() - forwards dhcp packets from server to client
 230 * p - packet to send
 231 */
 232static void pass_to_client(struct dhcp_packet *p, int packet_len, int *fds)
 233{
 234        int type;
 235        struct xid_item *item;
 236
 237        /* check packet type */
 238        type = get_dhcp_packet_type(p);
 239//FIXME: the above does not consider packet_len!
 240        if (type != DHCPOFFER && type != DHCPACK && type != DHCPNAK) {
 241                return;
 242        }
 243
 244        /* check xid */
 245        item = xid_find(p->xid);
 246        if (!item) {
 247                return;
 248        }
 249//NB: RFC 1542 section 4.1 seems to envision the logic that
 250//relay agents use giaddr (dhcp_msg.gateway_nip in our code)
 251//to find out on which interface to reply.
 252//(server is meant to copy giaddr from our request packet to its reply).
 253//Above, we don't use that logic, instead we use xid as a key.
 254
 255//TODO: also do it if (p->flags & htons(BROADCAST_FLAG)) is set!
 256        if (item->ip.sin_addr.s_addr == htonl(INADDR_ANY))
 257                item->ip.sin_addr.s_addr = htonl(INADDR_BROADCAST);
 258
 259        sendto_ip4(fds[item->iface_no], p, packet_len, &item->ip);
 260        /* ^^^ if send error occurred, we can't do much, hence no check */
 261
 262        /* remove xid entry */
 263        xid_del(p->xid);
 264}
 265
 266int dhcprelay_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
 267int dhcprelay_main(int argc UNUSED_PARAM, char **argv)
 268{
 269        struct sockaddr_in server_addr;
 270        char **iface_list;
 271        int *fds;
 272        unsigned num_sockets, max_socket;
 273        uint32_t our_nip;
 274
 275        INIT_G();
 276
 277        server_addr.sin_family = AF_INET;
 278        server_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
 279        server_addr.sin_port = htons(SERVER_PORT);
 280
 281        /* dhcprelay CLIENT_IFACE1[,CLIENT_IFACE2...] SERVER_IFACE [SERVER_IP] */
 282        if (!argv[1] || !argv[2])
 283                bb_show_usage();
 284        if (argv[3]) {
 285                if (!inet_aton(argv[3], &server_addr.sin_addr))
 286                        bb_simple_perror_msg_and_die("bad server IP");
 287        }
 288
 289        iface_list = make_iface_list(argv + 1, &num_sockets);
 290
 291        fds = xmalloc(num_sockets * sizeof(fds[0]));
 292
 293        /* Create sockets and bind one to every iface */
 294        max_socket = init_sockets(iface_list, num_sockets, fds);
 295
 296        /* Get our IP on server_iface */
 297        if (udhcp_read_interface(argv[2], NULL, &our_nip, NULL))
 298                return 1;
 299
 300        /* Main loop */
 301        while (1) {
 302// reinit stuff from time to time? go back to make_iface_list
 303// every N minutes?
 304                fd_set rfds;
 305                struct timeval tv;
 306                unsigned i;
 307
 308                FD_ZERO(&rfds);
 309                for (i = 0; i < num_sockets; i++)
 310                        FD_SET(fds[i], &rfds);
 311                tv.tv_sec = SELECT_TIMEOUT;
 312                tv.tv_usec = 0;
 313                if (select(max_socket + 1, &rfds, NULL, NULL, &tv) > 0) {
 314                        int packlen;
 315                        struct dhcp_packet dhcp_msg;
 316
 317                        /* from server */
 318                        if (FD_ISSET(fds[0], &rfds)) {
 319                                packlen = udhcp_recv_kernel_packet(&dhcp_msg, fds[0]);
 320//NB: we do not check source port here. Should we?
 321//It should be SERVER_PORT.
 322                                if (packlen > 0) {
 323                                        pass_to_client(&dhcp_msg, packlen, fds);
 324                                }
 325                        }
 326
 327                        /* from clients */
 328                        for (i = 1; i < num_sockets; i++) {
 329                                struct sockaddr_in client_addr;
 330                                socklen_t addr_size;
 331
 332                                if (!FD_ISSET(fds[i], &rfds))
 333                                        continue;
 334
 335                                addr_size = sizeof(client_addr);
 336                                packlen = recvfrom(fds[i], &dhcp_msg, sizeof(dhcp_msg), 0,
 337                                                (struct sockaddr *)(&client_addr), &addr_size);
 338                                if (packlen <= 0)
 339                                        continue;
 340//NB: we do not check source port here. Should we?
 341//It should be CLIENT_PORT for clients.
 342//It can be SERVER_PORT for relay agents (in which case giaddr must be != 0.0.0.0),
 343//but is it even supported to chain relay agents like this?
 344//(we still copy client_addr.port and use it to reply to the port we got request from)
 345
 346                                /* Get our IP on corresponding client_iface */
 347// RFC 1542
 348// 4.1 General BOOTP Processing for Relay Agents
 349// 4.1.1 BOOTREQUEST Messages
 350//   If the relay agent does decide to relay the request, it MUST examine
 351//   the 'giaddr' ("gateway" IP address) field.  If this field is zero,
 352//   the relay agent MUST fill this field with the IP address of the
 353//   interface on which the request was received.  If the interface has
 354//   more than one IP address logically associated with it, the relay
 355//   agent SHOULD choose one IP address associated with that interface and
 356//   use it consistently for all BOOTP messages it relays.  If the
 357//   'giaddr' field contains some non-zero value, the 'giaddr' field MUST
 358//   NOT be modified.  The relay agent MUST NOT, under any circumstances,
 359//   fill the 'giaddr' field with a broadcast address as is suggested in
 360//   [1] (Section 8, sixth paragraph).
 361
 362// but why? what if server can't route such IP? Client ifaces may be, say, NATed!
 363
 364// 4.1.2 BOOTREPLY Messages
 365//   BOOTP relay agents relay BOOTREPLY messages only to BOOTP clients.
 366//   It is the responsibility of BOOTP servers to send BOOTREPLY messages
 367//   directly to the relay agent identified in the 'giaddr' field.
 368// (yeah right, unless it is impossible... see comment above)
 369//   Therefore, a relay agent may assume that all BOOTREPLY messages it
 370//   receives are intended for BOOTP clients on its directly-connected
 371//   networks.
 372//
 373//   When a relay agent receives a BOOTREPLY message, it should examine
 374//   the BOOTP 'giaddr', 'yiaddr', 'chaddr', 'htype', and 'hlen' fields.
 375//   These fields should provide adequate information for the relay agent
 376//   to deliver the BOOTREPLY message to the client.
 377//
 378//   The 'giaddr' field can be used to identify the logical interface from
 379//   which the reply must be sent (i.e., the host or router interface
 380//   connected to the same network as the BOOTP client).  If the content
 381//   of the 'giaddr' field does not match one of the relay agent's
 382//   directly-connected logical interfaces, the BOOTREPLY message MUST be
 383//   silently discarded.
 384                                if (udhcp_read_interface(iface_list[i], NULL, &dhcp_msg.gateway_nip, NULL)) {
 385                                        /* Fall back to our IP on server iface */
 386// this makes more sense!
 387                                        dhcp_msg.gateway_nip = our_nip;
 388                                }
 389// maybe dhcp_msg.hops++? drop packets with too many hops (RFC 1542 says 4 or 16)?
 390                                pass_to_server(&dhcp_msg, packlen, i, fds, &client_addr, &server_addr);
 391                        }
 392                }
 393                xid_expire();
 394        } /* while (1) */
 395
 396        /* return 0; - not reached */
 397}
 398