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

4.10
Last change on this file since a078d6f0 was a078d6f0, checked in by Sebastien Bourdeauducq <sebastien@…>, on 05/22/12 at 10:06:20

network/bootp: PR2031: Add and use header file

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