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