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