source: rtems/cpukit/libnetworking/rtems/rtems_dhcp.c @ da10694

4.115
Last change on this file since da10694 was 88c74ab, checked in by Sebastian Huber <sebastian.huber@…>, on 07/25/13 at 13:10:11

score: Merge tod implementation into one file

Delete TOD_MICROSECONDS_PER_SECOND, TOD_MICROSECONDS_TO_TICKS() and
TOD_MILLISECONDS_TO_TICKS().

  • Property mode set to 100644
File size: 31.6 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   * DHCP Parameter request list
548   */
549  call->vend[len++] = DHCP_PARAMETERS;
550  call->vend[len++] = sizeof (dhcp_request_parameters);
551  memcpy (&call->vend[len], &dhcp_request_parameters, sizeof (dhcp_request_parameters));
552  len += sizeof (dhcp_request_parameters);
553
554  /*
555   * Lease time.
556   */
557  call->vend[len++] = DHCP_LEASE;
558  call->vend[len++] = 4;
559  memset (&call->vend[len], 0xFF, 4);   /* request infinite lease time */
560  len += 4;
561
562  /*
563   * End.
564   */
565  call->vend[len++] = DHCP_OPTION_END;
566  call->secs = 0;
567
568  return len;
569}
570
571/*
572 * Generate the packet for a DHCP REQUEST.
573 */
574static int
575dhcp_request_req (struct dhcp_packet* call,
576                  struct dhcp_packet* reply,
577                  struct sockaddr_dl *sdl,
578                  int broadcast)
579{
580  int           len = 0;
581  unsigned long temp;
582  char          *hostname;
583
584  memset (call, 0, sizeof (struct dhcp_packet));
585
586  /*
587   * Send a DHCP REQUEST Message
588   */
589  call->op = DHCP_BOOTREQUEST;
590  call->htype = 1;              /* 10mb ethernet */
591  call->hlen = sdl->sdl_alen;   /* Hardware address length */
592  call->hops = 0;
593  call->xid = reply->xid;
594  if (broadcast)
595    call->flags = htons (DHCP_BROADCAST);
596  else
597  {
598    call->flags = htons (DHCP_UNICAST);
599    call->ciaddr = reply->yiaddr;
600  }
601  memcpy (&call->chaddr, LLADDR (sdl), sdl->sdl_alen);
602
603  /*
604   * Magic cookie.
605   */
606  memcpy (&call->vend[len], dhcp_magic_cookie, sizeof (dhcp_magic_cookie));
607  len += sizeof (dhcp_magic_cookie);
608
609  /*
610   * DHCP Message type.
611   */
612  call->vend[len++] = DHCP_MESSAGE;
613  call->vend[len++] = 1;
614  call->vend[len++] = DHCP_REQUEST;
615
616  /*
617   * DHCP server
618   */
619  if (broadcast)
620  {
621    call->vend[len++] = DHCP_SERVER;
622    call->vend[len++] = sizeof (rtems_bsdnet_bootp_server_address);
623    memcpy (&call->vend[len], &rtems_bsdnet_bootp_server_address,
624            sizeof (rtems_bsdnet_bootp_server_address));
625    len += sizeof (rtems_bsdnet_bootp_server_address);
626  }
627
628  /*
629   * Requested IP
630   */
631  call->vend[len++] = DHCP_REQUESTED_IP;
632  call->vend[len++] = sizeof (reply->yiaddr);
633  memcpy (&call->vend[len], &reply->yiaddr, sizeof (reply->yiaddr));
634  len += sizeof (reply->yiaddr);
635
636  /*
637   * DHCP Parameter request list
638   */
639  call->vend[len++] = DHCP_PARAMETERS;
640  call->vend[len++] = sizeof (dhcp_request_parameters);
641  memcpy (&call->vend[len], &dhcp_request_parameters, sizeof (dhcp_request_parameters));
642  len += sizeof (dhcp_request_parameters);
643
644  /*
645   * Lease time.
646   * For the REQUEST, return the lease time the server offered.
647   */
648  call->vend[len++] = DHCP_LEASE;
649  call->vend[len++] = 4;
650  temp = htonl (dhcp_lease_time);
651  memcpy (&call->vend[len], &temp, sizeof (unsigned long));
652  len += 4;
653
654  /*
655   * Host name.
656   */
657  hostname = malloc (MAXHOSTNAMELEN, 0, M_NOWAIT);
658  if (hostname != NULL)
659  {
660    if (gethostname (hostname, MAXHOSTNAMELEN) == 0)
661    {
662      call->vend[len++] = DHCP_HOST;
663      call->vend[len++] = strlen (hostname);
664      strcpy ((char*) &call->vend[len], hostname);
665      len += strlen (hostname);
666    }
667    free (hostname, 0);
668  }
669
670  /*
671   * End.
672   */
673  call->vend[len++] = DHCP_OPTION_END;
674  call->secs = 0;
675
676  return len;
677}
678
679/*
680 * Variables for the DHCP task.
681 */
682static struct dhcp_packet dhcp_req;
683static rtems_id           dhcp_task_id;
684
685/*
686 * The DHCP task counts until half the lease time has expired.
687 * When this period is up, it sends a DHCP REQUEST packet to the
688 * server again to renew the lease.
689 * If the lease is renewed, the task starts counting again.
690 * If the lease is not renewed, the task retries until it is.
691 *
692 * The task will not rebind if the lease is not renewed.
693 */
694static void
695dhcp_task (rtems_task_argument _sdl)
696{
697  unsigned long       count;
698  struct dhcp_packet  call;
699  struct sockaddr_dl  *sdl;
700  rtems_event_set     event_out;
701  unsigned int        timeout = 0;
702  int                 error;
703  struct proc *procp = NULL;
704  rtems_status_code   ev_st;
705
706  sdl = (struct sockaddr_dl *) _sdl;
707
708  count = dhcp_elapsed_time;
709
710  while (true)
711  {
712    /*
713     * Sleep until the next poll
714     */
715    timeout = RTEMS_MILLISECONDS_TO_TICKS (1000);
716    ev_st = rtems_event_receive (RTEMS_EVENT_0,
717                                 RTEMS_WAIT | RTEMS_EVENT_ANY,
718                                 timeout, &event_out);
719
720    /*
721     * Check if not a poll timeout. So when ANY event received, exit task.
722     * Actually, only event RTEMS_EVENT_0 sent from rtem_dhcp_failsafe.c
723     * if "failsafe" dhcp enabled when interface down.  Otherwise, no
724     * event should occur, just timeout.
725     */
726    if(ev_st != RTEMS_TIMEOUT)
727        break;
728
729    count++;
730
731    if (count >= (dhcp_lease_time / 2))
732    {
733      rtems_bsdnet_semaphore_obtain ();
734
735      dhcp_request_req (&call, &dhcp_req, sdl, true);
736
737      /*
738       * Send the Request.
739       */
740      error = bootpc_call ((struct bootp_packet *)&call, (struct bootp_packet *)&dhcp_req, procp);
741      if (error) {
742        rtems_bsdnet_semaphore_release ();
743        printf ("DHCP call failed -- error %d", error);
744        continue;
745      }
746
747      /*
748       * Check for DHCP ACK/NACK
749       */
750      if (memcmp (&dhcp_req.vend[0],
751                  dhcp_magic_cookie,
752                  sizeof (dhcp_magic_cookie)) != 0)
753      {
754        rtems_bsdnet_semaphore_release ();
755        printf ("DHCP server did not send Magic Cookie.\n");
756        continue;
757      }
758
759      /*
760       * We have an ack. Clear the DNS entries that have been assigned by a previous
761       * DHCP request.
762       */
763      clean_dns_entries ();
764
765      /*
766       * Process this requests options.
767       */
768      process_options (&dhcp_req.vend[4], sizeof (dhcp_req.vend) - 4);
769
770      if (dhcp_message_type != DHCP_ACK)
771      {
772        rtems_bsdnet_semaphore_release ();
773        printf ("DHCP server did not accept the DHCP request");
774        continue;
775      }
776
777      rtems_bsdnet_semaphore_release ();
778
779      count = 0;
780    }
781  }
782
783
784  dhcp_task_id = 0;
785  printf ("dhcpc: exiting lease renewal task.\n");
786  rtems_task_delete( RTEMS_SELF);
787
788}
789
790/*
791 * Start the DHCP task.
792 */
793static rtems_status_code
794dhcp_start_task (struct sockaddr_dl *sdl,
795                 struct dhcp_packet *reply,
796                 int priority)
797{
798  rtems_status_code sc;
799
800  memcpy (&dhcp_req, reply, sizeof (struct dhcp_packet));
801
802  sc = rtems_task_create (rtems_build_name ('d','h','c','p'),
803                          priority,
804                          2048,
805                          RTEMS_PREEMPT |
806                          RTEMS_NO_TIMESLICE |
807                          RTEMS_NO_ASR |
808                          RTEMS_INTERRUPT_LEVEL (0),
809                          RTEMS_LOCAL,
810                          &dhcp_task_id);
811
812  if (sc != RTEMS_SUCCESSFUL)
813    return sc;
814
815  sc = rtems_task_start (dhcp_task_id,
816                         dhcp_task,
817                         (rtems_task_argument) sdl);
818
819  if (sc != RTEMS_SUCCESSFUL)
820    return sc;
821
822  return RTEMS_SUCCESSFUL;
823}
824
825/*
826 * Check if the chosen interface already has an IP.
827 */
828static int
829dhcp_interface_has_ip (struct ifreq *ireq, struct socket *so, struct proc *procp)
830{
831  struct sockaddr_in* sin;
832  int error;
833
834  /*
835   * Check if the interface is already up.
836   */
837  error = ifioctl(so, SIOCGIFFLAGS, (caddr_t)ireq, procp);
838  if (error)
839    return 0;
840
841  if ((ireq->ifr_flags & IFF_UP) == 0)
842    return 0;
843
844  sin = (struct sockaddr_in *)&ireq->ifr_addr;
845  bzero ((caddr_t)sin, sizeof (struct sockaddr_in));
846  sin->sin_len = sizeof (struct sockaddr_in);
847  sin->sin_family = AF_INET;
848  error = ifioctl (so, SIOCGIFADDR, (caddr_t)ireq, procp);
849  if (error)
850    return 0;
851
852  if (sin->sin_addr.s_addr != 0)
853    return 1;
854
855  return 0;
856}
857
858/*
859 *  DCHP Client Routine
860 *    - The first DHCP offer is always accepted
861 *    - No DHCP DECLINE message is sent if ARPing fails
862 *
863 *    return value:
864 *    0: ok
865 *    < 0: failed to startup or configure interface
866 */
867static int
868dhcp_init (int update_files)
869{
870  struct dhcp_packet   call;
871  struct dhcp_packet   reply;
872  static unsigned long xid = ~0xFF;
873  struct ifreq         ireq;
874  struct ifnet         *ifp;
875  struct socket        *so;
876  int                  error;
877  struct sockaddr_in   myaddr;
878  struct ifaddr        *ifa;
879  struct sockaddr_dl   *sdl = NULL;
880  struct proc          *procp = NULL;
881
882  clean_dns_entries();
883 
884  /*
885   * If we are to update the files create the root
886   * file structure.
887   */
888  if (update_files)
889    if (rtems_create_root_fs () < 0) {
890      printf("Error creating the root filesystem.\nFile not created.\n");
891      update_files = 0;
892    }
893
894  /*
895   * Find a network interface.
896   */
897  for (ifp = ifnet; ifp != 0; ifp = ifp->if_next)
898    if ((ifp->if_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) == 0)
899      break;
900  if (ifp == NULL){
901    printf ("dhcpc_init: no suitable interface\n");
902    return -1;
903  }
904
905  memset (&ireq, 0, sizeof (ireq));
906  sprintf (ireq.ifr_name, "%s%d", ifp->if_name, ifp->if_unit);
907
908  if ((error = socreate (AF_INET, &so, SOCK_DGRAM, 0, procp)) != 0) {
909    printf ("dhcpc_init: socreate, error: %s\n", strerror(error));
910    return -1;
911  }
912
913  if (!dhcp_interface_has_ip (&ireq, so, procp))
914    bootpc_fakeup_interface (&ireq, so, procp);
915
916  /*
917   * Get HW address
918   */
919  for (ifa = ifp->if_addrlist; ifa; ifa = ifa->ifa_next)
920    if (ifa->ifa_addr->sa_family == AF_LINK &&
921        (sdl = ((struct sockaddr_dl *) ifa->ifa_addr)) &&
922        sdl->sdl_type == IFT_ETHER)
923      break;
924
925  if (!sdl){
926    printf ("dhcpc_init: Unable to find HW address\n");
927    soclose (so);
928    return -1;
929  }
930  if (sdl->sdl_alen != EALEN) {
931    printf ("dhcpc_init: HW address len is %d, expected value is %d\n",
932           sdl->sdl_alen, EALEN);
933    soclose (so);
934    return -1;
935  }
936
937  /*
938   * Build the DHCP Discover
939   */
940  dhcp_discover_req (&call, sdl, &xid);
941
942  /*
943   * Send the Discover.
944   */
945  error = bootpc_call ((struct bootp_packet *)&call, (struct bootp_packet *)&reply, procp);
946  if (error) {
947    printf ("BOOTP call failed -- %s\n", strerror(error));
948    soclose (so);
949    return -1;
950  }
951
952  /*
953   * Check for DHCP OFFER
954   */
955  if (memcmp (&reply.vend[0], dhcp_magic_cookie, sizeof (dhcp_magic_cookie)) != 0) {
956    printf ("DHCP server did not send Magic Cookie.\n");
957    soclose (so);
958    return -1;
959  }
960
961  process_options (&reply.vend[4], sizeof (reply.vend) - 4);
962
963  if (dhcp_message_type != DHCP_OFFER) {
964    printf ("DHCP server did not send a DHCP Offer.\n");
965    soclose (so);
966    return -1;
967  }
968
969  /*
970   * Send a DHCP REQUEST
971   */
972  dhcp_request_req (&call, &reply, sdl, true);
973
974  error = bootpc_call ((struct bootp_packet *)&call, (struct bootp_packet *)&reply, procp);
975  if (error) {
976    printf ("BOOTP call failed -- %s\n", strerror(error));
977    soclose (so);
978    return -1;
979  }
980
981  /*
982   * Check for DHCP ACK/NACK
983   */
984  if (memcmp (&reply.vend[0], dhcp_magic_cookie, sizeof (dhcp_magic_cookie)) != 0) {
985    printf ("DHCP server did not send Magic Cookie.\n");
986    soclose (so);
987    return -1;
988  }
989
990  process_options (&reply.vend[4], sizeof (reply.vend) - 4);
991
992  if (dhcp_message_type != DHCP_ACK) {
993    printf ("DHCP server did not accept the DHCP request\n");
994    soclose (so);
995    return -1;
996  }
997
998  /*
999   * Initialize network address structures
1000   */
1001  memset (&myaddr, 0, sizeof (myaddr));
1002  memset (&dhcp_netmask, 0, sizeof (dhcp_netmask));
1003  memset (&dhcp_gw, 0, sizeof (dhcp_gw));
1004  myaddr.sin_len = sizeof (myaddr);
1005  myaddr.sin_family = AF_INET;
1006  dhcp_netmask.sin_len = sizeof (dhcp_netmask);
1007  dhcp_netmask.sin_family = AF_INET;
1008  dhcp_gw.sin_len = sizeof (dhcp_gw);
1009  dhcp_gw.sin_family = AF_INET;
1010
1011  /*
1012   * Set our address
1013   */
1014  myaddr.sin_addr = reply.yiaddr;
1015
1016  /*
1017   * Process BOOTP/DHCP options
1018   */
1019  if (memcmp (&reply.vend[0], dhcp_magic_cookie, sizeof (dhcp_magic_cookie)) == 0)
1020    process_options (&reply.vend[4], sizeof (reply.vend) - 4);
1021
1022  if (dhcp_option_overload & 1)
1023    process_options ((unsigned char*) reply.file, sizeof reply.file);
1024  else
1025    if (reply.file[0])
1026      rtems_bsdnet_bootp_boot_file_name = strdup (reply.file);
1027
1028  if (dhcp_option_overload & 2)
1029    process_options ((unsigned char*) reply.sname, sizeof reply.sname);
1030  else
1031    if (reply.sname[0])
1032      rtems_bsdnet_bootp_server_name = strdup (reply.sname);
1033
1034  /*
1035   * Use defaults if values were not supplied by BOOTP/DHCP options
1036   */
1037  if (!dhcp_gotnetmask)
1038  {
1039    if (IN_CLASSA (ntohl (myaddr.sin_addr.s_addr)))
1040      dhcp_netmask.sin_addr.s_addr = htonl (IN_CLASSA_NET);
1041    else if (IN_CLASSB (ntohl (myaddr.sin_addr.s_addr)))
1042      dhcp_netmask.sin_addr.s_addr = htonl (IN_CLASSB_NET);
1043    else
1044      dhcp_netmask.sin_addr.s_addr = htonl (IN_CLASSC_NET);
1045  }
1046
1047  if (!dhcp_gotserver)
1048    rtems_bsdnet_bootp_server_address = reply.siaddr;
1049
1050  if (!dhcp_gotgw)
1051    dhcp_gw.sin_addr = reply.giaddr;
1052
1053  if (!dhcp_gotlogserver)
1054    rtems_bsdnet_log_host_address = rtems_bsdnet_bootp_server_address;
1055
1056  printsetup (ifp->if_name, myaddr.sin_addr, dhcp_netmask.sin_addr,
1057              rtems_bsdnet_bootp_server_address, dhcp_gw.sin_addr);
1058
1059  /*
1060   * Update the files if we are asked too.
1061   */
1062  if (update_files) {
1063    char *dn = rtems_bsdnet_domain_name;
1064    char *hn = dhcp_hostname;
1065    if (!dn)
1066      dn = "mydomain";
1067    if (!hn)
1068    {
1069      hn = "me";
1070      sethostname (hn, strlen (hn));
1071    }
1072    rtems_rootfs_append_host_rec(myaddr.sin_addr.s_addr, hn, dn);
1073
1074    /*
1075     * Should the given domainname be used here ?
1076     */
1077    if (dhcp_gotserver) {
1078      if (rtems_bsdnet_bootp_server_name)
1079        hn = rtems_bsdnet_bootp_server_name;
1080      else
1081        hn = "bootps";
1082      rtems_rootfs_append_host_rec(rtems_bsdnet_bootp_server_address.s_addr,
1083                                   hn, dn);
1084    }
1085
1086    if (dhcp_gotlogserver) {
1087      rtems_rootfs_append_host_rec(rtems_bsdnet_log_host_address.s_addr,
1088                                   "logs", dn);
1089    }
1090
1091    /*
1092     * Setup the DNS configuration file /etc/resolv.conf.
1093     */
1094    if (rtems_bsdnet_nameserver_count) {
1095      int        i;
1096      char       buf[64];
1097      const char *bufl[1];
1098
1099      bufl[0] = buf;
1100
1101#define MKFILE_MODE (S_IRUSR | S_IWUSR | S_IWGRP | S_IRGRP | S_IROTH)
1102
1103      if (rtems_bsdnet_domain_name &&
1104          (strlen(rtems_bsdnet_domain_name) < (sizeof(buf) - 1))) {
1105        strcpy(buf, "search ");
1106        strcat(buf, rtems_bsdnet_domain_name);
1107        strcat(buf, "\n");
1108        rtems_rootfs_file_append ("/etc/resolv.conf", MKFILE_MODE, 1, bufl);
1109      }
1110
1111      for (i = 0; i < rtems_bsdnet_nameserver_count; i++) {
1112        strcpy(buf, "nameserver ");
1113        strcat(buf, inet_ntoa(rtems_bsdnet_ntpserver[i]));
1114        strcat(buf, "\n");
1115        if (rtems_rootfs_file_append ("/etc/resolv.conf", MKFILE_MODE, 1, bufl))
1116          break;
1117      }
1118    }
1119  }
1120
1121  /*
1122   * Configure the interface with the new settings
1123   */
1124  error = bootpc_adjust_interface (&ireq, so,
1125                                   &myaddr, &dhcp_netmask, &dhcp_gw, procp);
1126
1127  /*
1128   * Start the DHCP task if the lease isn't infinite.
1129   */
1130  if (dhcp_lease_time != 0xffffffff)
1131    dhcp_start_task (sdl, &reply, 150);
1132
1133  soclose (so);
1134
1135  return 0;
1136}
1137
1138/*
1139 *
1140 *  RTEMS Entry point to DHCP client
1141 *
1142 */
1143void rtems_bsdnet_do_dhcp (void)
1144{
1145  bool update = true;
1146  rtems_bsdnet_semaphore_obtain ();
1147  while( dhcp_init (update) < 0 ) {
1148    update = false;
1149    rtems_bsdnet_semaphore_release();
1150    rtems_task_wake_after(RTEMS_MILLISECONDS_TO_TICKS(1000));
1151    rtems_bsdnet_semaphore_obtain ();
1152  }
1153  rtems_bsdnet_semaphore_release ();
1154}
1155
1156int rtems_bsdnet_do_dhcp_timeout( void )
1157{
1158  int return_value;
1159
1160  rtems_bsdnet_semaphore_obtain ();
1161  return_value = dhcp_init (false);
1162  rtems_bsdnet_semaphore_release ();
1163
1164  return return_value;
1165}
1166
1167void rtems_bsdnet_dhcp_down (void)
1168{
1169   if(dhcp_task_id != 0) {
1170     rtems_event_send (dhcp_task_id, RTEMS_EVENT_0);
1171   }
1172}
1173
1174void
1175rtems_bsdnet_do_dhcp_refresh_only (unsigned long xid,
1176                                   unsigned long lease_time,
1177                                   unsigned long elapsed_time,
1178                                   unsigned long ip_address,
1179                                   unsigned long srv_address,
1180                                   const char*   hostname)
1181{
1182  struct dhcp_packet reply;
1183  struct ifnet       *ifp = NULL;
1184  struct ifaddr      *ifa = NULL;
1185  struct sockaddr_dl *sdl = NULL;
1186  struct sockaddr_in *sin = NULL;
1187  int                match = 0;
1188  struct ifnet       *mtif = NULL;
1189
1190  /*
1191   * If an infinite lease has been granted, no task is needed.
1192   */
1193  if (lease_time == 0xffffffff)
1194    return;
1195
1196  /*
1197   * Find a network interface.
1198   */
1199  for (ifp = ifnet; (ifp != NULL) && !match; ifp = ifp->if_next)
1200    if ((ifp->if_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) == 0)
1201      for (ifa = ifp->if_addrlist; ifa; ifa = ifa->ifa_next)
1202        if (ifa->ifa_addr->sa_family == AF_INET)
1203        {
1204          sin = (struct sockaddr_in *) ifa->ifa_addr;
1205          if (sin->sin_addr.s_addr == htonl (ip_address))
1206          {
1207            mtif = ifp;
1208            match = 1;
1209            break;
1210          }
1211        }
1212
1213  if (!match) {
1214    printf ("dhcpc: no matching interface\n");
1215    return;
1216  }
1217
1218  for (ifa = mtif->if_addrlist; ifa != NULL; ifa = ifa->ifa_next)
1219    if (ifa->ifa_addr->sa_family == AF_LINK &&
1220        (sdl = ((struct sockaddr_dl *) ifa->ifa_addr)) &&
1221        sdl->sdl_type == IFT_ETHER)
1222      break;
1223
1224  if (!match) {
1225    printf ("dhcpc: no matching interface address\n");
1226    return;
1227  }
1228
1229  /*
1230   * Set up given values in a simulated DHCP reply.
1231   */
1232  memset (&reply, 0x00, sizeof (reply));
1233  reply.xid = htonl (xid);
1234  reply.yiaddr.s_addr = htonl (ip_address);
1235  reply.siaddr.s_addr = htonl (srv_address);
1236  if (reply.siaddr.s_addr != rtems_bsdnet_bootp_server_address.s_addr)
1237  {
1238    memcpy (&rtems_bsdnet_bootp_server_address, &reply.siaddr,
1239            sizeof (reply.siaddr));
1240  }
1241
1242  dhcp_lease_time = lease_time;
1243  dhcp_elapsed_time = elapsed_time;
1244
1245  if (hostname)
1246  {
1247    sethostname ((char *) hostname, strlen (hostname));
1248    dhcp_hostname = bootp_strdup_realloc (dhcp_hostname, hostname);
1249  }
1250
1251  dhcp_start_task (sdl, &reply, 150);
1252}
Note: See TracBrowser for help on using the repository browser.