]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeHttpLib/DxeHttpLib.c
MdeModulePkg/Library/DxeHttpLib: Handle the blank value in HTTP header.
[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 - 2018, 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
903 Convert an Ascii char to its uppercase.
904
905 @param[in] Char Ascii character.
906
907 @return Uppercase value of the input Char.
908
909 **/
910 CHAR8
911 HttpIoCharToUpper (
912 IN CHAR8 Char
913 )
914 {
915 if (Char >= 'a' && Char <= 'z') {
916 return Char - ('a' - 'A');
917 }
918
919 return Char;
920 }
921
922 /**
923 Convert an hexadecimal char to a value of type UINTN.
924
925 @param[in] Char Ascii character.
926
927 @return Value translated from Char.
928
929 **/
930 UINTN
931 HttpIoHexCharToUintn (
932 IN CHAR8 Char
933 )
934 {
935 if (Char >= '0' && Char <= '9') {
936 return Char - '0';
937 }
938
939 return (10 + HttpIoCharToUpper (Char) - 'A');
940 }
941
942 /**
943 Get the value of the content length if there is a "Content-Length" header.
944
945 @param[in] HeaderCount Number of HTTP header structures in Headers.
946 @param[in] Headers Array containing list of HTTP headers.
947 @param[out] ContentLength Pointer to save the value of the content length.
948
949 @retval EFI_SUCCESS Successfully get the content length.
950 @retval EFI_NOT_FOUND No "Content-Length" header in the Headers.
951
952 **/
953 EFI_STATUS
954 HttpIoParseContentLengthHeader (
955 IN UINTN HeaderCount,
956 IN EFI_HTTP_HEADER *Headers,
957 OUT UINTN *ContentLength
958 )
959 {
960 EFI_HTTP_HEADER *Header;
961
962 Header = HttpFindHeader (HeaderCount, Headers, HTTP_HEADER_CONTENT_LENGTH);
963 if (Header == NULL) {
964 return EFI_NOT_FOUND;
965 }
966
967 return AsciiStrDecimalToUintnS (Header->FieldValue, (CHAR8 **) NULL, ContentLength);
968 }
969
970 /**
971
972 Check whether the HTTP message is using the "chunked" transfer-coding.
973
974 @param[in] HeaderCount Number of HTTP header structures in Headers.
975 @param[in] Headers Array containing list of HTTP headers.
976
977 @return The message is "chunked" transfer-coding (TRUE) or not (FALSE).
978
979 **/
980 BOOLEAN
981 HttpIoIsChunked (
982 IN UINTN HeaderCount,
983 IN EFI_HTTP_HEADER *Headers
984 )
985 {
986 EFI_HTTP_HEADER *Header;
987
988
989 Header = HttpFindHeader (HeaderCount, Headers, HTTP_HEADER_TRANSFER_ENCODING);
990 if (Header == NULL) {
991 return FALSE;
992 }
993
994 if (AsciiStriCmp (Header->FieldValue, "identity") != 0) {
995 return TRUE;
996 }
997
998 return FALSE;
999 }
1000
1001 /**
1002 Check whether the HTTP message should have a message-body.
1003
1004 @param[in] Method The HTTP method (e.g. GET, POST) for this HTTP message.
1005 @param[in] StatusCode Response status code returned by the remote host.
1006
1007 @return The message should have a message-body (FALSE) or not (TRUE).
1008
1009 **/
1010 BOOLEAN
1011 HttpIoNoMessageBody (
1012 IN EFI_HTTP_METHOD Method,
1013 IN EFI_HTTP_STATUS_CODE StatusCode
1014 )
1015 {
1016 //
1017 // RFC 2616:
1018 // All responses to the HEAD request method
1019 // MUST NOT include a message-body, even though the presence of entity-
1020 // header fields might lead one to believe they do. All 1xx
1021 // (informational), 204 (no content), and 304 (not modified) responses
1022 // MUST NOT include a message-body. All other responses do include a
1023 // message-body, although it MAY be of zero length.
1024 //
1025 if (Method == HttpMethodHead) {
1026 return TRUE;
1027 }
1028
1029 if ((StatusCode == HTTP_STATUS_100_CONTINUE) ||
1030 (StatusCode == HTTP_STATUS_101_SWITCHING_PROTOCOLS) ||
1031 (StatusCode == HTTP_STATUS_204_NO_CONTENT) ||
1032 (StatusCode == HTTP_STATUS_304_NOT_MODIFIED))
1033 {
1034 return TRUE;
1035 }
1036
1037 return FALSE;
1038 }
1039
1040 /**
1041 Initialize a HTTP message-body parser.
1042
1043 This function will create and initialize a HTTP message parser according to caller provided HTTP message
1044 header information. It is the caller's responsibility to free the buffer returned in *UrlParser by HttpFreeMsgParser().
1045
1046 @param[in] Method The HTTP method (e.g. GET, POST) for this HTTP message.
1047 @param[in] StatusCode Response status code returned by the remote host.
1048 @param[in] HeaderCount Number of HTTP header structures in Headers.
1049 @param[in] Headers Array containing list of HTTP headers.
1050 @param[in] Callback Callback function that is invoked when parsing the HTTP message-body,
1051 set to NULL to ignore all events.
1052 @param[in] Context Pointer to the context that will be passed to Callback.
1053 @param[out] MsgParser Pointer to the returned buffer to store the message parser.
1054
1055 @retval EFI_SUCCESS Successfully initialized the parser.
1056 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
1057 @retval EFI_INVALID_PARAMETER MsgParser is NULL or HeaderCount is not NULL but Headers is NULL.
1058 @retval Others Failed to initialize the parser.
1059
1060 **/
1061 EFI_STATUS
1062 EFIAPI
1063 HttpInitMsgParser (
1064 IN EFI_HTTP_METHOD Method,
1065 IN EFI_HTTP_STATUS_CODE StatusCode,
1066 IN UINTN HeaderCount,
1067 IN EFI_HTTP_HEADER *Headers,
1068 IN HTTP_BODY_PARSER_CALLBACK Callback,
1069 IN VOID *Context,
1070 OUT VOID **MsgParser
1071 )
1072 {
1073 EFI_STATUS Status;
1074 HTTP_BODY_PARSER *Parser;
1075
1076 if (HeaderCount != 0 && Headers == NULL) {
1077 return EFI_INVALID_PARAMETER;
1078 }
1079
1080 if (MsgParser == NULL) {
1081 return EFI_INVALID_PARAMETER;
1082 }
1083
1084 Parser = AllocateZeroPool (sizeof (HTTP_BODY_PARSER));
1085 if (Parser == NULL) {
1086 return EFI_OUT_OF_RESOURCES;
1087 }
1088
1089 Parser->State = BodyParserBodyStart;
1090
1091 //
1092 // Determine the message length according to RFC 2616.
1093 // 1. Check whether the message "MUST NOT" have a message-body.
1094 //
1095 Parser->IgnoreBody = HttpIoNoMessageBody (Method, StatusCode);
1096 //
1097 // 2. Check whether the message using "chunked" transfer-coding.
1098 //
1099 Parser->IsChunked = HttpIoIsChunked (HeaderCount, Headers);
1100 //
1101 // 3. Check whether the message has a Content-Length header field.
1102 //
1103 Status = HttpIoParseContentLengthHeader (HeaderCount, Headers, &Parser->ContentLength);
1104 if (!EFI_ERROR (Status)) {
1105 Parser->ContentLengthIsValid = TRUE;
1106 }
1107 //
1108 // 4. Range header is not supported now, so we won't meet media type "multipart/byteranges".
1109 // 5. By server closing the connection
1110 //
1111
1112 //
1113 // Set state to skip body parser if the message shouldn't have a message body.
1114 //
1115 if (Parser->IgnoreBody) {
1116 Parser->State = BodyParserComplete;
1117 } else {
1118 Parser->Callback = Callback;
1119 Parser->Context = Context;
1120 }
1121
1122 *MsgParser = Parser;
1123 return EFI_SUCCESS;
1124 }
1125
1126 /**
1127 Parse message body.
1128
1129 Parse BodyLength of message-body. This function can be called repeatedly to parse the message-body partially.
1130
1131 @param[in, out] MsgParser Pointer to the message parser.
1132 @param[in] BodyLength Length in bytes of the Body.
1133 @param[in] Body Pointer to the buffer of the message-body to be parsed.
1134
1135 @retval EFI_SUCCESS Successfully parse the message-body.
1136 @retval EFI_INVALID_PARAMETER MsgParser is NULL or Body is NULL or BodyLength is 0.
1137 @retval EFI_ABORTED Operation aborted.
1138 @retval Other Error happened while parsing message body.
1139
1140 **/
1141 EFI_STATUS
1142 EFIAPI
1143 HttpParseMessageBody (
1144 IN OUT VOID *MsgParser,
1145 IN UINTN BodyLength,
1146 IN CHAR8 *Body
1147 )
1148 {
1149 CHAR8 *Char;
1150 UINTN RemainderLengthInThis;
1151 UINTN LengthForCallback;
1152 EFI_STATUS Status;
1153 HTTP_BODY_PARSER *Parser;
1154
1155 if (BodyLength == 0 || Body == NULL) {
1156 return EFI_INVALID_PARAMETER;
1157 }
1158
1159 if (MsgParser == NULL) {
1160 return EFI_INVALID_PARAMETER;
1161 }
1162
1163 Parser = (HTTP_BODY_PARSER *) MsgParser;
1164
1165 if (Parser->IgnoreBody) {
1166 Parser->State = BodyParserComplete;
1167 if (Parser->Callback != NULL) {
1168 Status = Parser->Callback (
1169 BodyParseEventOnComplete,
1170 Body,
1171 0,
1172 Parser->Context
1173 );
1174 if (EFI_ERROR (Status)) {
1175 return Status;
1176 }
1177 }
1178 return EFI_SUCCESS;
1179 }
1180
1181 if (Parser->State == BodyParserBodyStart) {
1182 Parser->ParsedBodyLength = 0;
1183 if (Parser->IsChunked) {
1184 Parser->State = BodyParserChunkSizeStart;
1185 } else {
1186 Parser->State = BodyParserBodyIdentity;
1187 }
1188 }
1189
1190 //
1191 // The message body might be truncated in anywhere, so we need to parse is byte-by-byte.
1192 //
1193 for (Char = Body; Char < Body + BodyLength; ) {
1194
1195 switch (Parser->State) {
1196 case BodyParserStateMax:
1197 return EFI_ABORTED;
1198
1199 case BodyParserBodyIdentity:
1200 //
1201 // Identity transfer-coding, just notify user to save the body data.
1202 //
1203 if (Parser->Callback != NULL) {
1204 Status = Parser->Callback (
1205 BodyParseEventOnData,
1206 Char,
1207 MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength),
1208 Parser->Context
1209 );
1210 if (EFI_ERROR (Status)) {
1211 return Status;
1212 }
1213 }
1214 Char += MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength);
1215 Parser->ParsedBodyLength += MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength);
1216 if (Parser->ParsedBodyLength == Parser->ContentLength) {
1217 Parser->State = BodyParserComplete;
1218 if (Parser->Callback != NULL) {
1219 Status = Parser->Callback (
1220 BodyParseEventOnComplete,
1221 Char,
1222 0,
1223 Parser->Context
1224 );
1225 if (EFI_ERROR (Status)) {
1226 return Status;
1227 }
1228 }
1229 }
1230 break;
1231
1232 case BodyParserChunkSizeStart:
1233 //
1234 // First byte of chunk-size, the chunk-size might be truncated.
1235 //
1236 Parser->CurrentChunkSize = 0;
1237 Parser->State = BodyParserChunkSize;
1238 case BodyParserChunkSize:
1239 if (!NET_IS_HEX_CHAR (*Char)) {
1240 if (*Char == ';') {
1241 Parser->State = BodyParserChunkExtStart;
1242 Char++;
1243 } else if (*Char == '\r') {
1244 Parser->State = BodyParserChunkSizeEndCR;
1245 Char++;
1246 } else {
1247 Parser->State = BodyParserStateMax;
1248 }
1249 break;
1250 }
1251
1252 if (Parser->CurrentChunkSize > (((~((UINTN) 0)) - 16) / 16)) {
1253 return EFI_INVALID_PARAMETER;
1254 }
1255 Parser->CurrentChunkSize = Parser->CurrentChunkSize * 16 + HttpIoHexCharToUintn (*Char);
1256 Char++;
1257 break;
1258
1259 case BodyParserChunkExtStart:
1260 //
1261 // Ignore all the chunk extensions.
1262 //
1263 if (*Char == '\r') {
1264 Parser->State = BodyParserChunkSizeEndCR;
1265 }
1266 Char++;
1267 break;
1268
1269 case BodyParserChunkSizeEndCR:
1270 if (*Char != '\n') {
1271 Parser->State = BodyParserStateMax;
1272 break;
1273 }
1274 Char++;
1275 if (Parser->CurrentChunkSize == 0) {
1276 //
1277 // The last chunk has been parsed and now assumed the state
1278 // of HttpBodyParse is ParserLastCRLF. So it need to decide
1279 // whether the rest message is trailer or last CRLF in the next round.
1280 //
1281 Parser->ContentLengthIsValid = TRUE;
1282 Parser->State = BodyParserLastCRLF;
1283 break;
1284 }
1285 Parser->State = BodyParserChunkDataStart;
1286 Parser->CurrentChunkParsedSize = 0;
1287 break;
1288
1289 case BodyParserLastCRLF:
1290 //
1291 // Judge the byte is belong to the Last CRLF or trailer, and then
1292 // configure the state of HttpBodyParse to corresponding state.
1293 //
1294 if (*Char == '\r') {
1295 Char++;
1296 Parser->State = BodyParserLastCRLFEnd;
1297 break;
1298 } else {
1299 Parser->State = BodyParserTrailer;
1300 break;
1301 }
1302
1303 case BodyParserLastCRLFEnd:
1304 if (*Char == '\n') {
1305 Parser->State = BodyParserComplete;
1306 Char++;
1307 if (Parser->Callback != NULL) {
1308 Status = Parser->Callback (
1309 BodyParseEventOnComplete,
1310 Char,
1311 0,
1312 Parser->Context
1313 );
1314 if (EFI_ERROR (Status)) {
1315 return Status;
1316 }
1317 }
1318 break;
1319 } else {
1320 Parser->State = BodyParserStateMax;
1321 break;
1322 }
1323
1324 case BodyParserTrailer:
1325 if (*Char == '\r') {
1326 Parser->State = BodyParserChunkSizeEndCR;
1327 }
1328 Char++;
1329 break;
1330
1331 case BodyParserChunkDataStart:
1332 //
1333 // First byte of chunk-data, the chunk data also might be truncated.
1334 //
1335 RemainderLengthInThis = BodyLength - (Char - Body);
1336 LengthForCallback = MIN (Parser->CurrentChunkSize - Parser->CurrentChunkParsedSize, RemainderLengthInThis);
1337 if (Parser->Callback != NULL) {
1338 Status = Parser->Callback (
1339 BodyParseEventOnData,
1340 Char,
1341 LengthForCallback,
1342 Parser->Context
1343 );
1344 if (EFI_ERROR (Status)) {
1345 return Status;
1346 }
1347 }
1348 Char += LengthForCallback;
1349 Parser->ContentLength += LengthForCallback;
1350 Parser->CurrentChunkParsedSize += LengthForCallback;
1351 if (Parser->CurrentChunkParsedSize == Parser->CurrentChunkSize) {
1352 Parser->State = BodyParserChunkDataEnd;
1353 }
1354 break;
1355
1356 case BodyParserChunkDataEnd:
1357 if (*Char == '\r') {
1358 Parser->State = BodyParserChunkDataEndCR;
1359 } else {
1360 Parser->State = BodyParserStateMax;
1361 }
1362 Char++;
1363 break;
1364
1365 case BodyParserChunkDataEndCR:
1366 if (*Char != '\n') {
1367 Parser->State = BodyParserStateMax;
1368 break;
1369 }
1370 Char++;
1371 Parser->State = BodyParserChunkSizeStart;
1372 break;
1373
1374 default:
1375 break;
1376 }
1377
1378 }
1379
1380 if (Parser->State == BodyParserStateMax) {
1381 return EFI_ABORTED;
1382 }
1383
1384 return EFI_SUCCESS;
1385 }
1386
1387 /**
1388 Check whether the message-body is complete or not.
1389
1390 @param[in] MsgParser Pointer to the message parser.
1391
1392 @retval TRUE Message-body is complete.
1393 @retval FALSE Message-body is not complete.
1394
1395 **/
1396 BOOLEAN
1397 EFIAPI
1398 HttpIsMessageComplete (
1399 IN VOID *MsgParser
1400 )
1401 {
1402 HTTP_BODY_PARSER *Parser;
1403
1404 if (MsgParser == NULL) {
1405 return FALSE;
1406 }
1407
1408 Parser = (HTTP_BODY_PARSER *) MsgParser;
1409
1410 if (Parser->State == BodyParserComplete) {
1411 return TRUE;
1412 }
1413 return FALSE;
1414 }
1415
1416 /**
1417 Get the content length of the entity.
1418
1419 Note that in trunk transfer, the entity length is not valid until the whole message body is received.
1420
1421 @param[in] MsgParser Pointer to the message parser.
1422 @param[out] ContentLength Pointer to store the length of the entity.
1423
1424 @retval EFI_SUCCESS Successfully to get the entity length.
1425 @retval EFI_NOT_READY Entity length is not valid yet.
1426 @retval EFI_INVALID_PARAMETER MsgParser is NULL or ContentLength is NULL.
1427
1428 **/
1429 EFI_STATUS
1430 EFIAPI
1431 HttpGetEntityLength (
1432 IN VOID *MsgParser,
1433 OUT UINTN *ContentLength
1434 )
1435 {
1436 HTTP_BODY_PARSER *Parser;
1437
1438 if (MsgParser == NULL || ContentLength == NULL) {
1439 return EFI_INVALID_PARAMETER;
1440 }
1441
1442 Parser = (HTTP_BODY_PARSER *) MsgParser;
1443
1444 if (!Parser->ContentLengthIsValid) {
1445 return EFI_NOT_READY;
1446 }
1447
1448 *ContentLength = Parser->ContentLength;
1449 return EFI_SUCCESS;
1450 }
1451
1452 /**
1453 Release the resource of the message parser.
1454
1455 @param[in] MsgParser Pointer to the message parser.
1456
1457 **/
1458 VOID
1459 EFIAPI
1460 HttpFreeMsgParser (
1461 IN VOID *MsgParser
1462 )
1463 {
1464 FreePool (MsgParser);
1465 }
1466
1467
1468 /**
1469 Get the next string, which is distinguished by specified separator.
1470
1471 @param[in] String Pointer to the string.
1472 @param[in] Separator Specified separator used to distinguish where is the beginning
1473 of next string.
1474
1475 @return Pointer to the next string.
1476 @return NULL if not find or String is NULL.
1477
1478 **/
1479 CHAR8 *
1480 AsciiStrGetNextToken (
1481 IN CONST CHAR8 *String,
1482 IN CHAR8 Separator
1483 )
1484 {
1485 CONST CHAR8 *Token;
1486
1487 Token = String;
1488 while (TRUE) {
1489 if (*Token == 0) {
1490 return NULL;
1491 }
1492 if (*Token == Separator) {
1493 return (CHAR8 *)(Token + 1);
1494 }
1495 Token++;
1496 }
1497 }
1498
1499 /**
1500 Set FieldName and FieldValue into specified HttpHeader.
1501
1502 @param[in,out] HttpHeader Specified HttpHeader.
1503 @param[in] FieldName FieldName of this HttpHeader, a NULL terminated ASCII string.
1504 @param[in] FieldValue FieldValue of this HttpHeader, a NULL terminated ASCII string.
1505
1506
1507 @retval EFI_SUCCESS The FieldName and FieldValue are set into HttpHeader successfully.
1508 @retval EFI_INVALID_PARAMETER The parameter is invalid.
1509 @retval EFI_OUT_OF_RESOURCES Failed to allocate resources.
1510
1511 **/
1512 EFI_STATUS
1513 EFIAPI
1514 HttpSetFieldNameAndValue (
1515 IN OUT EFI_HTTP_HEADER *HttpHeader,
1516 IN CONST CHAR8 *FieldName,
1517 IN CONST CHAR8 *FieldValue
1518 )
1519 {
1520 UINTN FieldNameSize;
1521 UINTN FieldValueSize;
1522
1523 if (HttpHeader == NULL || FieldName == NULL || FieldValue == NULL) {
1524 return EFI_INVALID_PARAMETER;
1525 }
1526
1527 if (HttpHeader->FieldName != NULL) {
1528 FreePool (HttpHeader->FieldName);
1529 }
1530 if (HttpHeader->FieldValue != NULL) {
1531 FreePool (HttpHeader->FieldValue);
1532 }
1533
1534 FieldNameSize = AsciiStrSize (FieldName);
1535 HttpHeader->FieldName = AllocateZeroPool (FieldNameSize);
1536 if (HttpHeader->FieldName == NULL) {
1537 return EFI_OUT_OF_RESOURCES;
1538 }
1539 CopyMem (HttpHeader->FieldName, FieldName, FieldNameSize);
1540 HttpHeader->FieldName[FieldNameSize - 1] = 0;
1541
1542 FieldValueSize = AsciiStrSize (FieldValue);
1543 HttpHeader->FieldValue = AllocateZeroPool (FieldValueSize);
1544 if (HttpHeader->FieldValue == NULL) {
1545 FreePool (HttpHeader->FieldName);
1546 return EFI_OUT_OF_RESOURCES;
1547 }
1548 CopyMem (HttpHeader->FieldValue, FieldValue, FieldValueSize);
1549 HttpHeader->FieldValue[FieldValueSize - 1] = 0;
1550
1551 return EFI_SUCCESS;
1552 }
1553
1554 /**
1555 Get one key/value header pair from the raw string.
1556
1557 @param[in] String Pointer to the raw string.
1558 @param[out] FieldName Points directly to field name within 'HttpHeader'.
1559 @param[out] FieldValue Points directly to field value within 'HttpHeader'.
1560
1561 @return Pointer to the next raw string.
1562 @return NULL if no key/value header pair from this raw string.
1563
1564 **/
1565 CHAR8 *
1566 EFIAPI
1567 HttpGetFieldNameAndValue (
1568 IN CHAR8 *String,
1569 OUT CHAR8 **FieldName,
1570 OUT CHAR8 **FieldValue
1571 )
1572 {
1573 CHAR8 *FieldNameStr;
1574 CHAR8 *FieldValueStr;
1575 CHAR8 *StrPtr;
1576 CHAR8 *EndofHeader;
1577
1578 if (String == NULL || FieldName == NULL || FieldValue == NULL) {
1579 return NULL;
1580 }
1581
1582 *FieldName = NULL;
1583 *FieldValue = NULL;
1584 FieldNameStr = NULL;
1585 FieldValueStr = NULL;
1586 StrPtr = NULL;
1587 EndofHeader = NULL;
1588
1589
1590 //
1591 // Check whether the raw HTTP header string is valid or not.
1592 //
1593 EndofHeader = AsciiStrStr (String, "\r\n\r\n");
1594 if (EndofHeader == NULL) {
1595 return NULL;
1596 }
1597
1598 //
1599 // Each header field consists of a name followed by a colon (":") and the field value.
1600 // The field value MAY be preceded by any amount of LWS, though a single SP is preferred.
1601 //
1602 // message-header = field-name ":" [ field-value ]
1603 // field-name = token
1604 // field-value = *( field-content | LWS )
1605 //
1606 // Note: "*(element)" allows any number element, including zero; "1*(element)" requires at least one element.
1607 // [element] means element is optional.
1608 // LWS = [CRLF] 1*(SP|HT), it can be ' ' or '\t' or '\r\n ' or '\r\n\t'.
1609 // CRLF = '\r\n'.
1610 // SP = ' '.
1611 // HT = '\t' (Tab).
1612 //
1613 FieldNameStr = String;
1614 FieldValueStr = AsciiStrGetNextToken (FieldNameStr, ':');
1615 if (FieldValueStr == NULL) {
1616 return NULL;
1617 }
1618
1619 //
1620 // Replace ':' with 0, then FieldName has been retrived from String.
1621 //
1622 *(FieldValueStr - 1) = 0;
1623
1624 //
1625 // Handle FieldValueStr, skip all the preceded LWS.
1626 //
1627 while (TRUE) {
1628 if (*FieldValueStr == ' ' || *FieldValueStr == '\t') {
1629 //
1630 // Boundary condition check.
1631 //
1632 if ((UINTN) EndofHeader - (UINTN) FieldValueStr < 1) {
1633 //
1634 // Wrong String format!
1635 //
1636 return NULL;
1637 }
1638
1639 FieldValueStr ++;
1640 } else if (*FieldValueStr == '\r') {
1641 //
1642 // Boundary condition check.
1643 //
1644 if ((UINTN) EndofHeader - (UINTN) FieldValueStr < 3) {
1645 //
1646 // No more preceded LWS, so break here.
1647 //
1648 break;
1649 }
1650
1651 if (*(FieldValueStr + 1) == '\n' ) {
1652 if (*(FieldValueStr + 2) == ' ' || *(FieldValueStr + 2) == '\t') {
1653 FieldValueStr = FieldValueStr + 3;
1654 } else {
1655 //
1656 // No more preceded LWS, so break here.
1657 //
1658 break;
1659 }
1660 } else {
1661 //
1662 // Wrong String format!
1663 //
1664 return NULL;
1665 }
1666 } else {
1667 //
1668 // No more preceded LWS, so break here.
1669 //
1670 break;
1671 }
1672 }
1673
1674 StrPtr = FieldValueStr;
1675 do {
1676 //
1677 // Handle the LWS within the field value.
1678 //
1679 StrPtr = AsciiStrGetNextToken (StrPtr, '\r');
1680 if (StrPtr == NULL || *StrPtr != '\n') {
1681 //
1682 // Wrong String format!
1683 //
1684 return NULL;
1685 }
1686
1687 StrPtr++;
1688 } while (*StrPtr == ' ' || *StrPtr == '\t');
1689
1690 //
1691 // Replace '\r' with 0
1692 //
1693 *(StrPtr - 2) = 0;
1694
1695 //
1696 // Get FieldName and FieldValue.
1697 //
1698 *FieldName = FieldNameStr;
1699 *FieldValue = FieldValueStr;
1700
1701 return StrPtr;
1702 }
1703
1704 /**
1705 Free existing HeaderFields.
1706
1707 @param[in] HeaderFields Pointer to array of key/value header pairs waitting for free.
1708 @param[in] FieldCount The number of header pairs in HeaderFields.
1709
1710 **/
1711 VOID
1712 EFIAPI
1713 HttpFreeHeaderFields (
1714 IN EFI_HTTP_HEADER *HeaderFields,
1715 IN UINTN FieldCount
1716 )
1717 {
1718 UINTN Index;
1719
1720 if (HeaderFields != NULL) {
1721 for (Index = 0; Index < FieldCount; Index++) {
1722 if (HeaderFields[Index].FieldName != NULL) {
1723 FreePool (HeaderFields[Index].FieldName);
1724 }
1725 if (HeaderFields[Index].FieldValue != NULL) {
1726 FreePool (HeaderFields[Index].FieldValue);
1727 }
1728 }
1729
1730 FreePool (HeaderFields);
1731 }
1732 }
1733
1734 /**
1735 Generate HTTP request message.
1736
1737 This function will allocate memory for the whole HTTP message and generate a
1738 well formatted HTTP Request message in it, include the Request-Line, header
1739 fields and also the message body. It is the caller's responsibility to free
1740 the buffer returned in *RequestMsg.
1741
1742 @param[in] Message Pointer to the EFI_HTTP_MESSAGE structure which
1743 contains the required information to generate
1744 the HTTP request message.
1745 @param[in] Url The URL of a remote host.
1746 @param[out] RequestMsg Pointer to the created HTTP request message.
1747 NULL if any error occured.
1748 @param[out] RequestMsgSize Size of the RequestMsg (in bytes).
1749
1750 @retval EFI_SUCCESS If HTTP request string was created successfully.
1751 @retval EFI_OUT_OF_RESOURCES Failed to allocate resources.
1752 @retval EFI_INVALID_PARAMETER The input arguments are invalid.
1753
1754 **/
1755 EFI_STATUS
1756 EFIAPI
1757 HttpGenRequestMessage (
1758 IN CONST EFI_HTTP_MESSAGE *Message,
1759 IN CONST CHAR8 *Url,
1760 OUT CHAR8 **RequestMsg,
1761 OUT UINTN *RequestMsgSize
1762 )
1763 {
1764 EFI_STATUS Status;
1765 UINTN StrLength;
1766 CHAR8 *RequestPtr;
1767 UINTN HttpHdrSize;
1768 UINTN MsgSize;
1769 BOOLEAN Success;
1770 VOID *HttpHdr;
1771 EFI_HTTP_HEADER **AppendList;
1772 UINTN Index;
1773 EFI_HTTP_UTILITIES_PROTOCOL *HttpUtilitiesProtocol;
1774
1775 Status = EFI_SUCCESS;
1776 HttpHdrSize = 0;
1777 MsgSize = 0;
1778 Success = FALSE;
1779 HttpHdr = NULL;
1780 AppendList = NULL;
1781 HttpUtilitiesProtocol = NULL;
1782
1783 //
1784 // 1. If we have a Request, we cannot have a NULL Url
1785 // 2. If we have a Request, HeaderCount can not be non-zero
1786 // 3. If we do not have a Request, HeaderCount should be zero
1787 // 4. If we do not have Request and Headers, we need at least a message-body
1788 //
1789 if ((Message == NULL || RequestMsg == NULL || RequestMsgSize == NULL) ||
1790 (Message->Data.Request != NULL && Url == NULL) ||
1791 (Message->Data.Request != NULL && Message->HeaderCount == 0) ||
1792 (Message->Data.Request == NULL && Message->HeaderCount != 0) ||
1793 (Message->Data.Request == NULL && Message->HeaderCount == 0 && Message->BodyLength == 0)) {
1794 return EFI_INVALID_PARAMETER;
1795 }
1796
1797 if (Message->HeaderCount != 0) {
1798 //
1799 // Locate the HTTP_UTILITIES protocol.
1800 //
1801 Status = gBS->LocateProtocol (
1802 &gEfiHttpUtilitiesProtocolGuid,
1803 NULL,
1804 (VOID **) &HttpUtilitiesProtocol
1805 );
1806
1807 if (EFI_ERROR (Status)) {
1808 DEBUG ((DEBUG_ERROR,"Failed to locate Http Utilities protocol. Status = %r.\n", Status));
1809 return Status;
1810 }
1811
1812 //
1813 // Build AppendList to send into HttpUtilitiesBuild
1814 //
1815 AppendList = AllocateZeroPool (sizeof (EFI_HTTP_HEADER *) * (Message->HeaderCount));
1816 if (AppendList == NULL) {
1817 return EFI_OUT_OF_RESOURCES;
1818 }
1819
1820 for(Index = 0; Index < Message->HeaderCount; Index++){
1821 AppendList[Index] = &Message->Headers[Index];
1822 }
1823
1824 //
1825 // Build raw HTTP Headers
1826 //
1827 Status = HttpUtilitiesProtocol->Build (
1828 HttpUtilitiesProtocol,
1829 0,
1830 NULL,
1831 0,
1832 NULL,
1833 Message->HeaderCount,
1834 AppendList,
1835 &HttpHdrSize,
1836 &HttpHdr
1837 );
1838
1839 FreePool (AppendList);
1840
1841 if (EFI_ERROR (Status) || HttpHdr == NULL){
1842 return Status;
1843 }
1844 }
1845
1846 //
1847 // If we have headers to be sent, account for it.
1848 //
1849 if (Message->HeaderCount != 0) {
1850 MsgSize = HttpHdrSize;
1851 }
1852
1853 //
1854 // If we have a request line, account for the fields.
1855 //
1856 if (Message->Data.Request != NULL) {
1857 MsgSize += HTTP_METHOD_MAXIMUM_LEN + AsciiStrLen (HTTP_VERSION_CRLF_STR) + AsciiStrLen (Url);
1858 }
1859
1860
1861 //
1862 // If we have a message body to be sent, account for it.
1863 //
1864 MsgSize += Message->BodyLength;
1865
1866 //
1867 // memory for the string that needs to be sent to TCP
1868 //
1869 *RequestMsg = NULL;
1870 *RequestMsg = AllocateZeroPool (MsgSize);
1871 if (*RequestMsg == NULL) {
1872 Status = EFI_OUT_OF_RESOURCES;
1873 goto Exit;
1874 }
1875
1876 RequestPtr = *RequestMsg;
1877 //
1878 // Construct header request
1879 //
1880 if (Message->Data.Request != NULL) {
1881 switch (Message->Data.Request->Method) {
1882 case HttpMethodGet:
1883 StrLength = sizeof (HTTP_METHOD_GET) - 1;
1884 CopyMem (RequestPtr, HTTP_METHOD_GET, StrLength);
1885 RequestPtr += StrLength;
1886 break;
1887 case HttpMethodPut:
1888 StrLength = sizeof (HTTP_METHOD_PUT) - 1;
1889 CopyMem (RequestPtr, HTTP_METHOD_PUT, StrLength);
1890 RequestPtr += StrLength;
1891 break;
1892 case HttpMethodPatch:
1893 StrLength = sizeof (HTTP_METHOD_PATCH) - 1;
1894 CopyMem (RequestPtr, HTTP_METHOD_PATCH, StrLength);
1895 RequestPtr += StrLength;
1896 break;
1897 case HttpMethodPost:
1898 StrLength = sizeof (HTTP_METHOD_POST) - 1;
1899 CopyMem (RequestPtr, HTTP_METHOD_POST, StrLength);
1900 RequestPtr += StrLength;
1901 break;
1902 case HttpMethodHead:
1903 StrLength = sizeof (HTTP_METHOD_HEAD) - 1;
1904 CopyMem (RequestPtr, HTTP_METHOD_HEAD, StrLength);
1905 RequestPtr += StrLength;
1906 break;
1907 case HttpMethodDelete:
1908 StrLength = sizeof (HTTP_METHOD_DELETE) - 1;
1909 CopyMem (RequestPtr, HTTP_METHOD_DELETE, StrLength);
1910 RequestPtr += StrLength;
1911 break;
1912 default:
1913 ASSERT (FALSE);
1914 Status = EFI_INVALID_PARAMETER;
1915 goto Exit;
1916 }
1917
1918 StrLength = AsciiStrLen(EMPTY_SPACE);
1919 CopyMem (RequestPtr, EMPTY_SPACE, StrLength);
1920 RequestPtr += StrLength;
1921
1922 StrLength = AsciiStrLen (Url);
1923 CopyMem (RequestPtr, Url, StrLength);
1924 RequestPtr += StrLength;
1925
1926 StrLength = sizeof (HTTP_VERSION_CRLF_STR) - 1;
1927 CopyMem (RequestPtr, HTTP_VERSION_CRLF_STR, StrLength);
1928 RequestPtr += StrLength;
1929
1930 if (HttpHdr != NULL) {
1931 //
1932 // Construct header
1933 //
1934 CopyMem (RequestPtr, HttpHdr, HttpHdrSize);
1935 RequestPtr += HttpHdrSize;
1936 }
1937 }
1938
1939 //
1940 // Construct body
1941 //
1942 if (Message->Body != NULL) {
1943 CopyMem (RequestPtr, Message->Body, Message->BodyLength);
1944 RequestPtr += Message->BodyLength;
1945 }
1946
1947 //
1948 // Done
1949 //
1950 (*RequestMsgSize) = (UINTN)(RequestPtr) - (UINTN)(*RequestMsg);
1951 Success = TRUE;
1952
1953 Exit:
1954
1955 if (!Success) {
1956 if (*RequestMsg != NULL) {
1957 FreePool (*RequestMsg);
1958 }
1959 *RequestMsg = NULL;
1960 return Status;
1961 }
1962
1963 if (HttpHdr != NULL) {
1964 FreePool (HttpHdr);
1965 }
1966
1967 return EFI_SUCCESS;
1968 }
1969
1970 /**
1971 Translate the status code in HTTP message to EFI_HTTP_STATUS_CODE defined
1972 in UEFI 2.5 specification.
1973
1974 @param[in] StatusCode The status code value in HTTP message.
1975
1976 @return Value defined in EFI_HTTP_STATUS_CODE .
1977
1978 **/
1979 EFI_HTTP_STATUS_CODE
1980 EFIAPI
1981 HttpMappingToStatusCode (
1982 IN UINTN StatusCode
1983 )
1984 {
1985 switch (StatusCode) {
1986 case 100:
1987 return HTTP_STATUS_100_CONTINUE;
1988 case 101:
1989 return HTTP_STATUS_101_SWITCHING_PROTOCOLS;
1990 case 200:
1991 return HTTP_STATUS_200_OK;
1992 case 201:
1993 return HTTP_STATUS_201_CREATED;
1994 case 202:
1995 return HTTP_STATUS_202_ACCEPTED;
1996 case 203:
1997 return HTTP_STATUS_203_NON_AUTHORITATIVE_INFORMATION;
1998 case 204:
1999 return HTTP_STATUS_204_NO_CONTENT;
2000 case 205:
2001 return HTTP_STATUS_205_RESET_CONTENT;
2002 case 206:
2003 return HTTP_STATUS_206_PARTIAL_CONTENT;
2004 case 300:
2005 return HTTP_STATUS_300_MULTIPLE_CHOICES;
2006 case 301:
2007 return HTTP_STATUS_301_MOVED_PERMANENTLY;
2008 case 302:
2009 return HTTP_STATUS_302_FOUND;
2010 case 303:
2011 return HTTP_STATUS_303_SEE_OTHER;
2012 case 304:
2013 return HTTP_STATUS_304_NOT_MODIFIED;
2014 case 305:
2015 return HTTP_STATUS_305_USE_PROXY;
2016 case 307:
2017 return HTTP_STATUS_307_TEMPORARY_REDIRECT;
2018 case 308:
2019 return HTTP_STATUS_308_PERMANENT_REDIRECT;
2020 case 400:
2021 return HTTP_STATUS_400_BAD_REQUEST;
2022 case 401:
2023 return HTTP_STATUS_401_UNAUTHORIZED;
2024 case 402:
2025 return HTTP_STATUS_402_PAYMENT_REQUIRED;
2026 case 403:
2027 return HTTP_STATUS_403_FORBIDDEN;
2028 case 404:
2029 return HTTP_STATUS_404_NOT_FOUND;
2030 case 405:
2031 return HTTP_STATUS_405_METHOD_NOT_ALLOWED;
2032 case 406:
2033 return HTTP_STATUS_406_NOT_ACCEPTABLE;
2034 case 407:
2035 return HTTP_STATUS_407_PROXY_AUTHENTICATION_REQUIRED;
2036 case 408:
2037 return HTTP_STATUS_408_REQUEST_TIME_OUT;
2038 case 409:
2039 return HTTP_STATUS_409_CONFLICT;
2040 case 410:
2041 return HTTP_STATUS_410_GONE;
2042 case 411:
2043 return HTTP_STATUS_411_LENGTH_REQUIRED;
2044 case 412:
2045 return HTTP_STATUS_412_PRECONDITION_FAILED;
2046 case 413:
2047 return HTTP_STATUS_413_REQUEST_ENTITY_TOO_LARGE;
2048 case 414:
2049 return HTTP_STATUS_414_REQUEST_URI_TOO_LARGE;
2050 case 415:
2051 return HTTP_STATUS_415_UNSUPPORTED_MEDIA_TYPE;
2052 case 416:
2053 return HTTP_STATUS_416_REQUESTED_RANGE_NOT_SATISFIED;
2054 case 417:
2055 return HTTP_STATUS_417_EXPECTATION_FAILED;
2056 case 500:
2057 return HTTP_STATUS_500_INTERNAL_SERVER_ERROR;
2058 case 501:
2059 return HTTP_STATUS_501_NOT_IMPLEMENTED;
2060 case 502:
2061 return HTTP_STATUS_502_BAD_GATEWAY;
2062 case 503:
2063 return HTTP_STATUS_503_SERVICE_UNAVAILABLE;
2064 case 504:
2065 return HTTP_STATUS_504_GATEWAY_TIME_OUT;
2066 case 505:
2067 return HTTP_STATUS_505_HTTP_VERSION_NOT_SUPPORTED;
2068
2069 default:
2070 return HTTP_STATUS_UNSUPPORTED_STATUS;
2071 }
2072 }
2073
2074 /**
2075 Check whether header field called FieldName is in DeleteList.
2076
2077 @param[in] DeleteList Pointer to array of key/value header pairs.
2078 @param[in] DeleteCount The number of header pairs.
2079 @param[in] FieldName Pointer to header field's name.
2080
2081 @return TRUE if FieldName is not in DeleteList, that means this header field is valid.
2082 @return FALSE if FieldName is in DeleteList, that means this header field is invalid.
2083
2084 **/
2085 BOOLEAN
2086 EFIAPI
2087 HttpIsValidHttpHeader (
2088 IN CHAR8 *DeleteList[],
2089 IN UINTN DeleteCount,
2090 IN CHAR8 *FieldName
2091 )
2092 {
2093 UINTN Index;
2094
2095 if (FieldName == NULL) {
2096 return FALSE;
2097 }
2098
2099 for (Index = 0; Index < DeleteCount; Index++) {
2100 if (DeleteList[Index] == NULL) {
2101 continue;
2102 }
2103
2104 if (AsciiStrCmp (FieldName, DeleteList[Index]) == 0) {
2105 return FALSE;
2106 }
2107 }
2108
2109 return TRUE;
2110 }
2111