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