99db3d5505dc01c5f7a38e94aeeffa960464f7d8
[mirror_edk2.git] / NetworkPkg / HttpBootDxe / HttpBootClient.c
1 /** @file
2 Implementation of the boot file download function.
3
4 Copyright (c) 2015 - 2017, Intel Corporation. All rights reserved.<BR>
5 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
6 This program and the accompanying materials are licensed and made available under
7 the terms and conditions of the BSD License that accompanies this distribution.
8 The full text of the license may be found at
9 http://opensource.org/licenses/bsd-license.php.
10
11 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
12 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
13
14 **/
15
16 #include "HttpBootDxe.h"
17
18 /**
19 Update the IP and URL device path node to include the boot resource information.
20
21 @param[in] Private The pointer to the driver's private data.
22
23 @retval EFI_SUCCESS Device patch successfully updated.
24 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
25 @retval Others Unexpected error happened.
26
27 **/
28 EFI_STATUS
29 HttpBootUpdateDevicePath (
30 IN HTTP_BOOT_PRIVATE_DATA *Private
31 )
32 {
33 EFI_DEV_PATH *Node;
34 EFI_DEVICE_PATH_PROTOCOL *TmpDevicePath;
35 EFI_DEVICE_PATH_PROTOCOL *NewDevicePath;
36 UINTN Length;
37 EFI_STATUS Status;
38
39 TmpDevicePath = NULL;
40
41 //
42 // Update the IP node with DHCP assigned information.
43 //
44 if (!Private->UsingIpv6) {
45 Node = AllocateZeroPool (sizeof (IPv4_DEVICE_PATH));
46 if (Node == NULL) {
47 return EFI_OUT_OF_RESOURCES;
48 }
49 Node->Ipv4.Header.Type = MESSAGING_DEVICE_PATH;
50 Node->Ipv4.Header.SubType = MSG_IPv4_DP;
51 SetDevicePathNodeLength (Node, sizeof (IPv4_DEVICE_PATH));
52 CopyMem (&Node->Ipv4.LocalIpAddress, &Private->StationIp, sizeof (EFI_IPv4_ADDRESS));
53 Node->Ipv4.RemotePort = Private->Port;
54 Node->Ipv4.Protocol = EFI_IP_PROTO_TCP;
55 Node->Ipv4.StaticIpAddress = FALSE;
56 CopyMem (&Node->Ipv4.GatewayIpAddress, &Private->GatewayIp, sizeof (EFI_IPv4_ADDRESS));
57 CopyMem (&Node->Ipv4.SubnetMask, &Private->SubnetMask, sizeof (EFI_IPv4_ADDRESS));
58 } else {
59 Node = AllocateZeroPool (sizeof (IPv6_DEVICE_PATH));
60 if (Node == NULL) {
61 return EFI_OUT_OF_RESOURCES;
62 }
63 Node->Ipv6.Header.Type = MESSAGING_DEVICE_PATH;
64 Node->Ipv6.Header.SubType = MSG_IPv6_DP;
65 SetDevicePathNodeLength (Node, sizeof (IPv6_DEVICE_PATH));
66 Node->Ipv6.PrefixLength = IP6_PREFIX_LENGTH;
67 Node->Ipv6.RemotePort = Private->Port;
68 Node->Ipv6.Protocol = EFI_IP_PROTO_TCP;
69 Node->Ipv6.IpAddressOrigin = 0;
70 CopyMem (&Node->Ipv6.LocalIpAddress, &Private->StationIp.v6, sizeof (EFI_IPv6_ADDRESS));
71 CopyMem (&Node->Ipv6.RemoteIpAddress, &Private->ServerIp.v6, sizeof (EFI_IPv6_ADDRESS));
72 CopyMem (&Node->Ipv6.GatewayIpAddress, &Private->GatewayIp.v6, sizeof (EFI_IPv6_ADDRESS));
73 }
74
75 TmpDevicePath = AppendDevicePathNode (Private->ParentDevicePath, (EFI_DEVICE_PATH_PROTOCOL*) Node);
76 FreePool (Node);
77 if (TmpDevicePath == NULL) {
78 return EFI_OUT_OF_RESOURCES;
79 }
80
81 //
82 // Update the URI node with the boot file URI.
83 //
84 Length = sizeof (EFI_DEVICE_PATH_PROTOCOL) + AsciiStrSize (Private->BootFileUri);
85 Node = AllocatePool (Length);
86 if (Node == NULL) {
87 FreePool (TmpDevicePath);
88 return EFI_OUT_OF_RESOURCES;
89 }
90 Node->DevPath.Type = MESSAGING_DEVICE_PATH;
91 Node->DevPath.SubType = MSG_URI_DP;
92 SetDevicePathNodeLength (Node, Length);
93 CopyMem ((UINT8*) Node + sizeof (EFI_DEVICE_PATH_PROTOCOL), Private->BootFileUri, AsciiStrSize (Private->BootFileUri));
94
95 NewDevicePath = AppendDevicePathNode (TmpDevicePath, (EFI_DEVICE_PATH_PROTOCOL*) Node);
96 FreePool (Node);
97 FreePool (TmpDevicePath);
98 if (NewDevicePath == NULL) {
99 return EFI_OUT_OF_RESOURCES;
100 }
101
102 if (!Private->UsingIpv6) {
103 //
104 // Reinstall the device path protocol of the child handle.
105 //
106 Status = gBS->ReinstallProtocolInterface (
107 Private->Ip4Nic->Controller,
108 &gEfiDevicePathProtocolGuid,
109 Private->Ip4Nic->DevicePath,
110 NewDevicePath
111 );
112 if (EFI_ERROR (Status)) {
113 return Status;
114 }
115
116 FreePool (Private->Ip4Nic->DevicePath);
117 Private->Ip4Nic->DevicePath = NewDevicePath;
118 } else {
119 //
120 // Reinstall the device path protocol of the child handle.
121 //
122 Status = gBS->ReinstallProtocolInterface (
123 Private->Ip6Nic->Controller,
124 &gEfiDevicePathProtocolGuid,
125 Private->Ip6Nic->DevicePath,
126 NewDevicePath
127 );
128 if (EFI_ERROR (Status)) {
129 return Status;
130 }
131 FreePool (Private->Ip6Nic->DevicePath);
132 Private->Ip6Nic->DevicePath = NewDevicePath;
133 }
134
135 return EFI_SUCCESS;
136 }
137
138 /**
139 Parse the boot file URI information from the selected Dhcp4 offer packet.
140
141 @param[in] Private The pointer to the driver's private data.
142
143 @retval EFI_SUCCESS Successfully parsed out all the boot information.
144 @retval Others Failed to parse out the boot information.
145
146 **/
147 EFI_STATUS
148 HttpBootDhcp4ExtractUriInfo (
149 IN HTTP_BOOT_PRIVATE_DATA *Private
150 )
151 {
152 HTTP_BOOT_DHCP4_PACKET_CACHE *SelectOffer;
153 HTTP_BOOT_DHCP4_PACKET_CACHE *HttpOffer;
154 UINT32 SelectIndex;
155 UINT32 ProxyIndex;
156 EFI_DHCP4_PACKET_OPTION *Option;
157 EFI_STATUS Status;
158
159 ASSERT (Private != NULL);
160 ASSERT (Private->SelectIndex != 0);
161 SelectIndex = Private->SelectIndex - 1;
162 ASSERT (SelectIndex < HTTP_BOOT_OFFER_MAX_NUM);
163
164 Status = EFI_SUCCESS;
165
166 //
167 // SelectOffer contains the IP address configuration and name server configuration.
168 // HttpOffer contains the boot file URL.
169 //
170 SelectOffer = &Private->OfferBuffer[SelectIndex].Dhcp4;
171 if (Private->FilePathUri == NULL) {
172 //
173 // In Corporate environment, we need a HttpOffer.
174 //
175 if ((SelectOffer->OfferType == HttpOfferTypeDhcpIpUri) ||
176 (SelectOffer->OfferType == HttpOfferTypeDhcpIpUriDns) ||
177 (SelectOffer->OfferType == HttpOfferTypeDhcpNameUriDns)) {
178 HttpOffer = SelectOffer;
179 } else {
180 ASSERT (Private->SelectProxyType != HttpOfferTypeMax);
181 ProxyIndex = Private->OfferIndex[Private->SelectProxyType][0];
182 HttpOffer = &Private->OfferBuffer[ProxyIndex].Dhcp4;
183 }
184 Private->BootFileUriParser = HttpOffer->UriParser;
185 Private->BootFileUri = (CHAR8*) HttpOffer->OptList[HTTP_BOOT_DHCP4_TAG_INDEX_BOOTFILE]->Data;
186 } else {
187 //
188 // In Home environment the BootFileUri comes from the FilePath.
189 //
190 Private->BootFileUriParser = Private->FilePathUriParser;
191 Private->BootFileUri = Private->FilePathUri;
192 }
193
194 //
195 // Check the URI scheme.
196 //
197 Status = HttpBootCheckUriScheme (Private->BootFileUri);
198 if (EFI_ERROR (Status)) {
199 DEBUG ((EFI_D_ERROR, "HttpBootDhcp4ExtractUriInfo: %r.\n", Status));
200 return Status;
201 }
202
203 //
204 // Configure the default DNS server if server assigned.
205 //
206 if ((SelectOffer->OfferType == HttpOfferTypeDhcpNameUriDns) ||
207 (SelectOffer->OfferType == HttpOfferTypeDhcpDns) ||
208 (SelectOffer->OfferType == HttpOfferTypeDhcpIpUriDns)) {
209 Option = SelectOffer->OptList[HTTP_BOOT_DHCP4_TAG_INDEX_DNS_SERVER];
210 ASSERT (Option != NULL);
211 Status = HttpBootRegisterIp4Dns (
212 Private,
213 Option->Length,
214 Option->Data
215 );
216 if (EFI_ERROR (Status)) {
217 return Status;
218 }
219 }
220
221 //
222 // Extract the port from URL, and use default HTTP port 80 if not provided.
223 //
224 Status = HttpUrlGetPort (
225 Private->BootFileUri,
226 Private->BootFileUriParser,
227 &Private->Port
228 );
229 if (EFI_ERROR (Status) || Private->Port == 0) {
230 Private->Port = 80;
231 }
232
233 //
234 // All boot informations are valid here.
235 //
236 AsciiPrint ("\n URI: %a", Private->BootFileUri);
237
238 //
239 // Update the device path to include the IP and boot URI information.
240 //
241 Status = HttpBootUpdateDevicePath (Private);
242
243 return Status;
244 }
245
246 /**
247 Parse the boot file URI information from the selected Dhcp6 offer packet.
248
249 @param[in] Private The pointer to the driver's private data.
250
251 @retval EFI_SUCCESS Successfully parsed out all the boot information.
252 @retval Others Failed to parse out the boot information.
253
254 **/
255 EFI_STATUS
256 HttpBootDhcp6ExtractUriInfo (
257 IN HTTP_BOOT_PRIVATE_DATA *Private
258 )
259 {
260 HTTP_BOOT_DHCP6_PACKET_CACHE *SelectOffer;
261 HTTP_BOOT_DHCP6_PACKET_CACHE *HttpOffer;
262 UINT32 SelectIndex;
263 UINT32 ProxyIndex;
264 EFI_DHCP6_PACKET_OPTION *Option;
265 EFI_IPv6_ADDRESS IpAddr;
266 CHAR8 *HostName;
267 UINTN HostNameSize;
268 CHAR16 *HostNameStr;
269 EFI_STATUS Status;
270
271 ASSERT (Private != NULL);
272 ASSERT (Private->SelectIndex != 0);
273 SelectIndex = Private->SelectIndex - 1;
274 ASSERT (SelectIndex < HTTP_BOOT_OFFER_MAX_NUM);
275
276 Status = EFI_SUCCESS;
277 HostName = NULL;
278 //
279 // SelectOffer contains the IP address configuration and name server configuration.
280 // HttpOffer contains the boot file URL.
281 //
282 SelectOffer = &Private->OfferBuffer[SelectIndex].Dhcp6;
283 if (Private->FilePathUri == NULL) {
284 //
285 // In Corporate environment, we need a HttpOffer.
286 //
287 if ((SelectOffer->OfferType == HttpOfferTypeDhcpIpUri) ||
288 (SelectOffer->OfferType == HttpOfferTypeDhcpIpUriDns) ||
289 (SelectOffer->OfferType == HttpOfferTypeDhcpNameUriDns)) {
290 HttpOffer = SelectOffer;
291 } else {
292 ASSERT (Private->SelectProxyType != HttpOfferTypeMax);
293 ProxyIndex = Private->OfferIndex[Private->SelectProxyType][0];
294 HttpOffer = &Private->OfferBuffer[ProxyIndex].Dhcp6;
295 }
296 Private->BootFileUriParser = HttpOffer->UriParser;
297 Private->BootFileUri = (CHAR8*) HttpOffer->OptList[HTTP_BOOT_DHCP6_IDX_BOOT_FILE_URL]->Data;
298 } else {
299 //
300 // In Home environment the BootFileUri comes from the FilePath.
301 //
302 Private->BootFileUriParser = Private->FilePathUriParser;
303 Private->BootFileUri = Private->FilePathUri;
304 }
305
306 //
307 // Check the URI scheme.
308 //
309 Status = HttpBootCheckUriScheme (Private->BootFileUri);
310 if (EFI_ERROR (Status)) {
311 DEBUG ((EFI_D_ERROR, "HttpBootDhcp6ExtractUriInfo: %r.\n", Status));
312 return Status;
313 }
314
315 //
316 // Set the Local station address to IP layer.
317 //
318 Status = HttpBootSetIp6Address (Private);
319 if (EFI_ERROR (Status)) {
320 return Status;
321 }
322
323 //
324 // Register the IPv6 gateway address to the network device.
325 //
326 Status = HttpBootSetIp6Gateway (Private);
327 if (EFI_ERROR (Status)) {
328 return Status;
329 }
330
331 //
332 // Configure the default DNS server if server assigned.
333 //
334 if ((SelectOffer->OfferType == HttpOfferTypeDhcpNameUriDns) ||
335 (SelectOffer->OfferType == HttpOfferTypeDhcpDns) ||
336 (SelectOffer->OfferType == HttpOfferTypeDhcpIpUriDns)) {
337 Option = SelectOffer->OptList[HTTP_BOOT_DHCP6_IDX_DNS_SERVER];
338 ASSERT (Option != NULL);
339 Status = HttpBootSetIp6Dns (
340 Private,
341 HTONS (Option->OpLen),
342 Option->Data
343 );
344 if (EFI_ERROR (Status)) {
345 return Status;
346 }
347 }
348
349 //
350 // Extract the HTTP server Ip frome URL. This is used to Check route table
351 // whether can send message to HTTP Server Ip through the GateWay.
352 //
353 Status = HttpUrlGetIp6 (
354 Private->BootFileUri,
355 Private->BootFileUriParser,
356 &IpAddr
357 );
358
359 if (EFI_ERROR (Status)) {
360 //
361 // The Http server address is expressed by Name Ip, so perform DNS resolution
362 //
363 Status = HttpUrlGetHostName (
364 Private->BootFileUri,
365 Private->BootFileUriParser,
366 &HostName
367 );
368 if (EFI_ERROR (Status)) {
369 return Status;
370 }
371
372 HostNameSize = AsciiStrSize (HostName);
373 HostNameStr = AllocateZeroPool (HostNameSize * sizeof (CHAR16));
374 if (HostNameStr == NULL) {
375 Status = EFI_OUT_OF_RESOURCES;
376 goto Error;
377 }
378
379 AsciiStrToUnicodeStrS (HostName, HostNameStr, HostNameSize);
380 Status = HttpBootDns (Private, HostNameStr, &IpAddr);
381 FreePool (HostNameStr);
382 if (EFI_ERROR (Status)) {
383 goto Error;
384 }
385 }
386
387 CopyMem (&Private->ServerIp.v6, &IpAddr, sizeof (EFI_IPv6_ADDRESS));
388
389 //
390 // Extract the port from URL, and use default HTTP port 80 if not provided.
391 //
392 Status = HttpUrlGetPort (
393 Private->BootFileUri,
394 Private->BootFileUriParser,
395 &Private->Port
396 );
397 if (EFI_ERROR (Status) || Private->Port == 0) {
398 Private->Port = 80;
399 }
400
401 //
402 // All boot informations are valid here.
403 //
404 AsciiPrint ("\n URI: %a", Private->BootFileUri);
405 //
406 // Update the device path to include the IP and boot URI information.
407 //
408 Status = HttpBootUpdateDevicePath (Private);
409
410 Error:
411
412 if (HostName != NULL) {
413 FreePool (HostName);
414 }
415
416 return Status;
417 }
418
419
420 /**
421 Discover all the boot information for boot file.
422
423 @param[in, out] Private The pointer to the driver's private data.
424
425 @retval EFI_SUCCESS Successfully obtained all the boot information .
426 @retval Others Failed to retrieve the boot information.
427
428 **/
429 EFI_STATUS
430 HttpBootDiscoverBootInfo (
431 IN OUT HTTP_BOOT_PRIVATE_DATA *Private
432 )
433 {
434 EFI_STATUS Status;
435
436 //
437 // Start D.O.R.A/S.A.R.R exchange to acquire station ip address and
438 // other Http boot information.
439 //
440 Status = HttpBootDhcp (Private);
441 if (EFI_ERROR (Status)) {
442 return Status;
443 }
444
445 if (!Private->UsingIpv6) {
446 Status = HttpBootDhcp4ExtractUriInfo (Private);
447 } else {
448 Status = HttpBootDhcp6ExtractUriInfo (Private);
449 }
450
451 return Status;
452 }
453
454 /**
455 Create a HttpIo instance for the file download.
456
457 @param[in] Private The pointer to the driver's private data.
458
459 @retval EFI_SUCCESS Successfully created.
460 @retval Others Failed to create HttpIo.
461
462 **/
463 EFI_STATUS
464 HttpBootCreateHttpIo (
465 IN HTTP_BOOT_PRIVATE_DATA *Private
466 )
467 {
468 HTTP_IO_CONFIG_DATA ConfigData;
469 EFI_STATUS Status;
470 EFI_HANDLE ImageHandle;
471
472 ASSERT (Private != NULL);
473
474 ZeroMem (&ConfigData, sizeof (HTTP_IO_CONFIG_DATA));
475 if (!Private->UsingIpv6) {
476 ConfigData.Config4.HttpVersion = HttpVersion11;
477 ConfigData.Config4.RequestTimeOut = HTTP_BOOT_REQUEST_TIMEOUT;
478 IP4_COPY_ADDRESS (&ConfigData.Config4.LocalIp, &Private->StationIp.v4);
479 IP4_COPY_ADDRESS (&ConfigData.Config4.SubnetMask, &Private->SubnetMask.v4);
480 ImageHandle = Private->Ip4Nic->ImageHandle;
481 } else {
482 ConfigData.Config6.HttpVersion = HttpVersion11;
483 ConfigData.Config6.RequestTimeOut = HTTP_BOOT_REQUEST_TIMEOUT;
484 IP6_COPY_ADDRESS (&ConfigData.Config6.LocalIp, &Private->StationIp.v6);
485 ImageHandle = Private->Ip6Nic->ImageHandle;
486 }
487
488 Status = HttpIoCreateIo (
489 ImageHandle,
490 Private->Controller,
491 Private->UsingIpv6 ? IP_VERSION_6 : IP_VERSION_4,
492 &ConfigData,
493 &Private->HttpIo
494 );
495 if (EFI_ERROR (Status)) {
496 return Status;
497 }
498
499 Private->HttpCreated = TRUE;
500 return EFI_SUCCESS;
501 }
502
503 /**
504 Release all the resource of a cache item.
505
506 @param[in] Cache The pointer to the cache item.
507
508 **/
509 VOID
510 HttpBootFreeCache (
511 IN HTTP_BOOT_CACHE_CONTENT *Cache
512 )
513 {
514 UINTN Index;
515 LIST_ENTRY *Entry;
516 LIST_ENTRY *NextEntry;
517 HTTP_BOOT_ENTITY_DATA *EntityData;
518
519 if (Cache != NULL) {
520 //
521 // Free the request data
522 //
523 if (Cache->RequestData != NULL) {
524 if (Cache->RequestData->Url != NULL) {
525 FreePool (Cache->RequestData->Url);
526 }
527 FreePool (Cache->RequestData);
528 }
529
530 //
531 // Free the response header
532 //
533 if (Cache->ResponseData != NULL) {
534 if (Cache->ResponseData->Headers != NULL) {
535 for (Index = 0; Index < Cache->ResponseData->HeaderCount; Index++) {
536 FreePool (Cache->ResponseData->Headers[Index].FieldName);
537 FreePool (Cache->ResponseData->Headers[Index].FieldValue);
538 }
539 FreePool (Cache->ResponseData->Headers);
540 }
541 }
542
543 //
544 // Free the response body
545 //
546 NET_LIST_FOR_EACH_SAFE (Entry, NextEntry, &Cache->EntityDataList) {
547 EntityData = NET_LIST_USER_STRUCT (Entry, HTTP_BOOT_ENTITY_DATA, Link);
548 if (EntityData->Block != NULL) {
549 FreePool (EntityData->Block);
550 }
551 RemoveEntryList (&EntityData->Link);
552 FreePool (EntityData);
553 }
554
555 FreePool (Cache);
556 }
557 }
558
559 /**
560 Clean up all cached data.
561
562 @param[in] Private The pointer to the driver's private data.
563
564 **/
565 VOID
566 HttpBootFreeCacheList (
567 IN HTTP_BOOT_PRIVATE_DATA *Private
568 )
569 {
570 LIST_ENTRY *Entry;
571 LIST_ENTRY *NextEntry;
572 HTTP_BOOT_CACHE_CONTENT *Cache;
573
574 NET_LIST_FOR_EACH_SAFE (Entry, NextEntry, &Private->CacheList) {
575 Cache = NET_LIST_USER_STRUCT (Entry, HTTP_BOOT_CACHE_CONTENT, Link);
576 RemoveEntryList (&Cache->Link);
577 HttpBootFreeCache (Cache);
578 }
579 }
580
581 /**
582 Get the file content from cached data.
583
584 @param[in] Private The pointer to the driver's private data.
585 @param[in] Uri Uri of the file to be retrieved from cache.
586 @param[in, out] BufferSize On input the size of Buffer in bytes. On output with a return
587 code of EFI_SUCCESS, the amount of data transferred to
588 Buffer. On output with a return code of EFI_BUFFER_TOO_SMALL,
589 the size of Buffer required to retrieve the requested file.
590 @param[out] Buffer The memory buffer to transfer the file to. IF Buffer is NULL,
591 then the size of the requested file is returned in
592 BufferSize.
593 @param[out] ImageType The image type of the downloaded file.
594
595 @retval EFI_SUCCESS Successfully created.
596 @retval Others Failed to create HttpIo.
597
598 **/
599 EFI_STATUS
600 HttpBootGetFileFromCache (
601 IN HTTP_BOOT_PRIVATE_DATA *Private,
602 IN CHAR16 *Uri,
603 IN OUT UINTN *BufferSize,
604 OUT UINT8 *Buffer,
605 OUT HTTP_BOOT_IMAGE_TYPE *ImageType
606 )
607 {
608 LIST_ENTRY *Entry;
609 LIST_ENTRY *Entry2;
610 HTTP_BOOT_CACHE_CONTENT *Cache;
611 HTTP_BOOT_ENTITY_DATA *EntityData;
612 UINTN CopyedSize;
613
614 if (Uri == NULL || BufferSize == 0 || Buffer == NULL || ImageType == NULL) {
615 return EFI_INVALID_PARAMETER;
616 }
617
618 NET_LIST_FOR_EACH (Entry, &Private->CacheList) {
619 Cache = NET_LIST_USER_STRUCT (Entry, HTTP_BOOT_CACHE_CONTENT, Link);
620 //
621 // Compare the URI to see whether we already have a cache for this file.
622 //
623 if ((Cache->RequestData != NULL) &&
624 (Cache->RequestData->Url != NULL) &&
625 (StrCmp (Uri, Cache->RequestData->Url) == 0))
626 {
627 //
628 // Hit in cache, record image type.
629 //
630 *ImageType = Cache->ImageType;
631
632 //
633 // Check buffer size.
634 //
635 if (*BufferSize < Cache->EntityLength) {
636 *BufferSize = Cache->EntityLength;
637 return EFI_BUFFER_TOO_SMALL;
638 }
639
640 //
641 // Fill data to buffer.
642 //
643 CopyedSize = 0;
644 NET_LIST_FOR_EACH (Entry2, &Cache->EntityDataList) {
645 EntityData = NET_LIST_USER_STRUCT (Entry2, HTTP_BOOT_ENTITY_DATA, Link);
646 if (*BufferSize > CopyedSize) {
647 CopyMem (
648 Buffer + CopyedSize,
649 EntityData->DataStart,
650 MIN (EntityData->DataLength, *BufferSize - CopyedSize)
651 );
652 CopyedSize += MIN (EntityData->DataLength, *BufferSize - CopyedSize);
653 }
654 }
655 *BufferSize = CopyedSize;
656 return EFI_SUCCESS;
657 }
658 }
659
660 return EFI_NOT_FOUND;
661 }
662
663 /**
664 A callback function to intercept events during message parser.
665
666 This function will be invoked during HttpParseMessageBody() with various events type. An error
667 return status of the callback function will cause the HttpParseMessageBody() aborted.
668
669 @param[in] EventType Event type of this callback call.
670 @param[in] Data A pointer to data buffer.
671 @param[in] Length Length in bytes of the Data.
672 @param[in] Context Callback context set by HttpInitMsgParser().
673
674 @retval EFI_SUCCESS Continue to parser the message body.
675 @retval Others Abort the parse.
676
677 **/
678 EFI_STATUS
679 EFIAPI
680 HttpBootGetBootFileCallback (
681 IN HTTP_BODY_PARSE_EVENT EventType,
682 IN CHAR8 *Data,
683 IN UINTN Length,
684 IN VOID *Context
685 )
686 {
687 HTTP_BOOT_CALLBACK_DATA *CallbackData;
688 HTTP_BOOT_ENTITY_DATA *NewEntityData;
689
690 //
691 // We only care about the entity data.
692 //
693 if (EventType != BodyParseEventOnData) {
694 return EFI_SUCCESS;
695 }
696
697 CallbackData = (HTTP_BOOT_CALLBACK_DATA *) Context;
698 //
699 // Copy data if caller has provided a buffer.
700 //
701 if (CallbackData->BufferSize > CallbackData->CopyedSize) {
702 CopyMem (
703 CallbackData->Buffer + CallbackData->CopyedSize,
704 Data,
705 MIN (Length, CallbackData->BufferSize - CallbackData->CopyedSize)
706 );
707 CallbackData->CopyedSize += MIN (Length, CallbackData->BufferSize - CallbackData->CopyedSize);
708 }
709
710 //
711 // The caller doesn't provide a buffer, save the block into cache list.
712 //
713 if (CallbackData->Cache != NULL) {
714 NewEntityData = AllocatePool (sizeof (HTTP_BOOT_ENTITY_DATA));
715 if (NewEntityData == NULL) {
716 return EFI_OUT_OF_RESOURCES;
717 }
718 if (CallbackData->NewBlock) {
719 NewEntityData->Block = CallbackData->Block;
720 CallbackData->Block = NULL;
721 }
722 NewEntityData->DataLength = Length;
723 NewEntityData->DataStart = (UINT8*) Data;
724 InsertTailList (&CallbackData->Cache->EntityDataList, &NewEntityData->Link);
725 }
726 return EFI_SUCCESS;
727 }
728
729 /**
730 This function download the boot file by using UEFI HTTP protocol.
731
732 @param[in] Private The pointer to the driver's private data.
733 @param[in] HeaderOnly Only request the response header, it could save a lot of time if
734 the caller only want to know the size of the requested file.
735 @param[in, out] BufferSize On input the size of Buffer in bytes. On output with a return
736 code of EFI_SUCCESS, the amount of data transferred to
737 Buffer. On output with a return code of EFI_BUFFER_TOO_SMALL,
738 the size of Buffer required to retrieve the requested file.
739 @param[out] Buffer The memory buffer to transfer the file to. IF Buffer is NULL,
740 then the size of the requested file is returned in
741 BufferSize.
742 @param[out] ImageType The image type of the downloaded file.
743
744 @retval EFI_SUCCESS The file was loaded.
745 @retval EFI_INVALID_PARAMETER BufferSize is NULL or Buffer Size is not NULL but Buffer is NULL.
746 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources
747 @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small to read the current directory entry.
748 BufferSize has been updated with the size needed to complete
749 the request.
750 @retval Others Unexpected error happened.
751
752 **/
753 EFI_STATUS
754 HttpBootGetBootFile (
755 IN HTTP_BOOT_PRIVATE_DATA *Private,
756 IN BOOLEAN HeaderOnly,
757 IN OUT UINTN *BufferSize,
758 OUT UINT8 *Buffer,
759 OUT HTTP_BOOT_IMAGE_TYPE *ImageType
760 )
761 {
762 EFI_STATUS Status;
763 EFI_HTTP_STATUS_CODE StatusCode;
764 CHAR8 *HostName;
765 EFI_HTTP_REQUEST_DATA *RequestData;
766 HTTP_IO_RESPONSE_DATA *ResponseData;
767 HTTP_IO_RESPONSE_DATA ResponseBody;
768 HTTP_IO *HttpIo;
769 HTTP_IO_HEADER *HttpIoHeader;
770 VOID *Parser;
771 HTTP_BOOT_CALLBACK_DATA Context;
772 UINTN ContentLength;
773 HTTP_BOOT_CACHE_CONTENT *Cache;
774 UINT8 *Block;
775 UINTN UrlSize;
776 CHAR16 *Url;
777 BOOLEAN IdentityMode;
778 UINTN ReceivedSize;
779
780 ASSERT (Private != NULL);
781 ASSERT (Private->HttpCreated);
782
783 if (BufferSize == NULL || ImageType == NULL) {
784 return EFI_INVALID_PARAMETER;
785 }
786
787 if (*BufferSize != 0 && Buffer == NULL) {
788 return EFI_INVALID_PARAMETER;
789 }
790
791 //
792 // First, check whether we already cached the requested Uri.
793 //
794 UrlSize = AsciiStrSize (Private->BootFileUri);
795 Url = AllocatePool (UrlSize * sizeof (CHAR16));
796 if (Url == NULL) {
797 return EFI_OUT_OF_RESOURCES;
798 }
799 AsciiStrToUnicodeStrS (Private->BootFileUri, Url, UrlSize);
800 if (!HeaderOnly) {
801 Status = HttpBootGetFileFromCache (Private, Url, BufferSize, Buffer, ImageType);
802 if (Status != EFI_NOT_FOUND) {
803 FreePool (Url);
804 return Status;
805 }
806 }
807
808 //
809 // Not found in cache, try to download it through HTTP.
810 //
811
812 //
813 // 1. Create a temp cache item for the requested URI if caller doesn't provide buffer.
814 //
815 Cache = NULL;
816 if ((!HeaderOnly) && (*BufferSize == 0)) {
817 Cache = AllocateZeroPool (sizeof (HTTP_BOOT_CACHE_CONTENT));
818 if (Cache == NULL) {
819 Status = EFI_OUT_OF_RESOURCES;
820 goto ERROR_1;
821 }
822 Cache->ImageType = ImageTypeMax;
823 InitializeListHead (&Cache->EntityDataList);
824 }
825
826 //
827 // 2. Send HTTP request message.
828 //
829
830 //
831 // 2.1 Build HTTP header for the request, 3 header is needed to download a boot file:
832 // Host
833 // Accept
834 // User-Agent
835 //
836 HttpIoHeader = HttpBootCreateHeader (3);
837 if (HttpIoHeader == NULL) {
838 Status = EFI_OUT_OF_RESOURCES;
839 goto ERROR_2;
840 }
841
842 //
843 // Add HTTP header field 1: Host
844 //
845 HostName = NULL;
846 Status = HttpUrlGetHostName (
847 Private->BootFileUri,
848 Private->BootFileUriParser,
849 &HostName
850 );
851 if (EFI_ERROR (Status)) {
852 goto ERROR_3;
853 }
854 Status = HttpBootSetHeader (
855 HttpIoHeader,
856 HTTP_HEADER_HOST,
857 HostName
858 );
859 FreePool (HostName);
860 if (EFI_ERROR (Status)) {
861 goto ERROR_3;
862 }
863
864 //
865 // Add HTTP header field 2: Accept
866 //
867 Status = HttpBootSetHeader (
868 HttpIoHeader,
869 HTTP_HEADER_ACCEPT,
870 "*/*"
871 );
872 if (EFI_ERROR (Status)) {
873 goto ERROR_3;
874 }
875
876 //
877 // Add HTTP header field 3: User-Agent
878 //
879 Status = HttpBootSetHeader (
880 HttpIoHeader,
881 HTTP_HEADER_USER_AGENT,
882 HTTP_USER_AGENT_EFI_HTTP_BOOT
883 );
884 if (EFI_ERROR (Status)) {
885 goto ERROR_3;
886 }
887
888 //
889 // 2.2 Build the rest of HTTP request info.
890 //
891 RequestData = AllocatePool (sizeof (EFI_HTTP_REQUEST_DATA));
892 if (RequestData == NULL) {
893 Status = EFI_OUT_OF_RESOURCES;
894 goto ERROR_3;
895 }
896 RequestData->Method = HeaderOnly ? HttpMethodHead : HttpMethodGet;
897 RequestData->Url = Url;
898
899 //
900 // 2.3 Record the request info in a temp cache item.
901 //
902 if (Cache != NULL) {
903 Cache->RequestData = RequestData;
904 }
905
906 //
907 // 2.4 Send out the request to HTTP server.
908 //
909 HttpIo = &Private->HttpIo;
910 Status = HttpIoSendRequest (
911 HttpIo,
912 RequestData,
913 HttpIoHeader->HeaderCount,
914 HttpIoHeader->Headers,
915 0,
916 NULL
917 );
918 if (EFI_ERROR (Status)) {
919 goto ERROR_4;
920 }
921
922 //
923 // 3. Receive HTTP response message.
924 //
925
926 //
927 // 3.1 First step, use zero BodyLength to only receive the response headers.
928 //
929 ResponseData = AllocateZeroPool (sizeof(HTTP_IO_RESPONSE_DATA));
930 if (ResponseData == NULL) {
931 Status = EFI_OUT_OF_RESOURCES;
932 goto ERROR_4;
933 }
934 Status = HttpIoRecvResponse (
935 &Private->HttpIo,
936 TRUE,
937 ResponseData
938 );
939 if (EFI_ERROR (Status) || EFI_ERROR (ResponseData->Status)) {
940 if (EFI_ERROR (ResponseData->Status)) {
941 StatusCode = HttpIo->RspToken.Message->Data.Response->StatusCode;
942 HttpBootPrintErrorMessage (StatusCode);
943 Status = ResponseData->Status;
944 }
945 goto ERROR_5;
946 }
947
948 //
949 // Check the image type according to server's response.
950 //
951 Status = HttpBootCheckImageType (
952 Private->BootFileUri,
953 Private->BootFileUriParser,
954 ResponseData->HeaderCount,
955 ResponseData->Headers,
956 ImageType
957 );
958 if (EFI_ERROR (Status)) {
959 goto ERROR_5;
960 }
961
962 //
963 // 3.2 Cache the response header.
964 //
965 if (Cache != NULL) {
966 Cache->ResponseData = ResponseData;
967 Cache->ImageType = *ImageType;
968 }
969
970 //
971 // 3.3 Init a message-body parser from the header information.
972 //
973 Parser = NULL;
974 Context.NewBlock = FALSE;
975 Context.Block = NULL;
976 Context.CopyedSize = 0;
977 Context.Buffer = Buffer;
978 Context.BufferSize = *BufferSize;
979 Context.Cache = Cache;
980 Status = HttpInitMsgParser (
981 HeaderOnly? HttpMethodHead : HttpMethodGet,
982 ResponseData->Response.StatusCode,
983 ResponseData->HeaderCount,
984 ResponseData->Headers,
985 HttpBootGetBootFileCallback,
986 (VOID*) &Context,
987 &Parser
988 );
989 if (EFI_ERROR (Status)) {
990 goto ERROR_6;
991 }
992
993 //
994 // 3.4 Continue to receive and parse message-body if needed.
995 //
996 Block = NULL;
997 if (!HeaderOnly) {
998 //
999 // 3.4.1, check whether we are in identity transfer-coding.
1000 //
1001 ContentLength = 0;
1002 Status = HttpGetEntityLength (Parser, &ContentLength);
1003 if (!EFI_ERROR (Status)) {
1004 IdentityMode = TRUE;
1005 } else {
1006 IdentityMode = FALSE;
1007 }
1008
1009 //
1010 // 3.4.2, start the message-body download, the identity and chunked transfer-coding
1011 // is handled in different path here.
1012 //
1013 ZeroMem (&ResponseBody, sizeof (HTTP_IO_RESPONSE_DATA));
1014 if (IdentityMode) {
1015 //
1016 // In identity transfer-coding there is no need to parse the message body,
1017 // just download the message body to the user provided buffer directly.
1018 //
1019 ReceivedSize = 0;
1020 while (ReceivedSize < ContentLength) {
1021 ResponseBody.Body = (CHAR8*) Buffer + ReceivedSize;
1022 ResponseBody.BodyLength = *BufferSize - ReceivedSize;
1023 Status = HttpIoRecvResponse (
1024 &Private->HttpIo,
1025 FALSE,
1026 &ResponseBody
1027 );
1028 if (EFI_ERROR (Status) || EFI_ERROR (ResponseBody.Status)) {
1029 if (EFI_ERROR (ResponseBody.Status)) {
1030 Status = ResponseBody.Status;
1031 }
1032 goto ERROR_6;
1033 }
1034 ReceivedSize += ResponseBody.BodyLength;
1035 }
1036 } else {
1037 //
1038 // In "chunked" transfer-coding mode, so we need to parse the received
1039 // data to get the real entity content.
1040 //
1041 Block = NULL;
1042 while (!HttpIsMessageComplete (Parser)) {
1043 //
1044 // Allocate a buffer in Block to hold the message-body.
1045 // If caller provides a buffer, this Block will be reused in every HttpIoRecvResponse().
1046 // Otherwise a buffer, the buffer in Block will be cached and we should allocate a new before
1047 // every HttpIoRecvResponse().
1048 //
1049 if (Block == NULL || Context.BufferSize == 0) {
1050 Block = AllocatePool (HTTP_BOOT_BLOCK_SIZE);
1051 if (Block == NULL) {
1052 Status = EFI_OUT_OF_RESOURCES;
1053 goto ERROR_6;
1054 }
1055 Context.NewBlock = TRUE;
1056 Context.Block = Block;
1057 } else {
1058 Context.NewBlock = FALSE;
1059 }
1060
1061 ResponseBody.Body = (CHAR8*) Block;
1062 ResponseBody.BodyLength = HTTP_BOOT_BLOCK_SIZE;
1063 Status = HttpIoRecvResponse (
1064 &Private->HttpIo,
1065 FALSE,
1066 &ResponseBody
1067 );
1068 if (EFI_ERROR (Status) || EFI_ERROR (ResponseBody.Status)) {
1069 if (EFI_ERROR (ResponseBody.Status)) {
1070 Status = ResponseBody.Status;
1071 }
1072 goto ERROR_6;
1073 }
1074
1075 //
1076 // Parse the new received block of the message-body, the block will be saved in cache.
1077 //
1078 Status = HttpParseMessageBody (
1079 Parser,
1080 ResponseBody.BodyLength,
1081 ResponseBody.Body
1082 );
1083 if (EFI_ERROR (Status)) {
1084 goto ERROR_6;
1085 }
1086 }
1087 }
1088 }
1089
1090 //
1091 // 3.5 Message-body receive & parse is completed, we should be able to get the file size now.
1092 //
1093 Status = HttpGetEntityLength (Parser, &ContentLength);
1094 if (EFI_ERROR (Status)) {
1095 goto ERROR_6;
1096 }
1097
1098 if (*BufferSize < ContentLength) {
1099 Status = EFI_BUFFER_TOO_SMALL;
1100 } else {
1101 Status = EFI_SUCCESS;
1102 }
1103 *BufferSize = ContentLength;
1104
1105 //
1106 // 4. Save the cache item to driver's cache list and return.
1107 //
1108 if (Cache != NULL) {
1109 Cache->EntityLength = ContentLength;
1110 InsertTailList (&Private->CacheList, &Cache->Link);
1111 }
1112
1113 if (Parser != NULL) {
1114 HttpFreeMsgParser (Parser);
1115 }
1116
1117 return Status;
1118
1119 ERROR_6:
1120 if (Parser != NULL) {
1121 HttpFreeMsgParser (Parser);
1122 }
1123 if (Context.Block != NULL) {
1124 FreePool (Context.Block);
1125 }
1126 HttpBootFreeCache (Cache);
1127
1128 ERROR_5:
1129 if (ResponseData != NULL) {
1130 FreePool (ResponseData);
1131 }
1132 ERROR_4:
1133 if (RequestData != NULL) {
1134 FreePool (RequestData);
1135 }
1136 ERROR_3:
1137 HttpBootFreeHeader (HttpIoHeader);
1138 ERROR_2:
1139 if (Cache != NULL) {
1140 FreePool (Cache);
1141 }
1142 ERROR_1:
1143 if (Url != NULL) {
1144 FreePool (Url);
1145 }
1146
1147 return Status;
1148 }
1149