source: rtems/cpukit/libnetworking/rtems/rtems_dhcp.c @ 083e6d6

4.115
Last change on this file since 083e6d6 was 083e6d6, checked in by Chris Johns <chrisj@…>, on 05/20/15 at 05:21:53

libnetworking: Send the hostname if set in the network configuration.

This allows a suitably configured DHCP server with DDNS to enter
the name into the DNS table making it addressiable via it's host name.

  • Property mode set to 100644
File size: 32.1 KB
Line 
1/*
2 *  DCHP client for RTEMS
3 *  Andrew Bythell, <abythell@nortelnetworks.com>
4 *  based on and uses subroutines from c/src/libnetworking/nfs/bootp_subr.c
5 */
6
7/*
8 * DHCP task added.
9 * Brendan Gannon, <bgannon@cybertec.com.au>
10 */
11
12/*
13 * Added interface to terminate DHCP task, and removed panics.
14 * Arnout Vandecappelle <arnout@mind.be>, Essensium/Mind
15 * Maarten Van Es <maarten@mind.be>, Essensium/Mind
16 */
17
18/*
19 * Copyright (c) 1995 Gordon Ross, Adam Glass
20 * Copyright (c) 1992 Regents of the University of California.
21 * All rights reserved.
22 *
23 * This software was developed by the Computer Systems Engineering group
24 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
25 * contributed to Berkeley.
26 *
27 * Redistribution and use in source and binary forms, with or without
28 * modification, are permitted provided that the following conditions
29 * are met:
30 * 1. Redistributions of source code must retain the above copyright
31 *    notice, this list of conditions and the following disclaimer.
32 * 2. Redistributions in binary form must reproduce the above copyright
33 *    notice, this list of conditions and the following disclaimer in the
34 *    documentation and/or other materials provided with the distribution.
35 * 3. All advertising materials mentioning features or use of this software
36 *    must display the following acknowledgement:
37 *      This product includes software developed by the University of
38 *      California, Lawrence Berkeley Laboratory and its contributors.
39 * 4. Neither the name of the University nor the names of its contributors
40 *    may be used to endorse or promote products derived from this software
41 *    without specific prior written permission.
42 *
43 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
44 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
47 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * SUCH DAMAGE.
54 *
55 */
56
57/*
58 * WARNING:
59 *   This file should be moved into c/src/libnetworking/nfs
60 *   and the following two #ifndef...#endif blocks and the #undefs at
61 *   the end of the file should be removed
62 */
63
64#ifndef __INSIDE_RTEMS_BSD_TCPIP_STACK__
65#define __INSIDE_RTEMS_BSD_TCPIP_STACK__
66#endif
67
68#ifndef __BSD_VISIBLE
69#define __BSD_VISIBLE 1
70#endif
71
72#if HAVE_CONFIG_H
73#include "config.h"
74#endif
75
76#include <rtems.h>
77#include <rtems/error.h>
78#include <rtems/rtems_bsdnet.h>
79#include <rtems/bsdnet/servers.h>
80
81#include <string.h>
82#include <stdlib.h>
83
84#include <sys/ioctl.h>
85#include <sys/param.h>          /* for MAXHOSTNAMELEN */
86#include <sys/systm.h>
87#include <sys/socketvar.h>      /* for socreat() soclose() */
88#include <sys/socket.h>
89
90#include <net/if.h>
91#include <net/if_var.h>
92#include <netinet/in.h>         /* for NBO-HBO conversions */
93#include <net/if_types.h>       /* for IFT_ETHER */
94#include <net/if_dl.h>          /* for LLADDR */
95
96#include <sys/stat.h>
97#include <sys/types.h>
98#include <fcntl.h>
99#include <rtems/mkrootfs.h>
100
101#include "rtems/dhcp.h"
102#include "rtems/bootp.h"
103
104#ifndef EALEN
105#define EALEN 6
106#endif
107
108/*
109 *DHCP flags
110 */
111#define DHCP_BROADCAST 0x8000
112#define DHCP_UNICAST   0x0000
113
114/*
115 * DHCP Op Codes
116 */
117#define DHCP_BOOTREQUEST 1
118#define DHCP_BOOTREPLY   2
119
120/*
121 * DHCP Messages
122 */
123#define DHCP_DISCOVER 1
124#define DHCP_OFFER    2
125#define DHCP_REQUEST  3
126#define DHCP_DECLINE  4
127#define DHCP_ACK      5
128#define DHCP_NACK     6
129#define DHCP_RELEASE  7
130
131/*
132 * DHCP Options
133 */
134#define DHCP_OPTION_PAD    0
135#define DHCP_SUBNET        1
136#define DHCP_GATEWAY       3
137#define DHCP_DNS           6
138#define DHCP_HOST          12
139#define DHCP_DOMAIN_NAME   15
140#define DHCP_NETMASK       28
141#define DHCP_REQUESTED_IP  50
142#define DHCP_LEASE         51
143#define DHCP_MESSAGE       53
144#define DHCP_SERVER        54
145#define DHCP_PARAMETERS    55
146#define DHCP_OPTION_END    255
147
148/*
149 * Definitions from RFC
150 */
151struct dhcp_packet
152{
153  u_int8_t       op;
154  u_int8_t       htype;
155  u_int8_t       hlen;
156  u_int8_t       hops;
157  u_int32_t      xid;
158  u_int16_t      secs;
159  u_int16_t      flags;
160  struct in_addr ciaddr;
161  struct in_addr yiaddr;
162  struct in_addr siaddr;
163  struct in_addr giaddr;
164  unsigned char  chaddr[16];
165  char           sname[64];
166  char           file[128];
167  unsigned char  vend[312];
168};
169
170/*
171 * Variables
172 */
173static int                dhcp_option_overload = 0;
174static char               dhcp_gotgw = 0;
175static char               dhcp_gotnetmask = 0;
176static char               dhcp_gotserver = 0;
177static char               dhcp_gotlogserver = 0;
178static struct sockaddr_in dhcp_netmask;
179static struct sockaddr_in dhcp_gw;
180static char               *dhcp_hostname;
181static int                dhcp_message_type = 0;
182static unsigned long      dhcp_lease_time;
183static unsigned long      dhcp_elapsed_time = 0;
184static const char         dhcp_magic_cookie[4] = { 99, 130, 83, 99 };
185static const char         dhcp_request_parameters[5] = { DHCP_SUBNET,
186                                                         DHCP_GATEWAY,
187                                                         DHCP_DNS,
188                                                         DHCP_HOST,
189                                                         DHCP_DOMAIN_NAME };
190#define NUM_NAMESERVERS \
191  (sizeof rtems_bsdnet_config.name_server / sizeof rtems_bsdnet_config.name_server[0])
192static struct in_addr rtems_dhcpd_nameserver[NUM_NAMESERVERS];
193static int rtems_dhcpd_nameserver_count = 0;
194
195/*
196 * Clean any DNS entries add by a DHCP request.
197 */
198static void
199clean_dns_entries (void)
200{
201  int e;
202  for (e = 0; e < rtems_dhcpd_nameserver_count; ++e)
203  {
204    int n;
205    for (n = 0; n < rtems_bsdnet_nameserver_count; ++ n)
206    {
207      if (memcmp (&rtems_dhcpd_nameserver[e], &rtems_bsdnet_nameserver[n], 4) == 0)
208      {
209        if (n < (NUM_NAMESERVERS - 1))
210          memmove (&rtems_bsdnet_nameserver[n],
211                   &rtems_bsdnet_nameserver[n + 1],
212                   (NUM_NAMESERVERS - n - 1) * 4);
213        --rtems_bsdnet_nameserver_count;
214      }
215    }
216  }
217  rtems_dhcpd_nameserver_count = 0;
218}
219
220/*
221 * Format an IP address in dotted decimal.
222 */
223static void
224format_ip (unsigned long ip, char* buffer)
225{
226  sprintf (buffer,
227           "%lu.%lu.%lu.%lu",
228          (ip >> 24),
229          (ip >> 16) & 0xff,
230          (ip >>  8) & 0xff,
231          (ip        & 0xff));
232
233  return;
234}
235
236/*
237 * Print the IP setup
238 */
239static void
240printsetup (const char     *iface,
241            struct in_addr ip_addr,
242            struct in_addr mask_addr,
243            struct in_addr srv_addr,
244            struct in_addr gw_addr)
245{
246  unsigned long ip;
247  char ip_str[15];
248
249  printf ("dhcpc: %s: ", iface);
250
251  ip = ntohl (ip_addr.s_addr);
252  format_ip (ip, ip_str);
253  printf ("inet: %-15s ", ip_str);
254
255  ip = ntohl (mask_addr.s_addr);
256  format_ip (ip, ip_str);
257  printf ("mask: %-15s\n", ip_str);
258
259  ip = ntohl (srv_addr.s_addr);
260  format_ip (ip, ip_str);
261  printf   ("             srv: %-15s ", ip_str);
262
263  ip = ntohl (gw_addr.s_addr);
264  format_ip (ip, ip_str);
265  printf ("  gw: %-15s\n", ip_str);
266
267  return;
268}
269
270/*
271 * Process options from the DHCP packet.
272 * Based on BOOTP routine.
273 */
274static void
275process_options (unsigned char *optbuf, int optbufSize)
276{
277  int j = 0;
278  int len;
279  int code, ncode;
280  char *p;
281
282  dhcp_message_type = 0;
283
284  ncode = optbuf[0];
285  while (j < optbufSize)
286  {
287    code = optbuf[j] = ncode;
288    if (code == 255)
289      return;
290    if (code == 0)
291    {
292      j++;
293      continue;
294    }
295    len = optbuf[j + 1];
296    j += 2;
297
298    if ((len + j) >= optbufSize)
299    {
300      printf ("Truncated field for code %d", code);
301      return;
302    }
303
304    ncode = optbuf[j + len];
305    optbuf[j + len] = '\0';
306    p = (char*) &optbuf[j];
307    j += len;
308
309    /*
310     * Process the option
311     */
312    switch (code)
313    {
314      case 1:
315        /* Subnet mask */
316        if (len != 4) {
317          printf ("dhcpc: subnet mask len is %d\n", len);
318          continue;
319        }
320        memcpy (&dhcp_netmask.sin_addr, p, 4);
321        dhcp_gotnetmask = 1;
322        break;
323
324      case 2:
325        /* Time offset */
326        if (len != 4) {
327          printf ("dhcpc: time offset len is %d\n", len);
328          continue;
329        }
330        memcpy (&rtems_bsdnet_timeoffset, p, 4);
331        rtems_bsdnet_timeoffset = ntohl (rtems_bsdnet_timeoffset);
332        break;
333
334      case 3:
335        /* Routers */
336        if (len % 4) {
337          printf ("dhcpc: Router Len is %d\n", len);
338          continue;
339        }
340        if (len > 0)
341        {
342          memcpy (&dhcp_gw.sin_addr, p, 4);
343          dhcp_gotgw = 1;
344        }
345        break;
346
347      case 42:
348        /* NTP servers */
349        if (len % 4) {
350          printf ("dhcpc: time server Len is %d\n", len);
351          continue;
352        }
353        {
354          int tlen = 0;
355          while ((tlen < len) &&
356                 (rtems_bsdnet_ntpserver_count <
357                  sizeof rtems_bsdnet_config.ntp_server /
358                  sizeof rtems_bsdnet_config.ntp_server[0]))
359          {
360            memcpy (&rtems_bsdnet_ntpserver[rtems_bsdnet_ntpserver_count],
361                    p + tlen, 4);
362            rtems_bsdnet_ntpserver_count++;
363            tlen += 4;
364          }
365        }
366        break;
367
368      case 6:
369        /* Domain Name servers */
370        if (len % 4) {
371          printf ("dhcpc: DNS Len is %d\n", len);
372          continue;
373        }
374        {
375          int dlen = 0;
376          while ((dlen < len) &&
377                 (rtems_dhcpd_nameserver_count < NUM_NAMESERVERS) &&
378                 (rtems_bsdnet_nameserver_count < NUM_NAMESERVERS))
379          {
380            memcpy (&rtems_dhcpd_nameserver
381                    [rtems_dhcpd_nameserver_count], p + dlen, 4);
382            rtems_dhcpd_nameserver_count++;
383            memcpy (&rtems_bsdnet_nameserver
384                    [rtems_bsdnet_nameserver_count], p + dlen, 4);
385            rtems_bsdnet_nameserver_count++;
386            dlen += 4;
387          }
388        }
389        break;
390
391      case 12:
392        /* Host name */
393        if (len >= MAXHOSTNAMELEN) {
394          printf ("dhcpc: hostname >= %d bytes\n", MAXHOSTNAMELEN);
395          len = MAXHOSTNAMELEN-1;
396        }
397        if (sethostname (p, len) < 0)
398          printf ("dhcpc: can't set host name");
399        if (dhcp_hostname != NULL)
400        {
401          dhcp_hostname = realloc (dhcp_hostname, len);
402          strncpy (dhcp_hostname, p, len);
403        }
404        else
405          dhcp_hostname = strndup (p, len);
406        break;
407
408      case 7:
409        /* Log servers */
410        if (len % 4) {
411          printf ("dhcpc: Log server Len is %d\n", len);
412          continue;
413        }
414        if (len > 0)
415        {
416          memcpy (&rtems_bsdnet_log_host_address, p, 4);
417          dhcp_gotlogserver = 1;
418        }
419        break;
420
421      case 15:
422        /* Domain name */
423        if (p[0])
424        {
425          rtems_bsdnet_domain_name = strdup (p);
426        }
427        break;
428
429      case 16:          /* Swap server IP address. unused */
430        break;
431
432      case 50:
433        /* DHCP Requested IP Address */
434        if (len != 4)
435          printf ("dhcpc: DHCP option requested IP len is %d", len);
436        /*
437         * although nothing happens here, this case keeps the client
438         * from complaining about unknown options.  The Requested IP
439         * is necessary to return to the server for a DHCP REQUEST
440         */
441        break;
442
443      case 51:
444        /* DHCP Lease Length */
445        if (len != 4) {
446          printf ("dhcpc: DHCP option lease-length len is %d", len);
447          continue;
448        }
449        memcpy (&dhcp_lease_time, &p[0], 4);
450        dhcp_lease_time = ntohl (dhcp_lease_time);
451        break;
452
453      case 52:
454        /* DHCP option override */
455        if (len != 1) {
456          printf ("dhcpc: DHCP option overload len is %d", len);
457          continue;
458        }
459        dhcp_option_overload = p[0];
460        break;
461
462      case 53:
463        /* DHCP message */
464        if (len != 1) {
465          printf ("dhcpc: DHCP message len is %d", len);
466          continue;
467        }
468        dhcp_message_type = p[0];
469        break;
470
471      case 128:         /* Site-specific option for DHCP servers that
472                   *   a) don't supply tag 54
473                   * and
474                   *   b) don't supply the server address in siaddr
475                   * For example, on Solaris 2.6 in.dhcpd, include in the dhcptab:
476                   *    Bootsrv s Site,128,IP,1,1
477                   * and use that symbol in the macro that defines the client:
478                   *    Bootsrv=<tftp-server-ip-address>
479                   */
480      case 54:
481        /* DHCP server */
482        if (len != 4) {
483          printf ("dhcpc: DHCP server len is %d", len);
484          continue;
485        }
486        memcpy (&rtems_bsdnet_bootp_server_address, p, 4);
487        dhcp_gotserver = 1;
488        break;
489
490      case 66:
491        /* DHCP server name option */
492        if (p[0])
493          rtems_bsdnet_bootp_server_name = strdup (p);
494        break;
495
496      case 67:
497        /* DHCP bootfile option */
498        if (p[0])
499          rtems_bsdnet_bootp_boot_file_name = strdup (p);
500        break;
501
502      default:
503        break;
504    }
505  }
506}
507
508/*
509 * Generate the packet for a DHCP DISCOVER.
510 */
511static int
512dhcp_discover_req (struct dhcp_packet* call,
513                   struct sockaddr_dl *sdl,
514                   unsigned long *xid)
515{
516  int len = 0;
517
518  memset (call, 0, sizeof (struct dhcp_packet));
519
520  /*
521   * Send a DHCP DISCOVER Message
522   */
523  call->op = DHCP_BOOTREQUEST;
524  call->htype = 1;              /* 10mb ethernet */
525  call->hlen = sdl->sdl_alen;   /* Hardware address length */
526  call->hops = 0;
527  (*xid)++;
528  call->xid = htonl (*xid);
529  call->flags = htons (DHCP_BROADCAST);
530
531  memcpy (&call->chaddr, LLADDR (sdl), sdl->sdl_alen);
532
533  /*
534   * Magic cookie.
535   */
536  memcpy (&call->vend[len], dhcp_magic_cookie, sizeof (dhcp_magic_cookie));
537  len += sizeof (dhcp_magic_cookie);
538
539  /*
540   * DHCP Message type.
541   */
542  call->vend[len++] = DHCP_MESSAGE;
543  call->vend[len++] = 1;
544  call->vend[len++] = DHCP_DISCOVER;
545
546  /*
547   * If a host name is set add it to the request.
548   */
549  if (rtems_bsdnet_config.hostname && \
550      (strlen (rtems_bsdnet_config.hostname) > 1) &&
551      (strlen (rtems_bsdnet_config.hostname) < 32)) {
552    call->vend[len++] = DHCP_HOST;
553    call->vend[len++] = strlen (rtems_bsdnet_config.hostname);
554    memcpy (&call->vend[len],
555            rtems_bsdnet_config.hostname,
556            strlen (rtems_bsdnet_config.hostname));
557    len += strlen (rtems_bsdnet_config.hostname);
558  }
559
560  /*
561   * DHCP Parameter request list
562   */
563  call->vend[len++] = DHCP_PARAMETERS;
564  call->vend[len++] = sizeof (dhcp_request_parameters);
565  memcpy (&call->vend[len], &dhcp_request_parameters, sizeof (dhcp_request_parameters));
566  len += sizeof (dhcp_request_parameters);
567
568  /*
569   * Lease time.
570   */
571  call->vend[len++] = DHCP_LEASE;
572  call->vend[len++] = 4;
573  memset (&call->vend[len], 0xFF, 4);   /* request infinite lease time */
574  len += 4;
575
576  /*
577   * End.
578   */
579  call->vend[len++] = DHCP_OPTION_END;
580  call->secs = 0;
581
582  return len;
583}
584
585/*
586 * Generate the packet for a DHCP REQUEST.
587 */
588static int
589dhcp_request_req (struct dhcp_packet* call,
590                  struct dhcp_packet* reply,
591                  struct sockaddr_dl *sdl,
592                  int broadcast)
593{
594  int           len = 0;
595  unsigned long temp;
596  char          *hostname;
597
598  memset (call, 0, sizeof (struct dhcp_packet));
599
600  /*
601   * Send a DHCP REQUEST Message
602   */
603  call->op = DHCP_BOOTREQUEST;
604  call->htype = 1;              /* 10mb ethernet */
605  call->hlen = sdl->sdl_alen;   /* Hardware address length */
606  call->hops = 0;
607  call->xid = reply->xid;
608  if (broadcast)
609    call->flags = htons (DHCP_BROADCAST);
610  else
611  {
612    call->flags = htons (DHCP_UNICAST);
613    call->ciaddr = reply->yiaddr;
614  }
615  memcpy (&call->chaddr, LLADDR (sdl), sdl->sdl_alen);
616
617  /*
618   * Magic cookie.
619   */
620  memcpy (&call->vend[len], dhcp_magic_cookie, sizeof (dhcp_magic_cookie));
621  len += sizeof (dhcp_magic_cookie);
622
623  /*
624   * DHCP Message type.
625   */
626  call->vend[len++] = DHCP_MESSAGE;
627  call->vend[len++] = 1;
628  call->vend[len++] = DHCP_REQUEST;
629
630  /*
631   * DHCP server
632   */
633  if (broadcast)
634  {
635    call->vend[len++] = DHCP_SERVER;
636    call->vend[len++] = sizeof (rtems_bsdnet_bootp_server_address);
637    memcpy (&call->vend[len], &rtems_bsdnet_bootp_server_address,
638            sizeof (rtems_bsdnet_bootp_server_address));
639    len += sizeof (rtems_bsdnet_bootp_server_address);
640  }
641
642  /*
643   * Requested IP
644   */
645  call->vend[len++] = DHCP_REQUESTED_IP;
646  call->vend[len++] = sizeof (reply->yiaddr);
647  memcpy (&call->vend[len], &reply->yiaddr, sizeof (reply->yiaddr));
648  len += sizeof (reply->yiaddr);
649
650  /*
651   * DHCP Parameter request list
652   */
653  call->vend[len++] = DHCP_PARAMETERS;
654  call->vend[len++] = sizeof (dhcp_request_parameters);
655  memcpy (&call->vend[len], &dhcp_request_parameters, sizeof (dhcp_request_parameters));
656  len += sizeof (dhcp_request_parameters);
657
658  /*
659   * Lease time.
660   * For the REQUEST, return the lease time the server offered.
661   */
662  call->vend[len++] = DHCP_LEASE;
663  call->vend[len++] = 4;
664  temp = htonl (dhcp_lease_time);
665  memcpy (&call->vend[len], &temp, sizeof (unsigned long));
666  len += 4;
667
668  /*
669   * Host name.
670   */
671  hostname = malloc (MAXHOSTNAMELEN, 0, M_NOWAIT);
672  if (hostname != NULL)
673  {
674    if (gethostname (hostname, MAXHOSTNAMELEN) == 0)
675    {
676      call->vend[len++] = DHCP_HOST;
677      call->vend[len++] = strlen (hostname);
678      strcpy ((char*) &call->vend[len], hostname);
679      len += strlen (hostname);
680    }
681    free (hostname, 0);
682  }
683
684  /*
685   * End.
686   */
687  call->vend[len++] = DHCP_OPTION_END;
688  call->secs = 0;
689
690  return len;
691}
692
693/*
694 * Variables for the DHCP task.
695 */
696static struct dhcp_packet dhcp_req;
697static rtems_id           dhcp_task_id;
698
699/*
700 * The DHCP task counts until half the lease time has expired.
701 * When this period is up, it sends a DHCP REQUEST packet to the
702 * server again to renew the lease.
703 * If the lease is renewed, the task starts counting again.
704 * If the lease is not renewed, the task retries until it is.
705 *
706 * The task will not rebind if the lease is not renewed.
707 */
708static void
709dhcp_task (rtems_task_argument _sdl)
710{
711  unsigned long       count;
712  struct dhcp_packet  call;
713  struct sockaddr_dl  *sdl;
714  rtems_event_set     event_out;
715  unsigned int        timeout = 0;
716  int                 error;
717  struct proc *procp = NULL;
718  rtems_status_code   ev_st;
719
720  sdl = (struct sockaddr_dl *) _sdl;
721
722  count = dhcp_elapsed_time;
723
724  while (true)
725  {
726    /*
727     * Sleep until the next poll
728     */
729    timeout = RTEMS_MILLISECONDS_TO_TICKS (1000);
730    ev_st = rtems_event_receive (RTEMS_EVENT_0,
731                                 RTEMS_WAIT | RTEMS_EVENT_ANY,
732                                 timeout, &event_out);
733
734    /*
735     * Check if not a poll timeout. So when ANY event received, exit task.
736     * Actually, only event RTEMS_EVENT_0 sent from rtem_dhcp_failsafe.c
737     * if "failsafe" dhcp enabled when interface down.  Otherwise, no
738     * event should occur, just timeout.
739     */
740    if(ev_st != RTEMS_TIMEOUT)
741        break;
742
743    count++;
744
745    if (count >= (dhcp_lease_time / 2))
746    {
747      rtems_bsdnet_semaphore_obtain ();
748
749      dhcp_request_req (&call, &dhcp_req, sdl, true);
750
751      /*
752       * Send the Request.
753       */
754      error = bootpc_call ((struct bootp_packet *)&call, (struct bootp_packet *)&dhcp_req, procp);
755      if (error) {
756        rtems_bsdnet_semaphore_release ();
757        printf ("DHCP call failed -- error %d", error);
758        continue;
759      }
760
761      /*
762       * Check for DHCP ACK/NACK
763       */
764      if (memcmp (&dhcp_req.vend[0],
765                  dhcp_magic_cookie,
766                  sizeof (dhcp_magic_cookie)) != 0)
767      {
768        rtems_bsdnet_semaphore_release ();
769        printf ("DHCP server did not send Magic Cookie.\n");
770        continue;
771      }
772
773      /*
774       * We have an ack. Clear the DNS entries that have been assigned by a previous
775       * DHCP request.
776       */
777      clean_dns_entries ();
778
779      /*
780       * Process this requests options.
781       */
782      process_options (&dhcp_req.vend[4], sizeof (dhcp_req.vend) - 4);
783
784      if (dhcp_message_type != DHCP_ACK)
785      {
786        rtems_bsdnet_semaphore_release ();
787        printf ("DHCP server did not accept the DHCP request");
788        continue;
789      }
790
791      rtems_bsdnet_semaphore_release ();
792
793      count = 0;
794    }
795  }
796
797
798  dhcp_task_id = 0;
799  printf ("dhcpc: exiting lease renewal task.\n");
800  rtems_task_delete( RTEMS_SELF);
801
802}
803
804/*
805 * Start the DHCP task.
806 */
807static rtems_status_code
808dhcp_start_task (struct sockaddr_dl *sdl,
809                 struct dhcp_packet *reply,
810                 int priority)
811{
812  rtems_status_code sc;
813
814  memcpy (&dhcp_req, reply, sizeof (struct dhcp_packet));
815
816  sc = rtems_task_create (rtems_build_name ('d','h','c','p'),
817                          priority,
818                          2048,
819                          RTEMS_PREEMPT |
820                          RTEMS_NO_TIMESLICE |
821                          RTEMS_NO_ASR |
822                          RTEMS_INTERRUPT_LEVEL (0),
823                          RTEMS_LOCAL,
824                          &dhcp_task_id);
825
826  if (sc != RTEMS_SUCCESSFUL)
827    return sc;
828
829  sc = rtems_task_start (dhcp_task_id,
830                         dhcp_task,
831                         (rtems_task_argument) sdl);
832
833  if (sc != RTEMS_SUCCESSFUL)
834    return sc;
835
836  return RTEMS_SUCCESSFUL;
837}
838
839/*
840 * Check if the chosen interface already has an IP.
841 */
842static int
843dhcp_interface_has_ip (struct ifreq *ireq, struct socket *so, struct proc *procp)
844{
845  struct sockaddr_in* sin;
846  int error;
847
848  /*
849   * Check if the interface is already up.
850   */
851  error = ifioctl(so, SIOCGIFFLAGS, (caddr_t)ireq, procp);
852  if (error)
853    return 0;
854
855  if ((ireq->ifr_flags & IFF_UP) == 0)
856    return 0;
857
858  sin = (struct sockaddr_in *)&ireq->ifr_addr;
859  bzero ((caddr_t)sin, sizeof (struct sockaddr_in));
860  sin->sin_len = sizeof (struct sockaddr_in);
861  sin->sin_family = AF_INET;
862  error = ifioctl (so, SIOCGIFADDR, (caddr_t)ireq, procp);
863  if (error)
864    return 0;
865
866  if (sin->sin_addr.s_addr != 0)
867    return 1;
868
869  return 0;
870}
871
872/*
873 *  DCHP Client Routine
874 *    - The first DHCP offer is always accepted
875 *    - No DHCP DECLINE message is sent if ARPing fails
876 *
877 *    return value:
878 *    0: ok
879 *    < 0: failed to startup or configure interface
880 */
881static int
882dhcp_init (int update_files)
883{
884  struct dhcp_packet   call;
885  struct dhcp_packet   reply;
886  static unsigned long xid = ~0xFF;
887  struct ifreq         ireq;
888  struct ifnet         *ifp;
889  struct socket        *so;
890  int                  error;
891  struct sockaddr_in   myaddr;
892  struct ifaddr        *ifa;
893  struct sockaddr_dl   *sdl = NULL;
894  struct proc          *procp = NULL;
895
896  clean_dns_entries();
897
898  /*
899   * If we are to update the files create the root
900   * file structure.
901   */
902  if (update_files)
903    if (rtems_create_root_fs () < 0) {
904      printf("Error creating the root filesystem.\nFile not created.\n");
905      update_files = 0;
906    }
907
908  /*
909   * Find a network interface.
910   */
911  for (ifp = ifnet; ifp != 0; ifp = ifp->if_next)
912    if ((ifp->if_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) == 0)
913      break;
914  if (ifp == NULL){
915    printf ("dhcpc_init: no suitable interface\n");
916    return -1;
917  }
918
919  memset (&ireq, 0, sizeof (ireq));
920  sprintf (ireq.ifr_name, "%s%d", ifp->if_name, ifp->if_unit);
921
922  if ((error = socreate (AF_INET, &so, SOCK_DGRAM, 0, procp)) != 0) {
923    printf ("dhcpc_init: socreate, error: %s\n", strerror(error));
924    return -1;
925  }
926
927  if (!dhcp_interface_has_ip (&ireq, so, procp))
928    bootpc_fakeup_interface (&ireq, so, procp);
929
930  /*
931   * Get HW address
932   */
933  for (ifa = ifp->if_addrlist; ifa; ifa = ifa->ifa_next)
934    if (ifa->ifa_addr->sa_family == AF_LINK &&
935        (sdl = ((struct sockaddr_dl *) ifa->ifa_addr)) &&
936        sdl->sdl_type == IFT_ETHER)
937      break;
938
939  if (!sdl){
940    printf ("dhcpc_init: Unable to find HW address\n");
941    soclose (so);
942    return -1;
943  }
944  if (sdl->sdl_alen != EALEN) {
945    printf ("dhcpc_init: HW address len is %d, expected value is %d\n",
946           sdl->sdl_alen, EALEN);
947    soclose (so);
948    return -1;
949  }
950
951  /*
952   * Build the DHCP Discover
953   */
954  dhcp_discover_req (&call, sdl, &xid);
955
956  /*
957   * Send the Discover.
958   */
959  error = bootpc_call ((struct bootp_packet *)&call, (struct bootp_packet *)&reply, procp);
960  if (error) {
961    printf ("BOOTP call failed -- %s\n", strerror(error));
962    soclose (so);
963    return -1;
964  }
965
966  /*
967   * Check for DHCP OFFER
968   */
969  if (memcmp (&reply.vend[0], dhcp_magic_cookie, sizeof (dhcp_magic_cookie)) != 0) {
970    printf ("DHCP server did not send Magic Cookie.\n");
971    soclose (so);
972    return -1;
973  }
974
975  process_options (&reply.vend[4], sizeof (reply.vend) - 4);
976
977  if (dhcp_message_type != DHCP_OFFER) {
978    printf ("DHCP server did not send a DHCP Offer.\n");
979    soclose (so);
980    return -1;
981  }
982
983  /*
984   * Send a DHCP REQUEST
985   */
986  dhcp_request_req (&call, &reply, sdl, true);
987
988  error = bootpc_call ((struct bootp_packet *)&call, (struct bootp_packet *)&reply, procp);
989  if (error) {
990    printf ("BOOTP call failed -- %s\n", strerror(error));
991    soclose (so);
992    return -1;
993  }
994
995  /*
996   * Check for DHCP ACK/NACK
997   */
998  if (memcmp (&reply.vend[0], dhcp_magic_cookie, sizeof (dhcp_magic_cookie)) != 0) {
999    printf ("DHCP server did not send Magic Cookie.\n");
1000    soclose (so);
1001    return -1;
1002  }
1003
1004  process_options (&reply.vend[4], sizeof (reply.vend) - 4);
1005
1006  if (dhcp_message_type != DHCP_ACK) {
1007    printf ("DHCP server did not accept the DHCP request\n");
1008    soclose (so);
1009    return -1;
1010  }
1011
1012  /*
1013   * Initialize network address structures
1014   */
1015  memset (&myaddr, 0, sizeof (myaddr));
1016  memset (&dhcp_netmask, 0, sizeof (dhcp_netmask));
1017  memset (&dhcp_gw, 0, sizeof (dhcp_gw));
1018  myaddr.sin_len = sizeof (myaddr);
1019  myaddr.sin_family = AF_INET;
1020  dhcp_netmask.sin_len = sizeof (dhcp_netmask);
1021  dhcp_netmask.sin_family = AF_INET;
1022  dhcp_gw.sin_len = sizeof (dhcp_gw);
1023  dhcp_gw.sin_family = AF_INET;
1024
1025  /*
1026   * Set our address
1027   */
1028  myaddr.sin_addr = reply.yiaddr;
1029
1030  /*
1031   * Process BOOTP/DHCP options
1032   */
1033  if (memcmp (&reply.vend[0], dhcp_magic_cookie, sizeof (dhcp_magic_cookie)) == 0)
1034    process_options (&reply.vend[4], sizeof (reply.vend) - 4);
1035
1036  if (dhcp_option_overload & 1)
1037    process_options ((unsigned char*) reply.file, sizeof reply.file);
1038  else
1039    if (reply.file[0])
1040      rtems_bsdnet_bootp_boot_file_name = strdup (reply.file);
1041
1042  if (dhcp_option_overload & 2)
1043    process_options ((unsigned char*) reply.sname, sizeof reply.sname);
1044  else
1045    if (reply.sname[0])
1046      rtems_bsdnet_bootp_server_name = strdup (reply.sname);
1047
1048  /*
1049   * Use defaults if values were not supplied by BOOTP/DHCP options
1050   */
1051  if (!dhcp_gotnetmask)
1052  {
1053    if (IN_CLASSA (ntohl (myaddr.sin_addr.s_addr)))
1054      dhcp_netmask.sin_addr.s_addr = htonl (IN_CLASSA_NET);
1055    else if (IN_CLASSB (ntohl (myaddr.sin_addr.s_addr)))
1056      dhcp_netmask.sin_addr.s_addr = htonl (IN_CLASSB_NET);
1057    else
1058      dhcp_netmask.sin_addr.s_addr = htonl (IN_CLASSC_NET);
1059  }
1060
1061  if (!dhcp_gotserver)
1062    rtems_bsdnet_bootp_server_address = reply.siaddr;
1063
1064  if (!dhcp_gotgw)
1065    dhcp_gw.sin_addr = reply.giaddr;
1066
1067  if (!dhcp_gotlogserver)
1068    rtems_bsdnet_log_host_address = rtems_bsdnet_bootp_server_address;
1069
1070  printsetup (ifp->if_name, myaddr.sin_addr, dhcp_netmask.sin_addr,
1071              rtems_bsdnet_bootp_server_address, dhcp_gw.sin_addr);
1072
1073  /*
1074   * Update the files if we are asked too.
1075   */
1076  if (update_files) {
1077    char *dn = rtems_bsdnet_domain_name;
1078    char *hn = dhcp_hostname;
1079    if (!dn)
1080      dn = "mydomain";
1081    if (!hn)
1082    {
1083      hn = "me";
1084      sethostname (hn, strlen (hn));
1085    }
1086    rtems_rootfs_append_host_rec(myaddr.sin_addr.s_addr, hn, dn);
1087
1088    /*
1089     * Should the given domainname be used here ?
1090     */
1091    if (dhcp_gotserver) {
1092      if (rtems_bsdnet_bootp_server_name)
1093        hn = rtems_bsdnet_bootp_server_name;
1094      else
1095        hn = "bootps";
1096      rtems_rootfs_append_host_rec(rtems_bsdnet_bootp_server_address.s_addr,
1097                                   hn, dn);
1098    }
1099
1100    if (dhcp_gotlogserver) {
1101      rtems_rootfs_append_host_rec(rtems_bsdnet_log_host_address.s_addr,
1102                                   "logs", dn);
1103    }
1104
1105    /*
1106     * Setup the DNS configuration file /etc/resolv.conf.
1107     */
1108    if (rtems_bsdnet_nameserver_count) {
1109      int        i;
1110      char       buf[64];
1111      const char *bufl[1];
1112
1113      bufl[0] = buf;
1114
1115#define MKFILE_MODE (S_IRUSR | S_IWUSR | S_IWGRP | S_IRGRP | S_IROTH)
1116
1117      if (rtems_bsdnet_domain_name &&
1118          (strlen(rtems_bsdnet_domain_name) < (sizeof(buf) - 1))) {
1119        strcpy(buf, "search ");
1120        strcat(buf, rtems_bsdnet_domain_name);
1121        strcat(buf, "\n");
1122        rtems_rootfs_file_append ("/etc/resolv.conf", MKFILE_MODE, 1, bufl);
1123      }
1124
1125      for (i = 0; i < rtems_bsdnet_nameserver_count; i++) {
1126        strcpy(buf, "nameserver ");
1127        strcat(buf, inet_ntoa(rtems_bsdnet_ntpserver[i]));
1128        strcat(buf, "\n");
1129        if (rtems_rootfs_file_append ("/etc/resolv.conf", MKFILE_MODE, 1, bufl))
1130          break;
1131      }
1132    }
1133  }
1134
1135  /*
1136   * Configure the interface with the new settings
1137   */
1138  error = bootpc_adjust_interface (&ireq, so,
1139                                   &myaddr, &dhcp_netmask, &dhcp_gw, procp);
1140
1141  /*
1142   * Start the DHCP task if the lease isn't infinite.
1143   */
1144  if (dhcp_lease_time != 0xffffffff)
1145    dhcp_start_task (sdl, &reply, 150);
1146
1147  soclose (so);
1148
1149  return 0;
1150}
1151
1152/*
1153 *
1154 *  RTEMS Entry point to DHCP client
1155 *
1156 */
1157void rtems_bsdnet_do_dhcp (void)
1158{
1159  bool update = true;
1160  rtems_bsdnet_semaphore_obtain ();
1161  while( dhcp_init (update) < 0 ) {
1162    update = false;
1163    rtems_bsdnet_semaphore_release();
1164    rtems_task_wake_after(RTEMS_MILLISECONDS_TO_TICKS(1000));
1165    rtems_bsdnet_semaphore_obtain ();
1166  }
1167  rtems_bsdnet_semaphore_release ();
1168}
1169
1170int rtems_bsdnet_do_dhcp_timeout( void )
1171{
1172  int return_value;
1173
1174  rtems_bsdnet_semaphore_obtain ();
1175  return_value = dhcp_init (false);
1176  rtems_bsdnet_semaphore_release ();
1177
1178  return return_value;
1179}
1180
1181void rtems_bsdnet_dhcp_down (void)
1182{
1183   if(dhcp_task_id != 0) {
1184     rtems_event_send (dhcp_task_id, RTEMS_EVENT_0);
1185   }
1186}
1187
1188void
1189rtems_bsdnet_do_dhcp_refresh_only (unsigned long xid,
1190                                   unsigned long lease_time,
1191                                   unsigned long elapsed_time,
1192                                   unsigned long ip_address,
1193                                   unsigned long srv_address,
1194                                   const char*   hostname)
1195{
1196  struct dhcp_packet reply;
1197  struct ifnet       *ifp = NULL;
1198  struct ifaddr      *ifa = NULL;
1199  struct sockaddr_dl *sdl = NULL;
1200  struct sockaddr_in *sin = NULL;
1201  int                match = 0;
1202  struct ifnet       *mtif = NULL;
1203
1204  /*
1205   * If an infinite lease has been granted, no task is needed.
1206   */
1207  if (lease_time == 0xffffffff)
1208    return;
1209
1210  /*
1211   * Find a network interface.
1212   */
1213  for (ifp = ifnet; (ifp != NULL) && !match; ifp = ifp->if_next)
1214    if ((ifp->if_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) == 0)
1215      for (ifa = ifp->if_addrlist; ifa; ifa = ifa->ifa_next)
1216        if (ifa->ifa_addr->sa_family == AF_INET)
1217        {
1218          sin = (struct sockaddr_in *) ifa->ifa_addr;
1219          if (sin->sin_addr.s_addr == htonl (ip_address))
1220          {
1221            mtif = ifp;
1222            match = 1;
1223            break;
1224          }
1225        }
1226
1227  if (!match) {
1228    printf ("dhcpc: no matching interface\n");
1229    return;
1230  }
1231
1232  for (ifa = mtif->if_addrlist; ifa != NULL; ifa = ifa->ifa_next)
1233    if (ifa->ifa_addr->sa_family == AF_LINK &&
1234        (sdl = ((struct sockaddr_dl *) ifa->ifa_addr)) &&
1235        sdl->sdl_type == IFT_ETHER)
1236      break;
1237
1238  if (!match) {
1239    printf ("dhcpc: no matching interface address\n");
1240    return;
1241  }
1242
1243  /*
1244   * Set up given values in a simulated DHCP reply.
1245   */
1246  memset (&reply, 0x00, sizeof (reply));
1247  reply.xid = htonl (xid);
1248  reply.yiaddr.s_addr = htonl (ip_address);
1249  reply.siaddr.s_addr = htonl (srv_address);
1250  if (reply.siaddr.s_addr != rtems_bsdnet_bootp_server_address.s_addr)
1251  {
1252    memcpy (&rtems_bsdnet_bootp_server_address, &reply.siaddr,
1253            sizeof (reply.siaddr));
1254  }
1255
1256  dhcp_lease_time = lease_time;
1257  dhcp_elapsed_time = elapsed_time;
1258
1259  if (hostname)
1260  {
1261    sethostname ((char *) hostname, strlen (hostname));
1262    dhcp_hostname = bootp_strdup_realloc (dhcp_hostname, hostname);
1263  }
1264
1265  dhcp_start_task (sdl, &reply, 150);
1266}
Note: See TracBrowser for help on using the repository browser.