]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeHttpLib/DxeHttpLib.c
MdeModulePkg: Clean up source files
[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 //
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 @retval 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 FreePool (AppendList);
1809
1810 if (EFI_ERROR (Status) || HttpHdr == NULL){
1811 return Status;
1812 }
1813 }
1814
1815 //
1816 // If we have headers to be sent, account for it.
1817 //
1818 if (Message->HeaderCount != 0) {
1819 MsgSize = HttpHdrSize;
1820 }
1821
1822 //
1823 // If we have a request line, account for the fields.
1824 //
1825 if (Message->Data.Request != NULL) {
1826 MsgSize += HTTP_METHOD_MAXIMUM_LEN + AsciiStrLen (HTTP_VERSION_CRLF_STR) + AsciiStrLen (Url);
1827 }
1828
1829
1830 //
1831 // If we have a message body to be sent, account for it.
1832 //
1833 MsgSize += Message->BodyLength;
1834
1835 //
1836 // memory for the string that needs to be sent to TCP
1837 //
1838 *RequestMsg = NULL;
1839 *RequestMsg = AllocateZeroPool (MsgSize);
1840 if (*RequestMsg == NULL) {
1841 Status = EFI_OUT_OF_RESOURCES;
1842 goto Exit;
1843 }
1844
1845 RequestPtr = *RequestMsg;
1846 //
1847 // Construct header request
1848 //
1849 if (Message->Data.Request != NULL) {
1850 switch (Message->Data.Request->Method) {
1851 case HttpMethodGet:
1852 StrLength = sizeof (HTTP_METHOD_GET) - 1;
1853 CopyMem (RequestPtr, HTTP_METHOD_GET, StrLength);
1854 RequestPtr += StrLength;
1855 break;
1856 case HttpMethodPut:
1857 StrLength = sizeof (HTTP_METHOD_PUT) - 1;
1858 CopyMem (RequestPtr, HTTP_METHOD_PUT, StrLength);
1859 RequestPtr += StrLength;
1860 break;
1861 case HttpMethodPatch:
1862 StrLength = sizeof (HTTP_METHOD_PATCH) - 1;
1863 CopyMem (RequestPtr, HTTP_METHOD_PATCH, StrLength);
1864 RequestPtr += StrLength;
1865 break;
1866 case HttpMethodPost:
1867 StrLength = sizeof (HTTP_METHOD_POST) - 1;
1868 CopyMem (RequestPtr, HTTP_METHOD_POST, StrLength);
1869 RequestPtr += StrLength;
1870 break;
1871 case HttpMethodHead:
1872 StrLength = sizeof (HTTP_METHOD_HEAD) - 1;
1873 CopyMem (RequestPtr, HTTP_METHOD_HEAD, StrLength);
1874 RequestPtr += StrLength;
1875 break;
1876 case HttpMethodDelete:
1877 StrLength = sizeof (HTTP_METHOD_DELETE) - 1;
1878 CopyMem (RequestPtr, HTTP_METHOD_DELETE, StrLength);
1879 RequestPtr += StrLength;
1880 break;
1881 default:
1882 ASSERT (FALSE);
1883 Status = EFI_INVALID_PARAMETER;
1884 goto Exit;
1885 }
1886
1887 StrLength = AsciiStrLen(EMPTY_SPACE);
1888 CopyMem (RequestPtr, EMPTY_SPACE, StrLength);
1889 RequestPtr += StrLength;
1890
1891 StrLength = AsciiStrLen (Url);
1892 CopyMem (RequestPtr, Url, StrLength);
1893 RequestPtr += StrLength;
1894
1895 StrLength = sizeof (HTTP_VERSION_CRLF_STR) - 1;
1896 CopyMem (RequestPtr, HTTP_VERSION_CRLF_STR, StrLength);
1897 RequestPtr += StrLength;
1898
1899 if (HttpHdr != NULL) {
1900 //
1901 // Construct header
1902 //
1903 CopyMem (RequestPtr, HttpHdr, HttpHdrSize);
1904 RequestPtr += HttpHdrSize;
1905 }
1906 }
1907
1908 //
1909 // Construct body
1910 //
1911 if (Message->Body != NULL) {
1912 CopyMem (RequestPtr, Message->Body, Message->BodyLength);
1913 RequestPtr += Message->BodyLength;
1914 }
1915
1916 //
1917 // Done
1918 //
1919 (*RequestMsgSize) = (UINTN)(RequestPtr) - (UINTN)(*RequestMsg);
1920 Success = TRUE;
1921
1922 Exit:
1923
1924 if (!Success) {
1925 if (*RequestMsg != NULL) {
1926 FreePool (*RequestMsg);
1927 }
1928 *RequestMsg = NULL;
1929 return Status;
1930 }
1931
1932 if (HttpHdr != NULL) {
1933 FreePool (HttpHdr);
1934 }
1935
1936 return EFI_SUCCESS;
1937 }
1938
1939 /**
1940 Translate the status code in HTTP message to EFI_HTTP_STATUS_CODE defined
1941 in UEFI 2.5 specification.
1942
1943 @param[in] StatusCode The status code value in HTTP message.
1944
1945 @return Value defined in EFI_HTTP_STATUS_CODE .
1946
1947 **/
1948 EFI_HTTP_STATUS_CODE
1949 EFIAPI
1950 HttpMappingToStatusCode (
1951 IN UINTN StatusCode
1952 )
1953 {
1954 switch (StatusCode) {
1955 case 100:
1956 return HTTP_STATUS_100_CONTINUE;
1957 case 101:
1958 return HTTP_STATUS_101_SWITCHING_PROTOCOLS;
1959 case 200:
1960 return HTTP_STATUS_200_OK;
1961 case 201:
1962 return HTTP_STATUS_201_CREATED;
1963 case 202:
1964 return HTTP_STATUS_202_ACCEPTED;
1965 case 203:
1966 return HTTP_STATUS_203_NON_AUTHORITATIVE_INFORMATION;
1967 case 204:
1968 return HTTP_STATUS_204_NO_CONTENT;
1969 case 205:
1970 return HTTP_STATUS_205_RESET_CONTENT;
1971 case 206:
1972 return HTTP_STATUS_206_PARTIAL_CONTENT;
1973 case 300:
1974 return HTTP_STATUS_300_MULTIPLE_CHOICES;
1975 case 301:
1976 return HTTP_STATUS_301_MOVED_PERMANENTLY;
1977 case 302:
1978 return HTTP_STATUS_302_FOUND;
1979 case 303:
1980 return HTTP_STATUS_303_SEE_OTHER;
1981 case 304:
1982 return HTTP_STATUS_304_NOT_MODIFIED;
1983 case 305:
1984 return HTTP_STATUS_305_USE_PROXY;
1985 case 307:
1986 return HTTP_STATUS_307_TEMPORARY_REDIRECT;
1987 case 308:
1988 return HTTP_STATUS_308_PERMANENT_REDIRECT;
1989 case 400:
1990 return HTTP_STATUS_400_BAD_REQUEST;
1991 case 401:
1992 return HTTP_STATUS_401_UNAUTHORIZED;
1993 case 402:
1994 return HTTP_STATUS_402_PAYMENT_REQUIRED;
1995 case 403:
1996 return HTTP_STATUS_403_FORBIDDEN;
1997 case 404:
1998 return HTTP_STATUS_404_NOT_FOUND;
1999 case 405:
2000 return HTTP_STATUS_405_METHOD_NOT_ALLOWED;
2001 case 406:
2002 return HTTP_STATUS_406_NOT_ACCEPTABLE;
2003 case 407:
2004 return HTTP_STATUS_407_PROXY_AUTHENTICATION_REQUIRED;
2005 case 408:
2006 return HTTP_STATUS_408_REQUEST_TIME_OUT;
2007 case 409:
2008 return HTTP_STATUS_409_CONFLICT;
2009 case 410:
2010 return HTTP_STATUS_410_GONE;
2011 case 411:
2012 return HTTP_STATUS_411_LENGTH_REQUIRED;
2013 case 412:
2014 return HTTP_STATUS_412_PRECONDITION_FAILED;
2015 case 413:
2016 return HTTP_STATUS_413_REQUEST_ENTITY_TOO_LARGE;
2017 case 414:
2018 return HTTP_STATUS_414_REQUEST_URI_TOO_LARGE;
2019 case 415:
2020 return HTTP_STATUS_415_UNSUPPORTED_MEDIA_TYPE;
2021 case 416:
2022 return HTTP_STATUS_416_REQUESTED_RANGE_NOT_SATISFIED;
2023 case 417:
2024 return HTTP_STATUS_417_EXPECTATION_FAILED;
2025 case 500:
2026 return HTTP_STATUS_500_INTERNAL_SERVER_ERROR;
2027 case 501:
2028 return HTTP_STATUS_501_NOT_IMPLEMENTED;
2029 case 502:
2030 return HTTP_STATUS_502_BAD_GATEWAY;
2031 case 503:
2032 return HTTP_STATUS_503_SERVICE_UNAVAILABLE;
2033 case 504:
2034 return HTTP_STATUS_504_GATEWAY_TIME_OUT;
2035 case 505:
2036 return HTTP_STATUS_505_HTTP_VERSION_NOT_SUPPORTED;
2037
2038 default:
2039 return HTTP_STATUS_UNSUPPORTED_STATUS;
2040 }
2041 }
2042
2043 /**
2044 Check whether header field called FieldName is in DeleteList.
2045
2046 @param[in] DeleteList Pointer to array of key/value header pairs.
2047 @param[in] DeleteCount The number of header pairs.
2048 @param[in] FieldName Pointer to header field's name.
2049
2050 @return TRUE if FieldName is not in DeleteList, that means this header field is valid.
2051 @return FALSE if FieldName is in DeleteList, that means this header field is invalid.
2052
2053 **/
2054 BOOLEAN
2055 EFIAPI
2056 HttpIsValidHttpHeader (
2057 IN CHAR8 *DeleteList[],
2058 IN UINTN DeleteCount,
2059 IN CHAR8 *FieldName
2060 )
2061 {
2062 UINTN Index;
2063
2064 if (FieldName == NULL) {
2065 return FALSE;
2066 }
2067
2068 for (Index = 0; Index < DeleteCount; Index++) {
2069 if (DeleteList[Index] == NULL) {
2070 continue;
2071 }
2072
2073 if (AsciiStrCmp (FieldName, DeleteList[Index]) == 0) {
2074 return FALSE;
2075 }
2076 }
2077
2078 return TRUE;
2079 }
2080