a56ed4cf8c0dea950a7a431f294d08114dec5233
[oweals/u-boot.git] / net / bootp.c
1 /*
2  *      Based on LiMon - BOOTP.
3  *
4  *      Copyright 1994, 1995, 2000 Neil Russell.
5  *      (See License)
6  *      Copyright 2000 Roland Borde
7  *      Copyright 2000 Paolo Scaffardi
8  *      Copyright 2000-2004 Wolfgang Denk, wd@denx.de
9  */
10
11 #include <common.h>
12 #include <command.h>
13 #include <net.h>
14 #include "bootp.h"
15 #include "tftp.h"
16 #include "nfs.h"
17 #ifdef CONFIG_STATUS_LED
18 #include <status_led.h>
19 #endif
20 #ifdef CONFIG_BOOTP_RANDOM_DELAY
21 #include "net_rand.h"
22 #endif
23
24 #define BOOTP_VENDOR_MAGIC      0x63825363      /* RFC1048 Magic Cookie */
25
26 /*
27  * The timeout for the initial BOOTP/DHCP request used to be described by a
28  * counter of fixed-length timeout periods. TIMEOUT_COUNT represents
29  * that counter
30  *
31  * Now that the timeout periods are variable (exponential backoff and retry)
32  * we convert the timeout count to the absolute time it would have take to
33  * execute that many retries, and keep sending retry packets until that time
34  * is reached.
35  */
36 #ifndef CONFIG_NET_RETRY_COUNT
37 # define TIMEOUT_COUNT  5               /* # of timeouts before giving up */
38 #else
39 # define TIMEOUT_COUNT  (CONFIG_NET_RETRY_COUNT)
40 #endif
41 #define TIMEOUT_MS      ((3 + (TIMEOUT_COUNT * 5)) * 1000)
42
43 #define PORT_BOOTPS     67              /* BOOTP server UDP port */
44 #define PORT_BOOTPC     68              /* BOOTP client UDP port */
45
46 #ifndef CONFIG_DHCP_MIN_EXT_LEN         /* minimal length of extension list */
47 #define CONFIG_DHCP_MIN_EXT_LEN 64
48 #endif
49
50 #ifndef CONFIG_BOOTP_ID_CACHE_SIZE
51 #define CONFIG_BOOTP_ID_CACHE_SIZE 4
52 #endif
53
54 ulong           bootp_ids[CONFIG_BOOTP_ID_CACHE_SIZE];
55 unsigned int    bootp_num_ids;
56 int             BootpTry;
57 ulong           bootp_start;
58 ulong           bootp_timeout;
59
60 #if defined(CONFIG_CMD_DHCP)
61 static dhcp_state_t dhcp_state = INIT;
62 static unsigned long dhcp_leasetime;
63 static struct in_addr dhcp_server_ip;
64 static void dhcp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
65                         unsigned src, unsigned len);
66
67 /* For Debug */
68 #if 0
69 static char *dhcpmsg2str(int type)
70 {
71         switch (type) {
72         case 1:  return "DHCPDISCOVER"; break;
73         case 2:  return "DHCPOFFER";    break;
74         case 3:  return "DHCPREQUEST";  break;
75         case 4:  return "DHCPDECLINE";  break;
76         case 5:  return "DHCPACK";      break;
77         case 6:  return "DHCPNACK";     break;
78         case 7:  return "DHCPRELEASE";  break;
79         default: return "UNKNOWN/INVALID MSG TYPE"; break;
80         }
81 }
82 #endif
83 #endif
84
85 static void bootp_add_id(ulong id)
86 {
87         if (bootp_num_ids >= ARRAY_SIZE(bootp_ids)) {
88                 size_t size = sizeof(bootp_ids) - sizeof(id);
89
90                 memmove(bootp_ids, &bootp_ids[1], size);
91                 bootp_ids[bootp_num_ids - 1] = id;
92         } else {
93                 bootp_ids[bootp_num_ids] = id;
94                 bootp_num_ids++;
95         }
96 }
97
98 static bool bootp_match_id(ulong id)
99 {
100         unsigned int i;
101
102         for (i = 0; i < bootp_num_ids; i++)
103                 if (bootp_ids[i] == id)
104                         return true;
105
106         return false;
107 }
108
109 static int BootpCheckPkt(uchar *pkt, unsigned dest, unsigned src, unsigned len)
110 {
111         struct Bootp_t *bp = (struct Bootp_t *) pkt;
112         int retval = 0;
113
114         if (dest != PORT_BOOTPC || src != PORT_BOOTPS)
115                 retval = -1;
116         else if (len < sizeof(struct Bootp_t) - OPT_FIELD_SIZE)
117                 retval = -2;
118         else if (bp->bp_op != OP_BOOTREQUEST &&
119                         bp->bp_op != OP_BOOTREPLY &&
120                         bp->bp_op != DHCP_OFFER &&
121                         bp->bp_op != DHCP_ACK &&
122                         bp->bp_op != DHCP_NAK)
123                 retval = -3;
124         else if (bp->bp_htype != HWT_ETHER)
125                 retval = -4;
126         else if (bp->bp_hlen != HWL_ETHER)
127                 retval = -5;
128         else if (!bootp_match_id(NetReadLong((ulong *)&bp->bp_id)))
129                 retval = -6;
130
131         debug("Filtering pkt = %d\n", retval);
132
133         return retval;
134 }
135
136 /*
137  * Copy parameters of interest from BOOTP_REPLY/DHCP_OFFER packet
138  */
139 static void BootpCopyNetParams(struct Bootp_t *bp)
140 {
141 #if !defined(CONFIG_BOOTP_SERVERIP)
142         struct in_addr tmp_ip;
143
144         net_copy_ip(&tmp_ip, &bp->bp_siaddr);
145         if (tmp_ip.s_addr != 0)
146                 net_copy_ip(&net_server_ip, &bp->bp_siaddr);
147         memcpy(NetServerEther, ((struct ethernet_hdr *)NetRxPacket)->et_src, 6);
148         if (strlen(bp->bp_file) > 0)
149                 copy_filename(BootFile, bp->bp_file, sizeof(BootFile));
150
151         debug("Bootfile: %s\n", BootFile);
152
153         /* Propagate to environment:
154          * don't delete exising entry when BOOTP / DHCP reply does
155          * not contain a new value
156          */
157         if (*BootFile)
158                 setenv("bootfile", BootFile);
159 #endif
160         net_copy_ip(&net_ip, &bp->bp_yiaddr);
161 }
162
163 static int truncate_sz(const char *name, int maxlen, int curlen)
164 {
165         if (curlen >= maxlen) {
166                 printf("*** WARNING: %s is too long (%d - max: %d)"
167                         " - truncated\n", name, curlen, maxlen);
168                 curlen = maxlen - 1;
169         }
170         return curlen;
171 }
172
173 #if !defined(CONFIG_CMD_DHCP)
174
175 static void BootpVendorFieldProcess(u8 *ext)
176 {
177         int size = *(ext + 1);
178
179         debug("[BOOTP] Processing extension %d... (%d bytes)\n", *ext,
180                 *(ext + 1));
181
182         NetBootFileSize = 0;
183
184         switch (*ext) {
185                 /* Fixed length fields */
186         case 1:                 /* Subnet mask */
187                 if (net_netmask.s_addr == 0)
188                         net_copy_ip(&net_netmask, (struct in_addr *)(ext + 2));
189                 break;
190         case 2:                 /* Time offset - Not yet supported */
191                 break;
192                 /* Variable length fields */
193         case 3:                 /* Gateways list */
194                 if (net_gateway.s_addr == 0)
195                         net_copy_ip(&net_gateway, (struct in_addr *)(ext + 2));
196                 break;
197         case 4:                 /* Time server - Not yet supported */
198                 break;
199         case 5:                 /* IEN-116 name server - Not yet supported */
200                 break;
201         case 6:
202                 if (net_dns_server.s_addr == 0)
203                         net_copy_ip(&net_dns_server,
204                                     (struct in_addr *)(ext + 2));
205 #if defined(CONFIG_BOOTP_DNS2)
206                 if ((net_dns_server2.s_addr == 0) && (size > 4))
207                         net_copy_ip(&net_dns_server2,
208                                     (struct in_addr *)(ext + 2 + 4));
209 #endif
210                 break;
211         case 7:                 /* Log server - Not yet supported */
212                 break;
213         case 8:                 /* Cookie/Quote server - Not yet supported */
214                 break;
215         case 9:                 /* LPR server - Not yet supported */
216                 break;
217         case 10:                /* Impress server - Not yet supported */
218                 break;
219         case 11:                /* RPL server - Not yet supported */
220                 break;
221         case 12:                /* Host name */
222                 if (NetOurHostName[0] == 0) {
223                         size = truncate_sz("Host Name",
224                                 sizeof(NetOurHostName), size);
225                         memcpy(&NetOurHostName, ext + 2, size);
226                         NetOurHostName[size] = 0;
227                 }
228                 break;
229         case 13:                /* Boot file size */
230                 if (size == 2)
231                         NetBootFileSize = ntohs(*(ushort *) (ext + 2));
232                 else if (size == 4)
233                         NetBootFileSize = ntohl(*(ulong *) (ext + 2));
234                 break;
235         case 14:                /* Merit dump file - Not yet supported */
236                 break;
237         case 15:                /* Domain name - Not yet supported */
238                 break;
239         case 16:                /* Swap server - Not yet supported */
240                 break;
241         case 17:                /* Root path */
242                 if (NetOurRootPath[0] == 0) {
243                         size = truncate_sz("Root Path",
244                                 sizeof(NetOurRootPath), size);
245                         memcpy(&NetOurRootPath, ext + 2, size);
246                         NetOurRootPath[size] = 0;
247                 }
248                 break;
249         case 18:                /* Extension path - Not yet supported */
250                 /*
251                  * This can be used to send the information of the
252                  * vendor area in another file that the client can
253                  * access via TFTP.
254                  */
255                 break;
256                 /* IP host layer fields */
257         case 40:                /* NIS Domain name */
258                 if (NetOurNISDomain[0] == 0) {
259                         size = truncate_sz("NIS Domain Name",
260                                 sizeof(NetOurNISDomain), size);
261                         memcpy(&NetOurNISDomain, ext + 2, size);
262                         NetOurNISDomain[size] = 0;
263                 }
264                 break;
265 #if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_NTPSERVER)
266         case 42:        /* NTP server IP */
267                 net_copy_ip(&net_ntp_server, (struct in_addr *)(ext + 2));
268                 break;
269 #endif
270                 /* Application layer fields */
271         case 43:                /* Vendor specific info - Not yet supported */
272                 /*
273                  * Binary information to exchange specific
274                  * product information.
275                  */
276                 break;
277                 /* Reserved (custom) fields (128..254) */
278         }
279 }
280
281 static void BootpVendorProcess(u8 *ext, int size)
282 {
283         u8 *end = ext + size;
284
285         debug("[BOOTP] Checking extension (%d bytes)...\n", size);
286
287         while ((ext < end) && (*ext != 0xff)) {
288                 if (*ext == 0) {
289                         ext++;
290                 } else {
291                         u8 *opt = ext;
292
293                         ext += ext[1] + 2;
294                         if (ext <= end)
295                                 BootpVendorFieldProcess(opt);
296                 }
297         }
298
299         debug("[BOOTP] Received fields:\n");
300         if (net_netmask.s_addr)
301                 debug("net_netmask : %pI4\n", &net_netmask);
302
303         if (net_gateway.s_addr)
304                 debug("net_gateway      : %pI4", &net_gateway);
305
306         if (NetBootFileSize)
307                 debug("NetBootFileSize : %d\n", NetBootFileSize);
308
309         if (NetOurHostName[0])
310                 debug("NetOurHostName  : %s\n", NetOurHostName);
311
312         if (NetOurRootPath[0])
313                 debug("NetOurRootPath  : %s\n", NetOurRootPath);
314
315         if (NetOurNISDomain[0])
316                 debug("NetOurNISDomain : %s\n", NetOurNISDomain);
317
318         if (NetBootFileSize)
319                 debug("NetBootFileSize: %d\n", NetBootFileSize);
320
321 #if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_NTPSERVER)
322         if (net_ntp_server)
323                 debug("net_ntp_server : %pI4\n", &net_ntp_server);
324 #endif
325 }
326
327 /*
328  *      Handle a BOOTP received packet.
329  */
330 static void bootp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
331                           unsigned src, unsigned len)
332 {
333         struct Bootp_t *bp;
334
335         debug("got BOOTP packet (src=%d, dst=%d, len=%d want_len=%zu)\n",
336                 src, dest, len, sizeof(struct Bootp_t));
337
338         bp = (struct Bootp_t *)pkt;
339
340         /* Filter out pkts we don't want */
341         if (BootpCheckPkt(pkt, dest, src, len))
342                 return;
343
344         /*
345          *      Got a good BOOTP reply.  Copy the data into our variables.
346          */
347 #ifdef CONFIG_STATUS_LED
348         status_led_set(STATUS_LED_BOOT, STATUS_LED_OFF);
349 #endif
350
351         BootpCopyNetParams(bp);         /* Store net parameters from reply */
352
353         /* Retrieve extended information (we must parse the vendor area) */
354         if (NetReadLong((ulong *)&bp->bp_vend[0]) == htonl(BOOTP_VENDOR_MAGIC))
355                 BootpVendorProcess((uchar *)&bp->bp_vend[4], len);
356
357         NetSetTimeout(0, (thand_f *)0);
358         bootstage_mark_name(BOOTSTAGE_ID_BOOTP_STOP, "bootp_stop");
359
360         debug("Got good BOOTP\n");
361
362         net_auto_load();
363 }
364 #endif
365
366 /*
367  *      Timeout on BOOTP/DHCP request.
368  */
369 static void
370 BootpTimeout(void)
371 {
372         ulong time_taken = get_timer(bootp_start);
373
374         if (time_taken >= TIMEOUT_MS) {
375 #ifdef CONFIG_BOOTP_MAY_FAIL
376                 puts("\nRetry time exceeded\n");
377                 net_set_state(NETLOOP_FAIL);
378 #else
379                 puts("\nRetry time exceeded; starting again\n");
380                 NetStartAgain();
381 #endif
382         } else {
383                 bootp_timeout *= 2;
384                 if (bootp_timeout > 2000)
385                         bootp_timeout = 2000;
386                 NetSetTimeout(bootp_timeout, BootpTimeout);
387                 BootpRequest();
388         }
389 }
390
391 #define put_vci(e, str)                                         \
392         do {                                                    \
393                 size_t vci_strlen = strlen(str);                \
394                 *e++ = 60;      /* Vendor Class Identifier */   \
395                 *e++ = vci_strlen;                              \
396                 memcpy(e, str, vci_strlen);                     \
397                 e += vci_strlen;                                \
398         } while (0)
399
400 /*
401  *      Initialize BOOTP extension fields in the request.
402  */
403 #if defined(CONFIG_CMD_DHCP)
404 static int dhcp_extended(u8 *e, int message_type, struct in_addr server_ip,
405                         struct in_addr requested_ip)
406 {
407         u8 *start = e;
408         u8 *cnt;
409 #if defined(CONFIG_BOOTP_PXE)
410         char *uuid;
411         u16 clientarch;
412 #endif
413
414 #if defined(CONFIG_BOOTP_VENDOREX)
415         u8 *x;
416 #endif
417 #if defined(CONFIG_BOOTP_SEND_HOSTNAME)
418         char *hostname;
419 #endif
420
421         *e++ = 99;              /* RFC1048 Magic Cookie */
422         *e++ = 130;
423         *e++ = 83;
424         *e++ = 99;
425
426         *e++ = 53;              /* DHCP Message Type */
427         *e++ = 1;
428         *e++ = message_type;
429
430         *e++ = 57;              /* Maximum DHCP Message Size */
431         *e++ = 2;
432         *e++ = (576 - 312 + OPT_FIELD_SIZE) >> 8;
433         *e++ = (576 - 312 + OPT_FIELD_SIZE) & 0xff;
434
435         if (server_ip.s_addr) {
436                 int tmp = ntohl(server_ip.s_addr);
437
438                 *e++ = 54;      /* ServerID */
439                 *e++ = 4;
440                 *e++ = tmp >> 24;
441                 *e++ = tmp >> 16;
442                 *e++ = tmp >> 8;
443                 *e++ = tmp & 0xff;
444         }
445
446         if (requested_ip.s_addr) {
447                 int tmp = ntohl(requested_ip.s_addr);
448
449                 *e++ = 50;      /* Requested IP */
450                 *e++ = 4;
451                 *e++ = tmp >> 24;
452                 *e++ = tmp >> 16;
453                 *e++ = tmp >> 8;
454                 *e++ = tmp & 0xff;
455         }
456 #if defined(CONFIG_BOOTP_SEND_HOSTNAME)
457         hostname = getenv("hostname");
458         if (hostname) {
459                 int hostnamelen = strlen(hostname);
460
461                 *e++ = 12;      /* Hostname */
462                 *e++ = hostnamelen;
463                 memcpy(e, hostname, hostnamelen);
464                 e += hostnamelen;
465         }
466 #endif
467
468 #if defined(CONFIG_BOOTP_PXE)
469         clientarch = CONFIG_BOOTP_PXE_CLIENTARCH;
470         *e++ = 93;      /* Client System Architecture */
471         *e++ = 2;
472         *e++ = (clientarch >> 8) & 0xff;
473         *e++ = clientarch & 0xff;
474
475         *e++ = 94;      /* Client Network Interface Identifier */
476         *e++ = 3;
477         *e++ = 1;       /* type field for UNDI */
478         *e++ = 0;       /* major revision */
479         *e++ = 0;       /* minor revision */
480
481         uuid = getenv("pxeuuid");
482
483         if (uuid) {
484                 if (uuid_str_valid(uuid)) {
485                         *e++ = 97;      /* Client Machine Identifier */
486                         *e++ = 17;
487                         *e++ = 0;       /* type 0 - UUID */
488
489                         uuid_str_to_bin(uuid, e, UUID_STR_FORMAT_STD);
490                         e += 16;
491                 } else {
492                         printf("Invalid pxeuuid: %s\n", uuid);
493                 }
494         }
495 #endif
496
497 #ifdef CONFIG_BOOTP_VCI_STRING
498         put_vci(e, CONFIG_BOOTP_VCI_STRING);
499 #endif
500
501 #if defined(CONFIG_BOOTP_VENDOREX)
502         x = dhcp_vendorex_prep(e);
503         if (x)
504                 return x - start;
505 #endif
506
507         *e++ = 55;              /* Parameter Request List */
508          cnt = e++;             /* Pointer to count of requested items */
509         *cnt = 0;
510 #if defined(CONFIG_BOOTP_SUBNETMASK)
511         *e++  = 1;              /* Subnet Mask */
512         *cnt += 1;
513 #endif
514 #if defined(CONFIG_BOOTP_TIMEOFFSET)
515         *e++  = 2;
516         *cnt += 1;
517 #endif
518 #if defined(CONFIG_BOOTP_GATEWAY)
519         *e++  = 3;              /* Router Option */
520         *cnt += 1;
521 #endif
522 #if defined(CONFIG_BOOTP_DNS)
523         *e++  = 6;              /* DNS Server(s) */
524         *cnt += 1;
525 #endif
526 #if defined(CONFIG_BOOTP_HOSTNAME)
527         *e++  = 12;             /* Hostname */
528         *cnt += 1;
529 #endif
530 #if defined(CONFIG_BOOTP_BOOTFILESIZE)
531         *e++  = 13;             /* Boot File Size */
532         *cnt += 1;
533 #endif
534 #if defined(CONFIG_BOOTP_BOOTPATH)
535         *e++  = 17;             /* Boot path */
536         *cnt += 1;
537 #endif
538 #if defined(CONFIG_BOOTP_NISDOMAIN)
539         *e++  = 40;             /* NIS Domain name request */
540         *cnt += 1;
541 #endif
542 #if defined(CONFIG_BOOTP_NTPSERVER)
543         *e++  = 42;
544         *cnt += 1;
545 #endif
546         /* no options, so back up to avoid sending an empty request list */
547         if (*cnt == 0)
548                 e -= 2;
549
550         *e++  = 255;            /* End of the list */
551
552         /* Pad to minimal length */
553 #ifdef  CONFIG_DHCP_MIN_EXT_LEN
554         while ((e - start) < CONFIG_DHCP_MIN_EXT_LEN)
555                 *e++ = 0;
556 #endif
557
558         return e - start;
559 }
560
561 #else
562 /*
563  * Warning: no field size check - change CONFIG_BOOTP_* at your own risk!
564  */
565 static int bootp_extended(u8 *e)
566 {
567         u8 *start = e;
568
569         *e++ = 99;              /* RFC1048 Magic Cookie */
570         *e++ = 130;
571         *e++ = 83;
572         *e++ = 99;
573
574 #if defined(CONFIG_CMD_DHCP)
575         *e++ = 53;              /* DHCP Message Type */
576         *e++ = 1;
577         *e++ = DHCP_DISCOVER;
578
579         *e++ = 57;              /* Maximum DHCP Message Size */
580         *e++ = 2;
581         *e++ = (576 - 312 + OPT_FIELD_SIZE) >> 16;
582         *e++ = (576 - 312 + OPT_FIELD_SIZE) & 0xff;
583 #endif
584
585 #if defined(CONFIG_BOOTP_VCI_STRING) || \
586         (defined(CONFIG_SPL_BUILD) && defined(CONFIG_SPL_NET_VCI_STRING))
587 #ifdef CONFIG_SPL_BUILD
588         put_vci(e, CONFIG_SPL_NET_VCI_STRING);
589 #else
590         put_vci(e, CONFIG_BOOTP_VCI_STRING);
591 #endif
592 #endif
593
594 #if defined(CONFIG_BOOTP_SUBNETMASK)
595         *e++ = 1;               /* Subnet mask request */
596         *e++ = 4;
597         e   += 4;
598 #endif
599
600 #if defined(CONFIG_BOOTP_GATEWAY)
601         *e++ = 3;               /* Default gateway request */
602         *e++ = 4;
603         e   += 4;
604 #endif
605
606 #if defined(CONFIG_BOOTP_DNS)
607         *e++ = 6;               /* Domain Name Server */
608         *e++ = 4;
609         e   += 4;
610 #endif
611
612 #if defined(CONFIG_BOOTP_HOSTNAME)
613         *e++ = 12;              /* Host name request */
614         *e++ = 32;
615         e   += 32;
616 #endif
617
618 #if defined(CONFIG_BOOTP_BOOTFILESIZE)
619         *e++ = 13;              /* Boot file size */
620         *e++ = 2;
621         e   += 2;
622 #endif
623
624 #if defined(CONFIG_BOOTP_BOOTPATH)
625         *e++ = 17;              /* Boot path */
626         *e++ = 32;
627         e   += 32;
628 #endif
629
630 #if defined(CONFIG_BOOTP_NISDOMAIN)
631         *e++ = 40;              /* NIS Domain name request */
632         *e++ = 32;
633         e   += 32;
634 #endif
635 #if defined(CONFIG_BOOTP_NTPSERVER)
636         *e++ = 42;
637         *e++ = 4;
638         e   += 4;
639 #endif
640
641         *e++ = 255;             /* End of the list */
642
643         return e - start;
644 }
645 #endif
646
647 void BootpReset(void)
648 {
649         bootp_num_ids = 0;
650         BootpTry = 0;
651         bootp_start = get_timer(0);
652         bootp_timeout = 250;
653 }
654
655 void
656 BootpRequest(void)
657 {
658         uchar *pkt, *iphdr;
659         struct Bootp_t *bp;
660         int extlen, pktlen, iplen;
661         int eth_hdr_size;
662 #ifdef CONFIG_BOOTP_RANDOM_DELAY
663         ulong rand_ms;
664 #endif
665         ulong BootpID;
666         struct in_addr zero_ip;
667         struct in_addr bcast_ip;
668
669         bootstage_mark_name(BOOTSTAGE_ID_BOOTP_START, "bootp_start");
670 #if defined(CONFIG_CMD_DHCP)
671         dhcp_state = INIT;
672 #endif
673
674 #ifdef CONFIG_BOOTP_RANDOM_DELAY                /* Random BOOTP delay */
675         if (BootpTry == 0)
676                 srand_mac();
677
678         if (BootpTry <= 2)      /* Start with max 1024 * 1ms */
679                 rand_ms = rand() >> (22 - BootpTry);
680         else            /* After 3rd BOOTP request max 8192 * 1ms */
681                 rand_ms = rand() >> 19;
682
683         printf("Random delay: %ld ms...\n", rand_ms);
684         mdelay(rand_ms);
685
686 #endif  /* CONFIG_BOOTP_RANDOM_DELAY */
687
688         printf("BOOTP broadcast %d\n", ++BootpTry);
689         pkt = NetTxPacket;
690         memset((void *)pkt, 0, PKTSIZE);
691
692         eth_hdr_size = NetSetEther(pkt, NetBcastAddr, PROT_IP);
693         pkt += eth_hdr_size;
694
695         /*
696          * Next line results in incorrect packet size being transmitted,
697          * resulting in errors in some DHCP servers, reporting missing bytes.
698          * Size must be set in packet header after extension length has been
699          * determined.
700          * C. Hallinan, DS4.COM, Inc.
701          */
702         /* net_set_udp_header(pkt, 0xFFFFFFFFL, PORT_BOOTPS, PORT_BOOTPC,
703                 sizeof (struct Bootp_t)); */
704         iphdr = pkt;    /* We need this later for net_set_udp_header() */
705         pkt += IP_UDP_HDR_SIZE;
706
707         bp = (struct Bootp_t *)pkt;
708         bp->bp_op = OP_BOOTREQUEST;
709         bp->bp_htype = HWT_ETHER;
710         bp->bp_hlen = HWL_ETHER;
711         bp->bp_hops = 0;
712         bp->bp_secs = htons(get_timer(0) / 1000);
713         zero_ip.s_addr = 0;
714         net_write_ip(&bp->bp_ciaddr, zero_ip);
715         net_write_ip(&bp->bp_yiaddr, zero_ip);
716         net_write_ip(&bp->bp_siaddr, zero_ip);
717         net_write_ip(&bp->bp_giaddr, zero_ip);
718         memcpy(bp->bp_chaddr, NetOurEther, 6);
719         copy_filename(bp->bp_file, BootFile, sizeof(bp->bp_file));
720
721         /* Request additional information from the BOOTP/DHCP server */
722 #if defined(CONFIG_CMD_DHCP)
723         extlen = dhcp_extended((u8 *)bp->bp_vend, DHCP_DISCOVER, zero_ip,
724                                zero_ip);
725 #else
726         extlen = bootp_extended((u8 *)bp->bp_vend);
727 #endif
728
729         /*
730          *      Bootp ID is the lower 4 bytes of our ethernet address
731          *      plus the current time in ms.
732          */
733         BootpID = ((ulong)NetOurEther[2] << 24)
734                 | ((ulong)NetOurEther[3] << 16)
735                 | ((ulong)NetOurEther[4] << 8)
736                 | (ulong)NetOurEther[5];
737         BootpID += get_timer(0);
738         BootpID = htonl(BootpID);
739         bootp_add_id(BootpID);
740         NetCopyLong(&bp->bp_id, &BootpID);
741
742         /*
743          * Calculate proper packet lengths taking into account the
744          * variable size of the options field
745          */
746         iplen = BOOTP_HDR_SIZE - OPT_FIELD_SIZE + extlen;
747         pktlen = eth_hdr_size + IP_UDP_HDR_SIZE + iplen;
748         bcast_ip.s_addr = 0xFFFFFFFFL;
749         net_set_udp_header(iphdr, bcast_ip, PORT_BOOTPS, PORT_BOOTPC, iplen);
750         NetSetTimeout(bootp_timeout, BootpTimeout);
751
752 #if defined(CONFIG_CMD_DHCP)
753         dhcp_state = SELECTING;
754         net_set_udp_handler(dhcp_handler);
755 #else
756         net_set_udp_handler(bootp_handler);
757 #endif
758         NetSendPacket(NetTxPacket, pktlen);
759 }
760
761 #if defined(CONFIG_CMD_DHCP)
762 static void DhcpOptionsProcess(uchar *popt, struct Bootp_t *bp)
763 {
764         uchar *end = popt + BOOTP_HDR_SIZE;
765         int oplen, size;
766 #if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_TIMEOFFSET)
767         int *to_ptr;
768 #endif
769
770         while (popt < end && *popt != 0xff) {
771                 oplen = *(popt + 1);
772                 switch (*popt) {
773                 case 1:
774                         net_copy_ip(&net_netmask, (popt + 2));
775                         break;
776 #if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_TIMEOFFSET)
777                 case 2:         /* Time offset  */
778                         to_ptr = &NetTimeOffset;
779                         NetCopyLong((ulong *)to_ptr, (ulong *)(popt + 2));
780                         NetTimeOffset = ntohl(NetTimeOffset);
781                         break;
782 #endif
783                 case 3:
784                         net_copy_ip(&net_gateway, (popt + 2));
785                         break;
786                 case 6:
787                         net_copy_ip(&net_dns_server, (popt + 2));
788 #if defined(CONFIG_BOOTP_DNS2)
789                         if (*(popt + 1) > 4)
790                                 net_copy_ip(&net_dns_server2, (popt + 2 + 4));
791 #endif
792                         break;
793                 case 12:
794                         size = truncate_sz("Host Name",
795                                 sizeof(NetOurHostName), oplen);
796                         memcpy(&NetOurHostName, popt + 2, size);
797                         NetOurHostName[size] = 0;
798                         break;
799                 case 15:        /* Ignore Domain Name Option */
800                         break;
801                 case 17:
802                         size = truncate_sz("Root Path",
803                                 sizeof(NetOurRootPath), oplen);
804                         memcpy(&NetOurRootPath, popt + 2, size);
805                         NetOurRootPath[size] = 0;
806                         break;
807                 case 28:        /* Ignore Broadcast Address Option */
808                         break;
809 #if defined(CONFIG_CMD_SNTP) && defined(CONFIG_BOOTP_NTPSERVER)
810                 case 42:        /* NTP server IP */
811                         net_copy_ip(&net_ntp_server, (popt + 2));
812                         break;
813 #endif
814                 case 51:
815                         NetCopyLong(&dhcp_leasetime, (ulong *) (popt + 2));
816                         break;
817                 case 53:        /* Ignore Message Type Option */
818                         break;
819                 case 54:
820                         net_copy_ip(&dhcp_server_ip, (popt + 2));
821                         break;
822                 case 58:        /* Ignore Renewal Time Option */
823                         break;
824                 case 59:        /* Ignore Rebinding Time Option */
825                         break;
826                 case 66:        /* Ignore TFTP server name */
827                         break;
828                 case 67:        /* vendor opt bootfile */
829                         /*
830                          * I can't use dhcp_vendorex_proc here because I need
831                          * to write into the bootp packet - even then I had to
832                          * pass the bootp packet pointer into here as the
833                          * second arg
834                          */
835                         size = truncate_sz("Opt Boot File",
836                                             sizeof(bp->bp_file),
837                                             oplen);
838                         if (bp->bp_file[0] == '\0' && size > 0) {
839                                 /*
840                                  * only use vendor boot file if we didn't
841                                  * receive a boot file in the main non-vendor
842                                  * part of the packet - god only knows why
843                                  * some vendors chose not to use this perfectly
844                                  * good spot to store the boot file (join on
845                                  * Tru64 Unix) it seems mind bogglingly crazy
846                                  * to me
847                                  */
848                                 printf("*** WARNING: using vendor "
849                                         "optional boot file\n");
850                                 memcpy(bp->bp_file, popt + 2, size);
851                                 bp->bp_file[size] = '\0';
852                         }
853                         break;
854                 default:
855 #if defined(CONFIG_BOOTP_VENDOREX)
856                         if (dhcp_vendorex_proc(popt))
857                                 break;
858 #endif
859                         printf("*** Unhandled DHCP Option in OFFER/ACK:"
860                                 " %d\n", *popt);
861                         break;
862                 }
863                 popt += oplen + 2;      /* Process next option */
864         }
865 }
866
867 static int DhcpMessageType(unsigned char *popt)
868 {
869         if (NetReadLong((ulong *)popt) != htonl(BOOTP_VENDOR_MAGIC))
870                 return -1;
871
872         popt += 4;
873         while (*popt != 0xff) {
874                 if (*popt == 53)        /* DHCP Message Type */
875                         return *(popt + 2);
876                 popt += *(popt + 1) + 2;        /* Scan through all options */
877         }
878         return -1;
879 }
880
881 static void DhcpSendRequestPkt(struct Bootp_t *bp_offer)
882 {
883         uchar *pkt, *iphdr;
884         struct Bootp_t *bp;
885         int pktlen, iplen, extlen;
886         int eth_hdr_size;
887         struct in_addr offered_ip;
888         struct in_addr zero_ip;
889         struct in_addr bcast_ip;
890
891         debug("DhcpSendRequestPkt: Sending DHCPREQUEST\n");
892         pkt = NetTxPacket;
893         memset((void *)pkt, 0, PKTSIZE);
894
895         eth_hdr_size = NetSetEther(pkt, NetBcastAddr, PROT_IP);
896         pkt += eth_hdr_size;
897
898         iphdr = pkt;    /* We'll need this later to set proper pkt size */
899         pkt += IP_UDP_HDR_SIZE;
900
901         bp = (struct Bootp_t *)pkt;
902         bp->bp_op = OP_BOOTREQUEST;
903         bp->bp_htype = HWT_ETHER;
904         bp->bp_hlen = HWL_ETHER;
905         bp->bp_hops = 0;
906         bp->bp_secs = htons(get_timer(0) / 1000);
907         /* Do not set the client IP, your IP, or server IP yet, since it
908          * hasn't been ACK'ed by the server yet */
909
910         /*
911          * RFC3046 requires Relay Agents to discard packets with
912          * nonzero and offered giaddr
913          */
914         zero_ip.s_addr = 0;
915         net_write_ip(&bp->bp_giaddr, zero_ip);
916
917         memcpy(bp->bp_chaddr, NetOurEther, 6);
918
919         /*
920          * ID is the id of the OFFER packet
921          */
922
923         NetCopyLong(&bp->bp_id, &bp_offer->bp_id);
924
925         /*
926          * Copy options from OFFER packet if present
927          */
928
929         /* Copy offered IP into the parameters request list */
930         net_copy_ip(&offered_ip, &bp_offer->bp_yiaddr);
931         extlen = dhcp_extended((u8 *)bp->bp_vend, DHCP_REQUEST,
932                 dhcp_server_ip, offered_ip);
933
934         iplen = BOOTP_HDR_SIZE - OPT_FIELD_SIZE + extlen;
935         pktlen = eth_hdr_size + IP_UDP_HDR_SIZE + iplen;
936         bcast_ip.s_addr = 0xFFFFFFFFL;
937         net_set_udp_header(iphdr, bcast_ip, PORT_BOOTPS, PORT_BOOTPC, iplen);
938
939 #ifdef CONFIG_BOOTP_DHCP_REQUEST_DELAY
940         udelay(CONFIG_BOOTP_DHCP_REQUEST_DELAY);
941 #endif  /* CONFIG_BOOTP_DHCP_REQUEST_DELAY */
942         debug("Transmitting DHCPREQUEST packet: len = %d\n", pktlen);
943         NetSendPacket(NetTxPacket, pktlen);
944 }
945
946 /*
947  *      Handle DHCP received packets.
948  */
949 static void dhcp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
950                          unsigned src, unsigned len)
951 {
952         struct Bootp_t *bp = (struct Bootp_t *)pkt;
953
954         debug("DHCPHandler: got packet: (src=%d, dst=%d, len=%d) state: %d\n",
955                 src, dest, len, dhcp_state);
956
957         /* Filter out pkts we don't want */
958         if (BootpCheckPkt(pkt, dest, src, len))
959                 return;
960
961         debug("DHCPHandler: got DHCP packet: (src=%d, dst=%d, len=%d) state:"
962                 " %d\n", src, dest, len, dhcp_state);
963
964         switch (dhcp_state) {
965         case SELECTING:
966                 /*
967                  * Wait an appropriate time for any potential DHCPOFFER packets
968                  * to arrive.  Then select one, and generate DHCPREQUEST
969                  * response.  If filename is in format we recognize, assume it
970                  * is a valid OFFER from a server we want.
971                  */
972                 debug("DHCP: state=SELECTING bp_file: \"%s\"\n", bp->bp_file);
973 #ifdef CONFIG_SYS_BOOTFILE_PREFIX
974                 if (strncmp(bp->bp_file,
975                             CONFIG_SYS_BOOTFILE_PREFIX,
976                             strlen(CONFIG_SYS_BOOTFILE_PREFIX)) == 0) {
977 #endif  /* CONFIG_SYS_BOOTFILE_PREFIX */
978
979                         debug("TRANSITIONING TO REQUESTING STATE\n");
980                         dhcp_state = REQUESTING;
981
982                         if (NetReadLong((ulong *)&bp->bp_vend[0]) ==
983                                                 htonl(BOOTP_VENDOR_MAGIC))
984                                 DhcpOptionsProcess((u8 *)&bp->bp_vend[4], bp);
985
986                         NetSetTimeout(5000, BootpTimeout);
987                         DhcpSendRequestPkt(bp);
988 #ifdef CONFIG_SYS_BOOTFILE_PREFIX
989                 }
990 #endif  /* CONFIG_SYS_BOOTFILE_PREFIX */
991
992                 return;
993                 break;
994         case REQUESTING:
995                 debug("DHCP State: REQUESTING\n");
996
997                 if (DhcpMessageType((u8 *)bp->bp_vend) == DHCP_ACK) {
998                         if (NetReadLong((ulong *)&bp->bp_vend[0]) ==
999                                                 htonl(BOOTP_VENDOR_MAGIC))
1000                                 DhcpOptionsProcess((u8 *)&bp->bp_vend[4], bp);
1001                         /* Store net params from reply */
1002                         BootpCopyNetParams(bp);
1003                         dhcp_state = BOUND;
1004                         printf("DHCP client bound to address %pI4 (%lu ms)\n",
1005                                 &net_ip, get_timer(bootp_start));
1006                         bootstage_mark_name(BOOTSTAGE_ID_BOOTP_STOP,
1007                                 "bootp_stop");
1008
1009                         net_auto_load();
1010                         return;
1011                 }
1012                 break;
1013         case BOUND:
1014                 /* DHCP client bound to address */
1015                 break;
1016         default:
1017                 puts("DHCP: INVALID STATE\n");
1018                 break;
1019         }
1020
1021 }
1022
1023 void DhcpRequest(void)
1024 {
1025         BootpRequest();
1026 }
1027 #endif  /* CONFIG_CMD_DHCP */