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