]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeHttpLib/DxeHttpLib.c
MdeModulePkg/BmBoot: Report status when fail to load/start boot option
[mirror_edk2.git] / MdeModulePkg / Library / DxeHttpLib / DxeHttpLib.c
1 /** @file
2 This library is used to share code between UEFI network stack modules.
3 It provides the helper routines to parse the HTTP message byte stream.
4
5 Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.<BR>
6 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
7 This program and the accompanying materials
8 are licensed and made available under the terms and conditions of the BSD License
9 which accompanies this distribution. The full text of the license may be found at<BR>
10 http://opensource.org/licenses/bsd-license.php
11
12 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
14
15 **/
16
17 #include "DxeHttpLib.h"
18
19
20
21 /**
22 Decode a percent-encoded URI component to the ASCII character.
23
24 Decode the input component in Buffer according to RFC 3986. The caller is responsible to make
25 sure ResultBuffer points to a buffer with size equal or greater than ((AsciiStrSize (Buffer))
26 in bytes.
27
28 @param[in] Buffer The pointer to a percent-encoded URI component.
29 @param[in] BufferLength Length of Buffer in bytes.
30 @param[out] ResultBuffer Point to the buffer to store the decode result.
31 @param[out] ResultLength Length of decoded string in ResultBuffer in bytes.
32
33 @retval EFI_SUCCESS Successfully decoded the URI.
34 @retval EFI_INVALID_PARAMETER Buffer is not a valid percent-encoded string.
35
36 **/
37 EFI_STATUS
38 EFIAPI
39 UriPercentDecode (
40 IN CHAR8 *Buffer,
41 IN UINT32 BufferLength,
42 OUT CHAR8 *ResultBuffer,
43 OUT UINT32 *ResultLength
44 )
45 {
46 UINTN Index;
47 UINTN Offset;
48 CHAR8 HexStr[3];
49
50 if (Buffer == NULL || BufferLength == 0 || ResultBuffer == NULL) {
51 return EFI_INVALID_PARAMETER;
52 }
53
54 Index = 0;
55 Offset = 0;
56 HexStr[2] = '\0';
57 while (Index < BufferLength) {
58 if (Buffer[Index] == '%') {
59 if (Index + 1 >= BufferLength || Index + 2 >= BufferLength ||
60 !NET_IS_HEX_CHAR (Buffer[Index+1]) || !NET_IS_HEX_CHAR (Buffer[Index+2])) {
61 return EFI_INVALID_PARAMETER;
62 }
63 HexStr[0] = Buffer[Index+1];
64 HexStr[1] = Buffer[Index+2];
65 ResultBuffer[Offset] = (CHAR8) AsciiStrHexToUintn (HexStr);
66 Index += 3;
67 } else {
68 ResultBuffer[Offset] = Buffer[Index];
69 Index++;
70 }
71 Offset++;
72 }
73
74 *ResultLength = (UINT32) Offset;
75
76 return EFI_SUCCESS;
77 }
78
79 /**
80 This function return the updated state according to the input state and next character of
81 the authority.
82
83 @param[in] Char Next character.
84 @param[in] State Current value of the parser state machine.
85 @param[in] IsRightBracket TRUE if there is an sign ']' in the authority component and
86 indicates the next part is ':' before Port.
87
88 @return Updated state value.
89 **/
90 HTTP_URL_PARSE_STATE
91 NetHttpParseAuthorityChar (
92 IN CHAR8 Char,
93 IN HTTP_URL_PARSE_STATE State,
94 IN BOOLEAN *IsRightBracket
95 )
96 {
97
98 //
99 // RFC 3986:
100 // The authority component is preceded by a double slash ("//") and is
101 // terminated by the next slash ("/"), question mark ("?"), or number
102 // sign ("#") character, or by the end of the URI.
103 //
104 if (Char == ' ' || Char == '\r' || Char == '\n') {
105 return UrlParserStateMax;
106 }
107
108 //
109 // authority = [ userinfo "@" ] host [ ":" port ]
110 //
111 switch (State) {
112 case UrlParserUserInfo:
113 if (Char == '@') {
114 return UrlParserHostStart;
115 }
116 break;
117
118 case UrlParserHost:
119 case UrlParserHostStart:
120 if (Char == '[') {
121 return UrlParserHostIpv6;
122 }
123
124 if (Char == ':') {
125 return UrlParserPortStart;
126 }
127
128 return UrlParserHost;
129
130 case UrlParserHostIpv6:
131 if (Char == ']') {
132 *IsRightBracket = TRUE;
133 }
134
135 if (Char == ':' && *IsRightBracket) {
136 return UrlParserPortStart;
137 }
138 return UrlParserHostIpv6;
139
140 case UrlParserPort:
141 case UrlParserPortStart:
142 return UrlParserPort;
143
144 default:
145 break;
146 }
147
148 return State;
149 }
150
151 /**
152 This function parse the authority component of the input URL and update the parser.
153
154 @param[in] Url The pointer to a HTTP URL string.
155 @param[in] FoundAt TRUE if there is an at sign ('@') in the authority component.
156 @param[in, out] UrlParser Pointer to the buffer of the parse result.
157
158 @retval EFI_SUCCESS Successfully parse the authority.
159 @retval EFI_INVALID_PARAMETER The Url is invalid to parse the authority component.
160
161 **/
162 EFI_STATUS
163 NetHttpParseAuthority (
164 IN CHAR8 *Url,
165 IN BOOLEAN FoundAt,
166 IN OUT HTTP_URL_PARSER *UrlParser
167 )
168 {
169 CHAR8 *Char;
170 CHAR8 *Authority;
171 UINT32 Length;
172 HTTP_URL_PARSE_STATE State;
173 UINT32 Field;
174 UINT32 OldField;
175 BOOLEAN IsrightBracket;
176
177 ASSERT ((UrlParser->FieldBitMap & BIT (HTTP_URI_FIELD_AUTHORITY)) != 0);
178
179 //
180 // authority = [ userinfo "@" ] host [ ":" port ]
181 //
182 if (FoundAt) {
183 State = UrlParserUserInfo;
184 } else {
185 State = UrlParserHost;
186 }
187
188 IsrightBracket = FALSE;
189 Field = HTTP_URI_FIELD_MAX;
190 OldField = Field;
191 Authority = Url + UrlParser->FieldData[HTTP_URI_FIELD_AUTHORITY].Offset;
192 Length = UrlParser->FieldData[HTTP_URI_FIELD_AUTHORITY].Length;
193 for (Char = Authority; Char < Authority + Length; Char++) {
194 State = NetHttpParseAuthorityChar (*Char, State, &IsrightBracket);
195 switch (State) {
196 case UrlParserStateMax:
197 return EFI_INVALID_PARAMETER;
198
199 case UrlParserHostStart:
200 case UrlParserPortStart:
201 continue;
202
203 case UrlParserUserInfo:
204 Field = HTTP_URI_FIELD_USERINFO;
205 break;
206
207 case UrlParserHost:
208 Field = HTTP_URI_FIELD_HOST;
209 break;
210
211 case UrlParserHostIpv6:
212 Field = HTTP_URI_FIELD_HOST;
213 break;
214
215 case UrlParserPort:
216 Field = HTTP_URI_FIELD_PORT;
217 break;
218
219 default:
220 ASSERT (FALSE);
221 }
222
223 //
224 // Field not changed, count the length.
225 //
226 ASSERT (Field < HTTP_URI_FIELD_MAX);
227 if (Field == OldField) {
228 UrlParser->FieldData[Field].Length++;
229 continue;
230 }
231
232 //
233 // New field start
234 //
235 UrlParser->FieldBitMap |= BIT (Field);
236 UrlParser->FieldData[Field].Offset = (UINT32) (Char - Url);
237 UrlParser->FieldData[Field].Length = 1;
238 OldField = Field;
239 }
240
241 return EFI_SUCCESS;
242 }
243
244 /**
245 This function return the updated state according to the input state and next character of a URL.
246
247 @param[in] Char Next character.
248 @param[in] State Current value of the parser state machine.
249
250 @return Updated state value.
251
252 **/
253 HTTP_URL_PARSE_STATE
254 NetHttpParseUrlChar (
255 IN CHAR8 Char,
256 IN HTTP_URL_PARSE_STATE State
257 )
258 {
259 if (Char == ' ' || Char == '\r' || Char == '\n') {
260 return UrlParserStateMax;
261 }
262
263 //
264 // http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
265 //
266 // Request-URI = "*" | absolute-URI | path-absolute | authority
267 //
268 // absolute-URI = scheme ":" hier-part [ "?" query ]
269 // path-absolute = "/" [ segment-nz *( "/" segment ) ]
270 // authority = [ userinfo "@" ] host [ ":" port ]
271 //
272 switch (State) {
273 case UrlParserUrlStart:
274 if (Char == '*' || Char == '/') {
275 return UrlParserPath;
276 }
277 return UrlParserScheme;
278
279 case UrlParserScheme:
280 if (Char == ':') {
281 return UrlParserSchemeColon;
282 }
283 break;
284
285 case UrlParserSchemeColon:
286 if (Char == '/') {
287 return UrlParserSchemeColonSlash;
288 }
289 break;
290
291 case UrlParserSchemeColonSlash:
292 if (Char == '/') {
293 return UrlParserSchemeColonSlashSlash;
294 }
295 break;
296
297 case UrlParserAtInAuthority:
298 if (Char == '@') {
299 return UrlParserStateMax;
300 }
301
302 case UrlParserAuthority:
303 case UrlParserSchemeColonSlashSlash:
304 if (Char == '@') {
305 return UrlParserAtInAuthority;
306 }
307 if (Char == '/') {
308 return UrlParserPath;
309 }
310 if (Char == '?') {
311 return UrlParserQueryStart;
312 }
313 if (Char == '#') {
314 return UrlParserFragmentStart;
315 }
316 return UrlParserAuthority;
317
318 case UrlParserPath:
319 if (Char == '?') {
320 return UrlParserQueryStart;
321 }
322 if (Char == '#') {
323 return UrlParserFragmentStart;
324 }
325 break;
326
327 case UrlParserQuery:
328 case UrlParserQueryStart:
329 if (Char == '#') {
330 return UrlParserFragmentStart;
331 }
332 return UrlParserQuery;
333
334 case UrlParserFragmentStart:
335 return UrlParserFragment;
336
337 default:
338 break;
339 }
340
341 return State;
342 }
343 /**
344 Create a URL parser for the input URL string.
345
346 This function will parse and dereference the input HTTP URL into it components. The original
347 content of the URL won't be modified and the result will be returned in UrlParser, which can
348 be used in other functions like NetHttpUrlGetHostName().
349
350 @param[in] Url The pointer to a HTTP URL string.
351 @param[in] Length Length of Url in bytes.
352 @param[in] IsConnectMethod Whether the Url is used in HTTP CONNECT method or not.
353 @param[out] UrlParser Pointer to the returned buffer to store the parse result.
354
355 @retval EFI_SUCCESS Successfully dereferenced the HTTP URL.
356 @retval EFI_INVALID_PARAMETER UrlParser is NULL or Url is not a valid HTTP URL.
357 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
358
359 **/
360 EFI_STATUS
361 EFIAPI
362 HttpParseUrl (
363 IN CHAR8 *Url,
364 IN UINT32 Length,
365 IN BOOLEAN IsConnectMethod,
366 OUT VOID **UrlParser
367 )
368 {
369 HTTP_URL_PARSE_STATE State;
370 CHAR8 *Char;
371 UINT32 Field;
372 UINT32 OldField;
373 BOOLEAN FoundAt;
374 EFI_STATUS Status;
375 HTTP_URL_PARSER *Parser;
376
377 Parser = NULL;
378
379 if (Url == NULL || Length == 0 || UrlParser == NULL) {
380 return EFI_INVALID_PARAMETER;
381 }
382
383 Parser = AllocateZeroPool (sizeof (HTTP_URL_PARSER));
384 if (Parser == NULL) {
385 return EFI_OUT_OF_RESOURCES;
386 }
387
388 if (IsConnectMethod) {
389 //
390 // According to RFC 2616, the authority form is only used by the CONNECT method.
391 //
392 State = UrlParserAuthority;
393 } else {
394 State = UrlParserUrlStart;
395 }
396
397 Field = HTTP_URI_FIELD_MAX;
398 OldField = Field;
399 FoundAt = FALSE;
400 for (Char = Url; Char < Url + Length; Char++) {
401 //
402 // Update state machine according to next char.
403 //
404 State = NetHttpParseUrlChar (*Char, State);
405
406 switch (State) {
407 case UrlParserStateMax:
408 FreePool (Parser);
409 return EFI_INVALID_PARAMETER;
410
411 case UrlParserSchemeColon:
412 case UrlParserSchemeColonSlash:
413 case UrlParserSchemeColonSlashSlash:
414 case UrlParserQueryStart:
415 case UrlParserFragmentStart:
416 //
417 // Skip all the delimiting char: "://" "?" "@"
418 //
419 continue;
420
421 case UrlParserScheme:
422 Field = HTTP_URI_FIELD_SCHEME;
423 break;
424
425 case UrlParserAtInAuthority:
426 FoundAt = TRUE;
427 case UrlParserAuthority:
428 Field = HTTP_URI_FIELD_AUTHORITY;
429 break;
430
431 case UrlParserPath:
432 Field = HTTP_URI_FIELD_PATH;
433 break;
434
435 case UrlParserQuery:
436 Field = HTTP_URI_FIELD_QUERY;
437 break;
438
439 case UrlParserFragment:
440 Field = HTTP_URI_FIELD_FRAGMENT;
441 break;
442
443 default:
444 ASSERT (FALSE);
445 }
446
447 //
448 // Field not changed, count the length.
449 //
450 ASSERT (Field < HTTP_URI_FIELD_MAX);
451 if (Field == OldField) {
452 Parser->FieldData[Field].Length++;
453 continue;
454 }
455
456 //
457 // New field start
458 //
459 Parser->FieldBitMap |= BIT (Field);
460 Parser->FieldData[Field].Offset = (UINT32) (Char - Url);
461 Parser->FieldData[Field].Length = 1;
462 OldField = Field;
463 }
464
465 //
466 // If has authority component, continue to parse the username, host and port.
467 //
468 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_AUTHORITY)) != 0) {
469 Status = NetHttpParseAuthority (Url, FoundAt, Parser);
470 if (EFI_ERROR (Status)) {
471 FreePool (Parser);
472 return Status;
473 }
474 }
475
476 *UrlParser = Parser;
477 return EFI_SUCCESS;
478 }
479
480 /**
481 Get the Hostname from a HTTP URL.
482
483 This function will return the HostName according to the Url and previous parse result ,and
484 it is the caller's responsibility to free the buffer returned in *HostName.
485
486 @param[in] Url The pointer to a HTTP URL string.
487 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
488 @param[out] HostName Pointer to a buffer to store the HostName.
489
490 @retval EFI_SUCCESS Successfully get the required component.
491 @retval EFI_INVALID_PARAMETER Uri is NULL or HostName is NULL or UrlParser is invalid.
492 @retval EFI_NOT_FOUND No hostName component in the URL.
493 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
494
495 **/
496 EFI_STATUS
497 EFIAPI
498 HttpUrlGetHostName (
499 IN CHAR8 *Url,
500 IN VOID *UrlParser,
501 OUT CHAR8 **HostName
502 )
503 {
504 CHAR8 *Name;
505 EFI_STATUS Status;
506 UINT32 ResultLength;
507 HTTP_URL_PARSER *Parser;
508
509 if (Url == NULL || UrlParser == NULL || HostName == NULL) {
510 return EFI_INVALID_PARAMETER;
511 }
512
513 Parser = (HTTP_URL_PARSER *) UrlParser;
514
515 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_HOST)) == 0) {
516 return EFI_NOT_FOUND;
517 }
518
519 Name = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_HOST].Length + 1);
520 if (Name == NULL) {
521 return EFI_OUT_OF_RESOURCES;
522 }
523
524 Status = UriPercentDecode (
525 Url + Parser->FieldData[HTTP_URI_FIELD_HOST].Offset,
526 Parser->FieldData[HTTP_URI_FIELD_HOST].Length,
527 Name,
528 &ResultLength
529 );
530 if (EFI_ERROR (Status)) {
531 FreePool (Name);
532 return Status;
533 }
534
535 Name[ResultLength] = '\0';
536 *HostName = Name;
537 return EFI_SUCCESS;
538 }
539
540
541 /**
542 Get the IPv4 address from a HTTP URL.
543
544 This function will return the IPv4 address according to the Url and previous parse result.
545
546 @param[in] Url The pointer to a HTTP URL string.
547 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
548 @param[out] Ip4Address Pointer to a buffer to store the IP address.
549
550 @retval EFI_SUCCESS Successfully get the required component.
551 @retval EFI_INVALID_PARAMETER Uri is NULL or Ip4Address is NULL or UrlParser is invalid.
552 @retval EFI_NOT_FOUND No IPv4 address component in the URL.
553 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
554
555 **/
556 EFI_STATUS
557 EFIAPI
558 HttpUrlGetIp4 (
559 IN CHAR8 *Url,
560 IN VOID *UrlParser,
561 OUT EFI_IPv4_ADDRESS *Ip4Address
562 )
563 {
564 CHAR8 *Ip4String;
565 EFI_STATUS Status;
566 UINT32 ResultLength;
567 HTTP_URL_PARSER *Parser;
568
569 if (Url == NULL || UrlParser == NULL || Ip4Address == NULL) {
570 return EFI_INVALID_PARAMETER;
571 }
572
573 Parser = (HTTP_URL_PARSER *) UrlParser;
574
575 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_HOST)) == 0) {
576 return EFI_NOT_FOUND;
577 }
578
579 Ip4String = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_HOST].Length + 1);
580 if (Ip4String == NULL) {
581 return EFI_OUT_OF_RESOURCES;
582 }
583
584 Status = UriPercentDecode (
585 Url + Parser->FieldData[HTTP_URI_FIELD_HOST].Offset,
586 Parser->FieldData[HTTP_URI_FIELD_HOST].Length,
587 Ip4String,
588 &ResultLength
589 );
590 if (EFI_ERROR (Status)) {
591 FreePool (Ip4String);
592 return Status;
593 }
594
595 Ip4String[ResultLength] = '\0';
596 Status = NetLibAsciiStrToIp4 (Ip4String, Ip4Address);
597 FreePool (Ip4String);
598
599 return Status;
600 }
601
602 /**
603 Get the IPv6 address from a HTTP URL.
604
605 This function will return the IPv6 address according to the Url and previous parse result.
606
607 @param[in] Url The pointer to a HTTP URL string.
608 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
609 @param[out] Ip6Address Pointer to a buffer to store the IP address.
610
611 @retval EFI_SUCCESS Successfully get the required component.
612 @retval EFI_INVALID_PARAMETER Uri is NULL or Ip6Address is NULL or UrlParser is invalid.
613 @retval EFI_NOT_FOUND No IPv6 address component in the URL.
614 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
615
616 **/
617 EFI_STATUS
618 EFIAPI
619 HttpUrlGetIp6 (
620 IN CHAR8 *Url,
621 IN VOID *UrlParser,
622 OUT EFI_IPv6_ADDRESS *Ip6Address
623 )
624 {
625 CHAR8 *Ip6String;
626 CHAR8 *Ptr;
627 UINT32 Length;
628 EFI_STATUS Status;
629 UINT32 ResultLength;
630 HTTP_URL_PARSER *Parser;
631
632 if (Url == NULL || UrlParser == NULL || Ip6Address == NULL) {
633 return EFI_INVALID_PARAMETER;
634 }
635
636 Parser = (HTTP_URL_PARSER *) UrlParser;
637
638 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_HOST)) == 0) {
639 return EFI_NOT_FOUND;
640 }
641
642 //
643 // IP-literal = "[" ( IPv6address / IPvFuture ) "]"
644 //
645 Length = Parser->FieldData[HTTP_URI_FIELD_HOST].Length;
646 if (Length < 2) {
647 return EFI_INVALID_PARAMETER;
648 }
649
650 Ptr = Url + Parser->FieldData[HTTP_URI_FIELD_HOST].Offset;
651 if ((Ptr[0] != '[') || (Ptr[Length - 1] != ']')) {
652 return EFI_INVALID_PARAMETER;
653 }
654
655 Ip6String = AllocatePool (Length);
656 if (Ip6String == NULL) {
657 return EFI_OUT_OF_RESOURCES;
658 }
659
660 Status = UriPercentDecode (
661 Ptr + 1,
662 Length - 2,
663 Ip6String,
664 &ResultLength
665 );
666 if (EFI_ERROR (Status)) {
667 FreePool (Ip6String);
668 return Status;
669 }
670
671 Ip6String[ResultLength] = '\0';
672 Status = NetLibAsciiStrToIp6 (Ip6String, Ip6Address);
673 FreePool (Ip6String);
674
675 return Status;
676 }
677
678 /**
679 Get the port number from a HTTP URL.
680
681 This function will return the port number according to the Url and previous parse result.
682
683 @param[in] Url The pointer to a HTTP URL string.
684 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
685 @param[out] Port Pointer to a buffer to store the port number.
686
687 @retval EFI_SUCCESS Successfully get the required component.
688 @retval EFI_INVALID_PARAMETER Uri is NULL or Port is NULL or UrlParser is invalid.
689 @retval EFI_NOT_FOUND No port number in the URL.
690 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
691
692 **/
693 EFI_STATUS
694 EFIAPI
695 HttpUrlGetPort (
696 IN CHAR8 *Url,
697 IN VOID *UrlParser,
698 OUT UINT16 *Port
699 )
700 {
701 CHAR8 *PortString;
702 EFI_STATUS Status;
703 UINTN Index;
704 UINTN Data;
705 UINT32 ResultLength;
706 HTTP_URL_PARSER *Parser;
707
708 if (Url == NULL || UrlParser == NULL || Port == NULL) {
709 return EFI_INVALID_PARAMETER;
710 }
711
712 *Port = 0;
713 Index = 0;
714
715 Parser = (HTTP_URL_PARSER *) UrlParser;
716
717 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_PORT)) == 0) {
718 return EFI_NOT_FOUND;
719 }
720
721 PortString = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_PORT].Length + 1);
722 if (PortString == NULL) {
723 return EFI_OUT_OF_RESOURCES;
724 }
725
726 Status = UriPercentDecode (
727 Url + Parser->FieldData[HTTP_URI_FIELD_PORT].Offset,
728 Parser->FieldData[HTTP_URI_FIELD_PORT].Length,
729 PortString,
730 &ResultLength
731 );
732 if (EFI_ERROR (Status)) {
733 goto ON_EXIT;
734 }
735
736 PortString[ResultLength] = '\0';
737
738 while (Index < ResultLength) {
739 if (!NET_IS_DIGIT (PortString[Index])) {
740 Status = EFI_INVALID_PARAMETER;
741 goto ON_EXIT;
742 }
743 Index ++;
744 }
745
746 Status = AsciiStrDecimalToUintnS (Url + Parser->FieldData[HTTP_URI_FIELD_PORT].Offset, (CHAR8 **) NULL, &Data);
747
748 if (Data > HTTP_URI_PORT_MAX_NUM) {
749 Status = EFI_INVALID_PARAMETER;
750 goto ON_EXIT;
751 }
752
753 *Port = (UINT16) Data;
754
755 ON_EXIT:
756 FreePool (PortString);
757 return Status;
758 }
759
760 /**
761 Get the Path from a HTTP URL.
762
763 This function will return the Path according to the Url and previous parse result,and
764 it is the caller's responsibility to free the buffer returned in *Path.
765
766 @param[in] Url The pointer to a HTTP URL string.
767 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
768 @param[out] Path Pointer to a buffer to store the Path.
769
770 @retval EFI_SUCCESS Successfully get the required component.
771 @retval EFI_INVALID_PARAMETER Uri is NULL or HostName is NULL or UrlParser is invalid.
772 @retval EFI_NOT_FOUND No hostName component in the URL.
773 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
774
775 **/
776 EFI_STATUS
777 EFIAPI
778 HttpUrlGetPath (
779 IN CHAR8 *Url,
780 IN VOID *UrlParser,
781 OUT CHAR8 **Path
782 )
783 {
784 CHAR8 *PathStr;
785 EFI_STATUS Status;
786 UINT32 ResultLength;
787 HTTP_URL_PARSER *Parser;
788
789 if (Url == NULL || UrlParser == NULL || Path == NULL) {
790 return EFI_INVALID_PARAMETER;
791 }
792
793 Parser = (HTTP_URL_PARSER *) UrlParser;
794
795 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_PATH)) == 0) {
796 return EFI_NOT_FOUND;
797 }
798
799 PathStr = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_PATH].Length + 1);
800 if (PathStr == NULL) {
801 return EFI_OUT_OF_RESOURCES;
802 }
803
804 Status = UriPercentDecode (
805 Url + Parser->FieldData[HTTP_URI_FIELD_PATH].Offset,
806 Parser->FieldData[HTTP_URI_FIELD_PATH].Length,
807 PathStr,
808 &ResultLength
809 );
810 if (EFI_ERROR (Status)) {
811 FreePool (PathStr);
812 return Status;
813 }
814
815 PathStr[ResultLength] = '\0';
816 *Path = PathStr;
817 return EFI_SUCCESS;
818 }
819
820 /**
821 Release the resource of the URL parser.
822
823 @param[in] UrlParser Pointer to the parser.
824
825 **/
826 VOID
827 EFIAPI
828 HttpUrlFreeParser (
829 IN VOID *UrlParser
830 )
831 {
832 FreePool (UrlParser);
833 }
834
835 /**
836 Find a specified header field according to the field name.
837
838 @param[in] HeaderCount Number of HTTP header structures in Headers list.
839 @param[in] Headers Array containing list of HTTP headers.
840 @param[in] FieldName Null terminated string which describes a field name.
841
842 @return Pointer to the found header or NULL.
843
844 **/
845 EFI_HTTP_HEADER *
846 EFIAPI
847 HttpFindHeader (
848 IN UINTN HeaderCount,
849 IN EFI_HTTP_HEADER *Headers,
850 IN CHAR8 *FieldName
851 )
852 {
853 UINTN Index;
854
855 if (HeaderCount == 0 || Headers == NULL || FieldName == NULL) {
856 return NULL;
857 }
858
859 for (Index = 0; Index < HeaderCount; Index++){
860 //
861 // Field names are case-insensitive (RFC 2616).
862 //
863 if (AsciiStriCmp (Headers[Index].FieldName, FieldName) == 0) {
864 return &Headers[Index];
865 }
866 }
867 return NULL;
868 }
869
870 typedef enum {
871 BodyParserBodyStart,
872 BodyParserBodyIdentity,
873 BodyParserChunkSizeStart,
874 BodyParserChunkSize,
875 BodyParserChunkSizeEndCR,
876 BodyParserChunkExtStart,
877 BodyParserChunkDataStart,
878 BodyParserChunkDataEnd,
879 BodyParserChunkDataEndCR,
880 BodyParserTrailer,
881 BodyParserLastCRLF,
882 BodyParserLastCRLFEnd,
883 BodyParserComplete,
884 BodyParserStateMax
885 } HTTP_BODY_PARSE_STATE;
886
887 typedef struct {
888 BOOLEAN IgnoreBody; // "MUST NOT" include a message-body
889 BOOLEAN IsChunked; // "chunked" transfer-coding.
890 BOOLEAN ContentLengthIsValid;
891 UINTN ContentLength; // Entity length (not the message-body length), invalid until ContentLengthIsValid is TRUE
892
893 HTTP_BODY_PARSER_CALLBACK Callback;
894 VOID *Context;
895 UINTN ParsedBodyLength;
896 HTTP_BODY_PARSE_STATE State;
897 UINTN CurrentChunkSize;
898 UINTN CurrentChunkParsedSize;
899 } HTTP_BODY_PARSER;
900
901 /**
902 Convert an hexadecimal char to a value of type UINTN.
903
904 @param[in] Char Ascii character.
905
906 @return Value translated from Char.
907
908 **/
909 UINTN
910 HttpIoHexCharToUintn (
911 IN CHAR8 Char
912 )
913 {
914 if (Char >= '0' && Char <= '9') {
915 return Char - '0';
916 }
917
918 return (10 + AsciiCharToUpper (Char) - 'A');
919 }
920
921 /**
922 Get the value of the content length if there is a "Content-Length" header.
923
924 @param[in] HeaderCount Number of HTTP header structures in Headers.
925 @param[in] Headers Array containing list of HTTP headers.
926 @param[out] ContentLength Pointer to save the value of the content length.
927
928 @retval EFI_SUCCESS Successfully get the content length.
929 @retval EFI_NOT_FOUND No "Content-Length" header in the Headers.
930
931 **/
932 EFI_STATUS
933 HttpIoParseContentLengthHeader (
934 IN UINTN HeaderCount,
935 IN EFI_HTTP_HEADER *Headers,
936 OUT UINTN *ContentLength
937 )
938 {
939 EFI_HTTP_HEADER *Header;
940
941 Header = HttpFindHeader (HeaderCount, Headers, HTTP_HEADER_CONTENT_LENGTH);
942 if (Header == NULL) {
943 return EFI_NOT_FOUND;
944 }
945
946 return AsciiStrDecimalToUintnS (Header->FieldValue, (CHAR8 **) NULL, ContentLength);
947 }
948
949 /**
950
951 Check whether the HTTP message is using the "chunked" transfer-coding.
952
953 @param[in] HeaderCount Number of HTTP header structures in Headers.
954 @param[in] Headers Array containing list of HTTP headers.
955
956 @return The message is "chunked" transfer-coding (TRUE) or not (FALSE).
957
958 **/
959 BOOLEAN
960 HttpIoIsChunked (
961 IN UINTN HeaderCount,
962 IN EFI_HTTP_HEADER *Headers
963 )
964 {
965 EFI_HTTP_HEADER *Header;
966
967
968 Header = HttpFindHeader (HeaderCount, Headers, HTTP_HEADER_TRANSFER_ENCODING);
969 if (Header == NULL) {
970 return FALSE;
971 }
972
973 if (AsciiStriCmp (Header->FieldValue, "identity") != 0) {
974 return TRUE;
975 }
976
977 return FALSE;
978 }
979
980 /**
981 Check whether the HTTP message should have a message-body.
982
983 @param[in] Method The HTTP method (e.g. GET, POST) for this HTTP message.
984 @param[in] StatusCode Response status code returned by the remote host.
985
986 @return The message should have a message-body (FALSE) or not (TRUE).
987
988 **/
989 BOOLEAN
990 HttpIoNoMessageBody (
991 IN EFI_HTTP_METHOD Method,
992 IN EFI_HTTP_STATUS_CODE StatusCode
993 )
994 {
995 //
996 // RFC 2616:
997 // All responses to the HEAD request method
998 // MUST NOT include a message-body, even though the presence of entity-
999 // header fields might lead one to believe they do. All 1xx
1000 // (informational), 204 (no content), and 304 (not modified) responses
1001 // MUST NOT include a message-body. All other responses do include a
1002 // message-body, although it MAY be of zero length.
1003 //
1004 if (Method == HttpMethodHead) {
1005 return TRUE;
1006 }
1007
1008 if ((StatusCode == HTTP_STATUS_100_CONTINUE) ||
1009 (StatusCode == HTTP_STATUS_101_SWITCHING_PROTOCOLS) ||
1010 (StatusCode == HTTP_STATUS_204_NO_CONTENT) ||
1011 (StatusCode == HTTP_STATUS_304_NOT_MODIFIED))
1012 {
1013 return TRUE;
1014 }
1015
1016 return FALSE;
1017 }
1018
1019 /**
1020 Initialize a HTTP message-body parser.
1021
1022 This function will create and initialize a HTTP message parser according to caller provided HTTP message
1023 header information. It is the caller's responsibility to free the buffer returned in *UrlParser by HttpFreeMsgParser().
1024
1025 @param[in] Method The HTTP method (e.g. GET, POST) for this HTTP message.
1026 @param[in] StatusCode Response status code returned by the remote host.
1027 @param[in] HeaderCount Number of HTTP header structures in Headers.
1028 @param[in] Headers Array containing list of HTTP headers.
1029 @param[in] Callback Callback function that is invoked when parsing the HTTP message-body,
1030 set to NULL to ignore all events.
1031 @param[in] Context Pointer to the context that will be passed to Callback.
1032 @param[out] MsgParser Pointer to the returned buffer to store the message parser.
1033
1034 @retval EFI_SUCCESS Successfully initialized the parser.
1035 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
1036 @retval EFI_INVALID_PARAMETER MsgParser is NULL or HeaderCount is not NULL but Headers is NULL.
1037 @retval Others Failed to initialize the parser.
1038
1039 **/
1040 EFI_STATUS
1041 EFIAPI
1042 HttpInitMsgParser (
1043 IN EFI_HTTP_METHOD Method,
1044 IN EFI_HTTP_STATUS_CODE StatusCode,
1045 IN UINTN HeaderCount,
1046 IN EFI_HTTP_HEADER *Headers,
1047 IN HTTP_BODY_PARSER_CALLBACK Callback,
1048 IN VOID *Context,
1049 OUT VOID **MsgParser
1050 )
1051 {
1052 EFI_STATUS Status;
1053 HTTP_BODY_PARSER *Parser;
1054
1055 if (HeaderCount != 0 && Headers == NULL) {
1056 return EFI_INVALID_PARAMETER;
1057 }
1058
1059 if (MsgParser == NULL) {
1060 return EFI_INVALID_PARAMETER;
1061 }
1062
1063 Parser = AllocateZeroPool (sizeof (HTTP_BODY_PARSER));
1064 if (Parser == NULL) {
1065 return EFI_OUT_OF_RESOURCES;
1066 }
1067
1068 Parser->State = BodyParserBodyStart;
1069
1070 //
1071 // Determine the message length according to RFC 2616.
1072 // 1. Check whether the message "MUST NOT" have a message-body.
1073 //
1074 Parser->IgnoreBody = HttpIoNoMessageBody (Method, StatusCode);
1075 //
1076 // 2. Check whether the message using "chunked" transfer-coding.
1077 //
1078 Parser->IsChunked = HttpIoIsChunked (HeaderCount, Headers);
1079 //
1080 // 3. Check whether the message has a Content-Length header field.
1081 //
1082 Status = HttpIoParseContentLengthHeader (HeaderCount, Headers, &Parser->ContentLength);
1083 if (!EFI_ERROR (Status)) {
1084 Parser->ContentLengthIsValid = TRUE;
1085 }
1086 //
1087 // 4. Range header is not supported now, so we won't meet media type "multipart/byteranges".
1088 // 5. By server closing the connection
1089 //
1090
1091 //
1092 // Set state to skip body parser if the message shouldn't have a message body.
1093 //
1094 if (Parser->IgnoreBody) {
1095 Parser->State = BodyParserComplete;
1096 } else {
1097 Parser->Callback = Callback;
1098 Parser->Context = Context;
1099 }
1100
1101 *MsgParser = Parser;
1102 return EFI_SUCCESS;
1103 }
1104
1105 /**
1106 Parse message body.
1107
1108 Parse BodyLength of message-body. This function can be called repeatedly to parse the message-body partially.
1109
1110 @param[in, out] MsgParser Pointer to the message parser.
1111 @param[in] BodyLength Length in bytes of the Body.
1112 @param[in] Body Pointer to the buffer of the message-body to be parsed.
1113
1114 @retval EFI_SUCCESS Successfully parse the message-body.
1115 @retval EFI_INVALID_PARAMETER MsgParser is NULL or Body is NULL or BodyLength is 0.
1116 @retval EFI_ABORTED Operation aborted.
1117 @retval Other Error happened while parsing message body.
1118
1119 **/
1120 EFI_STATUS
1121 EFIAPI
1122 HttpParseMessageBody (
1123 IN OUT VOID *MsgParser,
1124 IN UINTN BodyLength,
1125 IN CHAR8 *Body
1126 )
1127 {
1128 CHAR8 *Char;
1129 UINTN RemainderLengthInThis;
1130 UINTN LengthForCallback;
1131 EFI_STATUS Status;
1132 HTTP_BODY_PARSER *Parser;
1133
1134 if (BodyLength == 0 || Body == NULL) {
1135 return EFI_INVALID_PARAMETER;
1136 }
1137
1138 if (MsgParser == NULL) {
1139 return EFI_INVALID_PARAMETER;
1140 }
1141
1142 Parser = (HTTP_BODY_PARSER *) MsgParser;
1143
1144 if (Parser->IgnoreBody) {
1145 Parser->State = BodyParserComplete;
1146 if (Parser->Callback != NULL) {
1147 Status = Parser->Callback (
1148 BodyParseEventOnComplete,
1149 Body,
1150 0,
1151 Parser->Context
1152 );
1153 if (EFI_ERROR (Status)) {
1154 return Status;
1155 }
1156 }
1157 return EFI_SUCCESS;
1158 }
1159
1160 if (Parser->State == BodyParserBodyStart) {
1161 Parser->ParsedBodyLength = 0;
1162 if (Parser->IsChunked) {
1163 Parser->State = BodyParserChunkSizeStart;
1164 } else {
1165 Parser->State = BodyParserBodyIdentity;
1166 }
1167 }
1168
1169 //
1170 // The message body might be truncated in anywhere, so we need to parse is byte-by-byte.
1171 //
1172 for (Char = Body; Char < Body + BodyLength; ) {
1173
1174 switch (Parser->State) {
1175 case BodyParserStateMax:
1176 return EFI_ABORTED;
1177
1178 case BodyParserBodyIdentity:
1179 //
1180 // Identity transfer-coding, just notify user to save the body data.
1181 //
1182 if (Parser->Callback != NULL) {
1183 Status = Parser->Callback (
1184 BodyParseEventOnData,
1185 Char,
1186 MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength),
1187 Parser->Context
1188 );
1189 if (EFI_ERROR (Status)) {
1190 return Status;
1191 }
1192 }
1193 Char += MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength);
1194 Parser->ParsedBodyLength += MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength);
1195 if (Parser->ParsedBodyLength == Parser->ContentLength) {
1196 Parser->State = BodyParserComplete;
1197 if (Parser->Callback != NULL) {
1198 Status = Parser->Callback (
1199 BodyParseEventOnComplete,
1200 Char,
1201 0,
1202 Parser->Context
1203 );
1204 if (EFI_ERROR (Status)) {
1205 return Status;
1206 }
1207 }
1208 }
1209 break;
1210
1211 case BodyParserChunkSizeStart:
1212 //
1213 // First byte of chunk-size, the chunk-size might be truncated.
1214 //
1215 Parser->CurrentChunkSize = 0;
1216 Parser->State = BodyParserChunkSize;
1217 case BodyParserChunkSize:
1218 if (!NET_IS_HEX_CHAR (*Char)) {
1219 if (*Char == ';') {
1220 Parser->State = BodyParserChunkExtStart;
1221 Char++;
1222 } else if (*Char == '\r') {
1223 Parser->State = BodyParserChunkSizeEndCR;
1224 Char++;
1225 } else {
1226 Parser->State = BodyParserStateMax;
1227 }
1228 break;
1229 }
1230
1231 if (Parser->CurrentChunkSize > (((~((UINTN) 0)) - 16) / 16)) {
1232 return EFI_INVALID_PARAMETER;
1233 }
1234 Parser->CurrentChunkSize = Parser->CurrentChunkSize * 16 + HttpIoHexCharToUintn (*Char);
1235 Char++;
1236 break;
1237
1238 case BodyParserChunkExtStart:
1239 //
1240 // Ignore all the chunk extensions.
1241 //
1242 if (*Char == '\r') {
1243 Parser->State = BodyParserChunkSizeEndCR;
1244 }
1245 Char++;
1246 break;
1247
1248 case BodyParserChunkSizeEndCR:
1249 if (*Char != '\n') {
1250 Parser->State = BodyParserStateMax;
1251 break;
1252 }
1253 Char++;
1254 if (Parser->CurrentChunkSize == 0) {
1255 //
1256 // The last chunk has been parsed and now assumed the state
1257 // of HttpBodyParse is ParserLastCRLF. So it need to decide
1258 // whether the rest message is trailer or last CRLF in the next round.
1259 //
1260 Parser->ContentLengthIsValid = TRUE;
1261 Parser->State = BodyParserLastCRLF;
1262 break;
1263 }
1264 Parser->State = BodyParserChunkDataStart;
1265 Parser->CurrentChunkParsedSize = 0;
1266 break;
1267
1268 case BodyParserLastCRLF:
1269 //
1270 // Judge the byte is belong to the Last CRLF or trailer, and then
1271 // configure the state of HttpBodyParse to corresponding state.
1272 //
1273 if (*Char == '\r') {
1274 Char++;
1275 Parser->State = BodyParserLastCRLFEnd;
1276 break;
1277 } else {
1278 Parser->State = BodyParserTrailer;
1279 break;
1280 }
1281
1282 case BodyParserLastCRLFEnd:
1283 if (*Char == '\n') {
1284 Parser->State = BodyParserComplete;
1285 Char++;
1286 if (Parser->Callback != NULL) {
1287 Status = Parser->Callback (
1288 BodyParseEventOnComplete,
1289 Char,
1290 0,
1291 Parser->Context
1292 );
1293 if (EFI_ERROR (Status)) {
1294 return Status;
1295 }
1296 }
1297 break;
1298 } else {
1299 Parser->State = BodyParserStateMax;
1300 break;
1301 }
1302
1303 case BodyParserTrailer:
1304 if (*Char == '\r') {
1305 Parser->State = BodyParserChunkSizeEndCR;
1306 }
1307 Char++;
1308 break;
1309
1310 case BodyParserChunkDataStart:
1311 //
1312 // First byte of chunk-data, the chunk data also might be truncated.
1313 //
1314 RemainderLengthInThis = BodyLength - (Char - Body);
1315 LengthForCallback = MIN (Parser->CurrentChunkSize - Parser->CurrentChunkParsedSize, RemainderLengthInThis);
1316 if (Parser->Callback != NULL) {
1317 Status = Parser->Callback (
1318 BodyParseEventOnData,
1319 Char,
1320 LengthForCallback,
1321 Parser->Context
1322 );
1323 if (EFI_ERROR (Status)) {
1324 return Status;
1325 }
1326 }
1327 Char += LengthForCallback;
1328 Parser->ContentLength += LengthForCallback;
1329 Parser->CurrentChunkParsedSize += LengthForCallback;
1330 if (Parser->CurrentChunkParsedSize == Parser->CurrentChunkSize) {
1331 Parser->State = BodyParserChunkDataEnd;
1332 }
1333 break;
1334
1335 case BodyParserChunkDataEnd:
1336 if (*Char == '\r') {
1337 Parser->State = BodyParserChunkDataEndCR;
1338 } else {
1339 Parser->State = BodyParserStateMax;
1340 }
1341 Char++;
1342 break;
1343
1344 case BodyParserChunkDataEndCR:
1345 if (*Char != '\n') {
1346 Parser->State = BodyParserStateMax;
1347 break;
1348 }
1349 Char++;
1350 Parser->State = BodyParserChunkSizeStart;
1351 break;
1352
1353 default:
1354 break;
1355 }
1356
1357 }
1358
1359 if (Parser->State == BodyParserStateMax) {
1360 return EFI_ABORTED;
1361 }
1362
1363 return EFI_SUCCESS;
1364 }
1365
1366 /**
1367 Check whether the message-body is complete or not.
1368
1369 @param[in] MsgParser Pointer to the message parser.
1370
1371 @retval TRUE Message-body is complete.
1372 @retval FALSE Message-body is not complete.
1373
1374 **/
1375 BOOLEAN
1376 EFIAPI
1377 HttpIsMessageComplete (
1378 IN VOID *MsgParser
1379 )
1380 {
1381 HTTP_BODY_PARSER *Parser;
1382
1383 if (MsgParser == NULL) {
1384 return FALSE;
1385 }
1386
1387 Parser = (HTTP_BODY_PARSER *) MsgParser;
1388
1389 if (Parser->State == BodyParserComplete) {
1390 return TRUE;
1391 }
1392 return FALSE;
1393 }
1394
1395 /**
1396 Get the content length of the entity.
1397
1398 Note that in trunk transfer, the entity length is not valid until the whole message body is received.
1399
1400 @param[in] MsgParser Pointer to the message parser.
1401 @param[out] ContentLength Pointer to store the length of the entity.
1402
1403 @retval EFI_SUCCESS Successfully to get the entity length.
1404 @retval EFI_NOT_READY Entity length is not valid yet.
1405 @retval EFI_INVALID_PARAMETER MsgParser is NULL or ContentLength is NULL.
1406
1407 **/
1408 EFI_STATUS
1409 EFIAPI
1410 HttpGetEntityLength (
1411 IN VOID *MsgParser,
1412 OUT UINTN *ContentLength
1413 )
1414 {
1415 HTTP_BODY_PARSER *Parser;
1416
1417 if (MsgParser == NULL || ContentLength == NULL) {
1418 return EFI_INVALID_PARAMETER;
1419 }
1420
1421 Parser = (HTTP_BODY_PARSER *) MsgParser;
1422
1423 if (!Parser->ContentLengthIsValid) {
1424 return EFI_NOT_READY;
1425 }
1426
1427 *ContentLength = Parser->ContentLength;
1428 return EFI_SUCCESS;
1429 }
1430
1431 /**
1432 Release the resource of the message parser.
1433
1434 @param[in] MsgParser Pointer to the message parser.
1435
1436 **/
1437 VOID
1438 EFIAPI
1439 HttpFreeMsgParser (
1440 IN VOID *MsgParser
1441 )
1442 {
1443 FreePool (MsgParser);
1444 }
1445
1446
1447 /**
1448 Get the next string, which is distinguished by specified separator.
1449
1450 @param[in] String Pointer to the string.
1451 @param[in] Separator Specified separator used to distinguish where is the beginning
1452 of next string.
1453
1454 @return Pointer to the next string.
1455 @return NULL if not find or String is NULL.
1456
1457 **/
1458 CHAR8 *
1459 AsciiStrGetNextToken (
1460 IN CONST CHAR8 *String,
1461 IN CHAR8 Separator
1462 )
1463 {
1464 CONST CHAR8 *Token;
1465
1466 Token = String;
1467 while (TRUE) {
1468 if (*Token == 0) {
1469 return NULL;
1470 }
1471 if (*Token == Separator) {
1472 return (CHAR8 *)(Token + 1);
1473 }
1474 Token++;
1475 }
1476 }
1477
1478 /**
1479 Set FieldName and FieldValue into specified HttpHeader.
1480
1481 @param[in,out] HttpHeader Specified HttpHeader.
1482 @param[in] FieldName FieldName of this HttpHeader, a NULL terminated ASCII string.
1483 @param[in] FieldValue FieldValue of this HttpHeader, a NULL terminated ASCII string.
1484
1485
1486 @retval EFI_SUCCESS The FieldName and FieldValue are set into HttpHeader successfully.
1487 @retval EFI_INVALID_PARAMETER The parameter is invalid.
1488 @retval EFI_OUT_OF_RESOURCES Failed to allocate resources.
1489
1490 **/
1491 EFI_STATUS
1492 EFIAPI
1493 HttpSetFieldNameAndValue (
1494 IN OUT EFI_HTTP_HEADER *HttpHeader,
1495 IN CONST CHAR8 *FieldName,
1496 IN CONST CHAR8 *FieldValue
1497 )
1498 {
1499 UINTN FieldNameSize;
1500 UINTN FieldValueSize;
1501
1502 if (HttpHeader == NULL || FieldName == NULL || FieldValue == NULL) {
1503 return EFI_INVALID_PARAMETER;
1504 }
1505
1506 if (HttpHeader->FieldName != NULL) {
1507 FreePool (HttpHeader->FieldName);
1508 }
1509 if (HttpHeader->FieldValue != NULL) {
1510 FreePool (HttpHeader->FieldValue);
1511 }
1512
1513 FieldNameSize = AsciiStrSize (FieldName);
1514 HttpHeader->FieldName = AllocateZeroPool (FieldNameSize);
1515 if (HttpHeader->FieldName == NULL) {
1516 return EFI_OUT_OF_RESOURCES;
1517 }
1518 CopyMem (HttpHeader->FieldName, FieldName, FieldNameSize);
1519 HttpHeader->FieldName[FieldNameSize - 1] = 0;
1520
1521 FieldValueSize = AsciiStrSize (FieldValue);
1522 HttpHeader->FieldValue = AllocateZeroPool (FieldValueSize);
1523 if (HttpHeader->FieldValue == NULL) {
1524 FreePool (HttpHeader->FieldName);
1525 return EFI_OUT_OF_RESOURCES;
1526 }
1527 CopyMem (HttpHeader->FieldValue, FieldValue, FieldValueSize);
1528 HttpHeader->FieldValue[FieldValueSize - 1] = 0;
1529
1530 return EFI_SUCCESS;
1531 }
1532
1533 /**
1534 Get one key/value header pair from the raw string.
1535
1536 @param[in] String Pointer to the raw string.
1537 @param[out] FieldName Points directly to field name within 'HttpHeader'.
1538 @param[out] FieldValue Points directly to field value within 'HttpHeader'.
1539
1540 @return Pointer to the next raw string.
1541 @return NULL if no key/value header pair from this raw string.
1542
1543 **/
1544 CHAR8 *
1545 EFIAPI
1546 HttpGetFieldNameAndValue (
1547 IN CHAR8 *String,
1548 OUT CHAR8 **FieldName,
1549 OUT CHAR8 **FieldValue
1550 )
1551 {
1552 CHAR8 *FieldNameStr;
1553 CHAR8 *FieldValueStr;
1554 CHAR8 *StrPtr;
1555 CHAR8 *EndofHeader;
1556
1557 if (String == NULL || FieldName == NULL || FieldValue == NULL) {
1558 return NULL;
1559 }
1560
1561 *FieldName = NULL;
1562 *FieldValue = NULL;
1563 FieldNameStr = NULL;
1564 FieldValueStr = NULL;
1565 StrPtr = NULL;
1566 EndofHeader = NULL;
1567
1568
1569 //
1570 // Check whether the raw HTTP header string is valid or not.
1571 //
1572 EndofHeader = AsciiStrStr (String, "\r\n\r\n");
1573 if (EndofHeader == NULL) {
1574 return NULL;
1575 }
1576
1577 //
1578 // Each header field consists of a name followed by a colon (":") and the field value.
1579 // The field value MAY be preceded by any amount of LWS, though a single SP is preferred.
1580 //
1581 // message-header = field-name ":" [ field-value ]
1582 // field-name = token
1583 // field-value = *( field-content | LWS )
1584 //
1585 // Note: "*(element)" allows any number element, including zero; "1*(element)" requires at least one element.
1586 // [element] means element is optional.
1587 // LWS = [CRLF] 1*(SP|HT), it can be ' ' or '\t' or '\r\n ' or '\r\n\t'.
1588 // CRLF = '\r\n'.
1589 // SP = ' '.
1590 // HT = '\t' (Tab).
1591 //
1592 FieldNameStr = String;
1593 FieldValueStr = AsciiStrGetNextToken (FieldNameStr, ':');
1594 if (FieldValueStr == NULL) {
1595 return NULL;
1596 }
1597
1598 //
1599 // Replace ':' with 0, then FieldName has been retrived from String.
1600 //
1601 *(FieldValueStr - 1) = 0;
1602
1603 //
1604 // Handle FieldValueStr, skip all the preceded LWS.
1605 //
1606 while (TRUE) {
1607 if (*FieldValueStr == ' ' || *FieldValueStr == '\t') {
1608 //
1609 // Boundary condition check.
1610 //
1611 if ((UINTN) EndofHeader - (UINTN) FieldValueStr < 1) {
1612 //
1613 // Wrong String format!
1614 //
1615 return NULL;
1616 }
1617
1618 FieldValueStr ++;
1619 } else if (*FieldValueStr == '\r') {
1620 //
1621 // Boundary condition check.
1622 //
1623 if ((UINTN) EndofHeader - (UINTN) FieldValueStr < 3) {
1624 //
1625 // No more preceded LWS, so break here.
1626 //
1627 break;
1628 }
1629
1630 if (*(FieldValueStr + 1) == '\n' ) {
1631 if (*(FieldValueStr + 2) == ' ' || *(FieldValueStr + 2) == '\t') {
1632 FieldValueStr = FieldValueStr + 3;
1633 } else {
1634 //
1635 // No more preceded LWS, so break here.
1636 //
1637 break;
1638 }
1639 } else {
1640 //
1641 // Wrong String format!
1642 //
1643 return NULL;
1644 }
1645 } else {
1646 //
1647 // No more preceded LWS, so break here.
1648 //
1649 break;
1650 }
1651 }
1652
1653 StrPtr = FieldValueStr;
1654 do {
1655 //
1656 // Handle the LWS within the field value.
1657 //
1658 StrPtr = AsciiStrGetNextToken (StrPtr, '\r');
1659 if (StrPtr == NULL || *StrPtr != '\n') {
1660 //
1661 // Wrong String format!
1662 //
1663 return NULL;
1664 }
1665
1666 StrPtr++;
1667 } while (*StrPtr == ' ' || *StrPtr == '\t');
1668
1669 //
1670 // Replace '\r' with 0
1671 //
1672 *(StrPtr - 2) = 0;
1673
1674 //
1675 // Get FieldName and FieldValue.
1676 //
1677 *FieldName = FieldNameStr;
1678 *FieldValue = FieldValueStr;
1679
1680 return StrPtr;
1681 }
1682
1683 /**
1684 Free existing HeaderFields.
1685
1686 @param[in] HeaderFields Pointer to array of key/value header pairs waitting for free.
1687 @param[in] FieldCount The number of header pairs in HeaderFields.
1688
1689 **/
1690 VOID
1691 EFIAPI
1692 HttpFreeHeaderFields (
1693 IN EFI_HTTP_HEADER *HeaderFields,
1694 IN UINTN FieldCount
1695 )
1696 {
1697 UINTN Index;
1698
1699 if (HeaderFields != NULL) {
1700 for (Index = 0; Index < FieldCount; Index++) {
1701 if (HeaderFields[Index].FieldName != NULL) {
1702 FreePool (HeaderFields[Index].FieldName);
1703 }
1704 if (HeaderFields[Index].FieldValue != NULL) {
1705 FreePool (HeaderFields[Index].FieldValue);
1706 }
1707 }
1708
1709 FreePool (HeaderFields);
1710 }
1711 }
1712
1713 /**
1714 Generate HTTP request message.
1715
1716 This function will allocate memory for the whole HTTP message and generate a
1717 well formatted HTTP Request message in it, include the Request-Line, header
1718 fields and also the message body. It is the caller's responsibility to free
1719 the buffer returned in *RequestMsg.
1720
1721 @param[in] Message Pointer to the EFI_HTTP_MESSAGE structure which
1722 contains the required information to generate
1723 the HTTP request message.
1724 @param[in] Url The URL of a remote host.
1725 @param[out] RequestMsg Pointer to the created HTTP request message.
1726 NULL if any error occured.
1727 @param[out] RequestMsgSize Size of the RequestMsg (in bytes).
1728
1729 @retval EFI_SUCCESS If HTTP request string was created successfully.
1730 @retval EFI_OUT_OF_RESOURCES Failed to allocate resources.
1731 @retval EFI_INVALID_PARAMETER The input arguments are invalid.
1732
1733 **/
1734 EFI_STATUS
1735 EFIAPI
1736 HttpGenRequestMessage (
1737 IN CONST EFI_HTTP_MESSAGE *Message,
1738 IN CONST CHAR8 *Url,
1739 OUT CHAR8 **RequestMsg,
1740 OUT UINTN *RequestMsgSize
1741 )
1742 {
1743 EFI_STATUS Status;
1744 UINTN StrLength;
1745 CHAR8 *RequestPtr;
1746 UINTN HttpHdrSize;
1747 UINTN MsgSize;
1748 BOOLEAN Success;
1749 VOID *HttpHdr;
1750 EFI_HTTP_HEADER **AppendList;
1751 UINTN Index;
1752 EFI_HTTP_UTILITIES_PROTOCOL *HttpUtilitiesProtocol;
1753
1754 Status = EFI_SUCCESS;
1755 HttpHdrSize = 0;
1756 MsgSize = 0;
1757 Success = FALSE;
1758 HttpHdr = NULL;
1759 AppendList = NULL;
1760 HttpUtilitiesProtocol = NULL;
1761
1762 //
1763 // 1. If we have a Request, we cannot have a NULL Url
1764 // 2. If we have a Request, HeaderCount can not be non-zero
1765 // 3. If we do not have a Request, HeaderCount should be zero
1766 // 4. If we do not have Request and Headers, we need at least a message-body
1767 //
1768 if ((Message == NULL || RequestMsg == NULL || RequestMsgSize == NULL) ||
1769 (Message->Data.Request != NULL && Url == NULL) ||
1770 (Message->Data.Request != NULL && Message->HeaderCount == 0) ||
1771 (Message->Data.Request == NULL && Message->HeaderCount != 0) ||
1772 (Message->Data.Request == NULL && Message->HeaderCount == 0 && Message->BodyLength == 0)) {
1773 return EFI_INVALID_PARAMETER;
1774 }
1775
1776 if (Message->HeaderCount != 0) {
1777 //
1778 // Locate the HTTP_UTILITIES protocol.
1779 //
1780 Status = gBS->LocateProtocol (
1781 &gEfiHttpUtilitiesProtocolGuid,
1782 NULL,
1783 (VOID **) &HttpUtilitiesProtocol
1784 );
1785
1786 if (EFI_ERROR (Status)) {
1787 DEBUG ((DEBUG_ERROR,"Failed to locate Http Utilities protocol. Status = %r.\n", Status));
1788 return Status;
1789 }
1790
1791 //
1792 // Build AppendList to send into HttpUtilitiesBuild
1793 //
1794 AppendList = AllocateZeroPool (sizeof (EFI_HTTP_HEADER *) * (Message->HeaderCount));
1795 if (AppendList == NULL) {
1796 return EFI_OUT_OF_RESOURCES;
1797 }
1798
1799 for(Index = 0; Index < Message->HeaderCount; Index++){
1800 AppendList[Index] = &Message->Headers[Index];
1801 }
1802
1803 //
1804 // Build raw HTTP Headers
1805 //
1806 Status = HttpUtilitiesProtocol->Build (
1807 HttpUtilitiesProtocol,
1808 0,
1809 NULL,
1810 0,
1811 NULL,
1812 Message->HeaderCount,
1813 AppendList,
1814 &HttpHdrSize,
1815 &HttpHdr
1816 );
1817
1818 FreePool (AppendList);
1819
1820 if (EFI_ERROR (Status) || HttpHdr == NULL){
1821 return Status;
1822 }
1823 }
1824
1825 //
1826 // If we have headers to be sent, account for it.
1827 //
1828 if (Message->HeaderCount != 0) {
1829 MsgSize = HttpHdrSize;
1830 }
1831
1832 //
1833 // If we have a request line, account for the fields.
1834 //
1835 if (Message->Data.Request != NULL) {
1836 MsgSize += HTTP_METHOD_MAXIMUM_LEN + AsciiStrLen (HTTP_VERSION_CRLF_STR) + AsciiStrLen (Url);
1837 }
1838
1839
1840 //
1841 // If we have a message body to be sent, account for it.
1842 //
1843 MsgSize += Message->BodyLength;
1844
1845 //
1846 // memory for the string that needs to be sent to TCP
1847 //
1848 *RequestMsg = NULL;
1849 *RequestMsg = AllocateZeroPool (MsgSize);
1850 if (*RequestMsg == NULL) {
1851 Status = EFI_OUT_OF_RESOURCES;
1852 goto Exit;
1853 }
1854
1855 RequestPtr = *RequestMsg;
1856 //
1857 // Construct header request
1858 //
1859 if (Message->Data.Request != NULL) {
1860 switch (Message->Data.Request->Method) {
1861 case HttpMethodGet:
1862 StrLength = sizeof (HTTP_METHOD_GET) - 1;
1863 CopyMem (RequestPtr, HTTP_METHOD_GET, StrLength);
1864 RequestPtr += StrLength;
1865 break;
1866 case HttpMethodPut:
1867 StrLength = sizeof (HTTP_METHOD_PUT) - 1;
1868 CopyMem (RequestPtr, HTTP_METHOD_PUT, StrLength);
1869 RequestPtr += StrLength;
1870 break;
1871 case HttpMethodPatch:
1872 StrLength = sizeof (HTTP_METHOD_PATCH) - 1;
1873 CopyMem (RequestPtr, HTTP_METHOD_PATCH, StrLength);
1874 RequestPtr += StrLength;
1875 break;
1876 case HttpMethodPost:
1877 StrLength = sizeof (HTTP_METHOD_POST) - 1;
1878 CopyMem (RequestPtr, HTTP_METHOD_POST, StrLength);
1879 RequestPtr += StrLength;
1880 break;
1881 case HttpMethodHead:
1882 StrLength = sizeof (HTTP_METHOD_HEAD) - 1;
1883 CopyMem (RequestPtr, HTTP_METHOD_HEAD, StrLength);
1884 RequestPtr += StrLength;
1885 break;
1886 case HttpMethodDelete:
1887 StrLength = sizeof (HTTP_METHOD_DELETE) - 1;
1888 CopyMem (RequestPtr, HTTP_METHOD_DELETE, StrLength);
1889 RequestPtr += StrLength;
1890 break;
1891 default:
1892 ASSERT (FALSE);
1893 Status = EFI_INVALID_PARAMETER;
1894 goto Exit;
1895 }
1896
1897 StrLength = AsciiStrLen(EMPTY_SPACE);
1898 CopyMem (RequestPtr, EMPTY_SPACE, StrLength);
1899 RequestPtr += StrLength;
1900
1901 StrLength = AsciiStrLen (Url);
1902 CopyMem (RequestPtr, Url, StrLength);
1903 RequestPtr += StrLength;
1904
1905 StrLength = sizeof (HTTP_VERSION_CRLF_STR) - 1;
1906 CopyMem (RequestPtr, HTTP_VERSION_CRLF_STR, StrLength);
1907 RequestPtr += StrLength;
1908
1909 if (HttpHdr != NULL) {
1910 //
1911 // Construct header
1912 //
1913 CopyMem (RequestPtr, HttpHdr, HttpHdrSize);
1914 RequestPtr += HttpHdrSize;
1915 }
1916 }
1917
1918 //
1919 // Construct body
1920 //
1921 if (Message->Body != NULL) {
1922 CopyMem (RequestPtr, Message->Body, Message->BodyLength);
1923 RequestPtr += Message->BodyLength;
1924 }
1925
1926 //
1927 // Done
1928 //
1929 (*RequestMsgSize) = (UINTN)(RequestPtr) - (UINTN)(*RequestMsg);
1930 Success = TRUE;
1931
1932 Exit:
1933
1934 if (!Success) {
1935 if (*RequestMsg != NULL) {
1936 FreePool (*RequestMsg);
1937 }
1938 *RequestMsg = NULL;
1939 return Status;
1940 }
1941
1942 if (HttpHdr != NULL) {
1943 FreePool (HttpHdr);
1944 }
1945
1946 return EFI_SUCCESS;
1947 }
1948
1949 /**
1950 Translate the status code in HTTP message to EFI_HTTP_STATUS_CODE defined
1951 in UEFI 2.5 specification.
1952
1953 @param[in] StatusCode The status code value in HTTP message.
1954
1955 @return Value defined in EFI_HTTP_STATUS_CODE .
1956
1957 **/
1958 EFI_HTTP_STATUS_CODE
1959 EFIAPI
1960 HttpMappingToStatusCode (
1961 IN UINTN StatusCode
1962 )
1963 {
1964 switch (StatusCode) {
1965 case 100:
1966 return HTTP_STATUS_100_CONTINUE;
1967 case 101:
1968 return HTTP_STATUS_101_SWITCHING_PROTOCOLS;
1969 case 200:
1970 return HTTP_STATUS_200_OK;
1971 case 201:
1972 return HTTP_STATUS_201_CREATED;
1973 case 202:
1974 return HTTP_STATUS_202_ACCEPTED;
1975 case 203:
1976 return HTTP_STATUS_203_NON_AUTHORITATIVE_INFORMATION;
1977 case 204:
1978 return HTTP_STATUS_204_NO_CONTENT;
1979 case 205:
1980 return HTTP_STATUS_205_RESET_CONTENT;
1981 case 206:
1982 return HTTP_STATUS_206_PARTIAL_CONTENT;
1983 case 300:
1984 return HTTP_STATUS_300_MULTIPLE_CHOICES;
1985 case 301:
1986 return HTTP_STATUS_301_MOVED_PERMANENTLY;
1987 case 302:
1988 return HTTP_STATUS_302_FOUND;
1989 case 303:
1990 return HTTP_STATUS_303_SEE_OTHER;
1991 case 304:
1992 return HTTP_STATUS_304_NOT_MODIFIED;
1993 case 305:
1994 return HTTP_STATUS_305_USE_PROXY;
1995 case 307:
1996 return HTTP_STATUS_307_TEMPORARY_REDIRECT;
1997 case 308:
1998 return HTTP_STATUS_308_PERMANENT_REDIRECT;
1999 case 400:
2000 return HTTP_STATUS_400_BAD_REQUEST;
2001 case 401:
2002 return HTTP_STATUS_401_UNAUTHORIZED;
2003 case 402:
2004 return HTTP_STATUS_402_PAYMENT_REQUIRED;
2005 case 403:
2006 return HTTP_STATUS_403_FORBIDDEN;
2007 case 404:
2008 return HTTP_STATUS_404_NOT_FOUND;
2009 case 405:
2010 return HTTP_STATUS_405_METHOD_NOT_ALLOWED;
2011 case 406:
2012 return HTTP_STATUS_406_NOT_ACCEPTABLE;
2013 case 407:
2014 return HTTP_STATUS_407_PROXY_AUTHENTICATION_REQUIRED;
2015 case 408:
2016 return HTTP_STATUS_408_REQUEST_TIME_OUT;
2017 case 409:
2018 return HTTP_STATUS_409_CONFLICT;
2019 case 410:
2020 return HTTP_STATUS_410_GONE;
2021 case 411:
2022 return HTTP_STATUS_411_LENGTH_REQUIRED;
2023 case 412:
2024 return HTTP_STATUS_412_PRECONDITION_FAILED;
2025 case 413:
2026 return HTTP_STATUS_413_REQUEST_ENTITY_TOO_LARGE;
2027 case 414:
2028 return HTTP_STATUS_414_REQUEST_URI_TOO_LARGE;
2029 case 415:
2030 return HTTP_STATUS_415_UNSUPPORTED_MEDIA_TYPE;
2031 case 416:
2032 return HTTP_STATUS_416_REQUESTED_RANGE_NOT_SATISFIED;
2033 case 417:
2034 return HTTP_STATUS_417_EXPECTATION_FAILED;
2035 case 500:
2036 return HTTP_STATUS_500_INTERNAL_SERVER_ERROR;
2037 case 501:
2038 return HTTP_STATUS_501_NOT_IMPLEMENTED;
2039 case 502:
2040 return HTTP_STATUS_502_BAD_GATEWAY;
2041 case 503:
2042 return HTTP_STATUS_503_SERVICE_UNAVAILABLE;
2043 case 504:
2044 return HTTP_STATUS_504_GATEWAY_TIME_OUT;
2045 case 505:
2046 return HTTP_STATUS_505_HTTP_VERSION_NOT_SUPPORTED;
2047
2048 default:
2049 return HTTP_STATUS_UNSUPPORTED_STATUS;
2050 }
2051 }
2052
2053 /**
2054 Check whether header field called FieldName is in DeleteList.
2055
2056 @param[in] DeleteList Pointer to array of key/value header pairs.
2057 @param[in] DeleteCount The number of header pairs.
2058 @param[in] FieldName Pointer to header field's name.
2059
2060 @return TRUE if FieldName is not in DeleteList, that means this header field is valid.
2061 @return FALSE if FieldName is in DeleteList, that means this header field is invalid.
2062
2063 **/
2064 BOOLEAN
2065 EFIAPI
2066 HttpIsValidHttpHeader (
2067 IN CHAR8 *DeleteList[],
2068 IN UINTN DeleteCount,
2069 IN CHAR8 *FieldName
2070 )
2071 {
2072 UINTN Index;
2073
2074 if (FieldName == NULL) {
2075 return FALSE;
2076 }
2077
2078 for (Index = 0; Index < DeleteCount; Index++) {
2079 if (DeleteList[Index] == NULL) {
2080 continue;
2081 }
2082
2083 if (AsciiStrCmp (FieldName, DeleteList[Index]) == 0) {
2084 return FALSE;
2085 }
2086 }
2087
2088 return TRUE;
2089 }
2090