]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeHttpLib/DxeHttpLib.c
MdeModulePkg/DxeHttpLib: Check the input parameters for some APIs.
[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 Other Error happened.
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_INVALID_PARAMETER;
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_INVALID_PARAMETER;
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_INVALID_PARAMETER;
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 Others Operation aborted.
1137
1138 **/
1139 EFI_STATUS
1140 EFIAPI
1141 HttpParseMessageBody (
1142 IN OUT VOID *MsgParser,
1143 IN UINTN BodyLength,
1144 IN CHAR8 *Body
1145 )
1146 {
1147 CHAR8 *Char;
1148 UINTN RemainderLengthInThis;
1149 UINTN LengthForCallback;
1150 EFI_STATUS Status;
1151 HTTP_BODY_PARSER *Parser;
1152
1153 if (BodyLength == 0 || Body == NULL) {
1154 return EFI_INVALID_PARAMETER;
1155 }
1156
1157 if (MsgParser == NULL) {
1158 return EFI_INVALID_PARAMETER;
1159 }
1160
1161 Parser = (HTTP_BODY_PARSER*) MsgParser;
1162
1163 if (Parser->IgnoreBody) {
1164 Parser->State = BodyParserComplete;
1165 if (Parser->Callback != NULL) {
1166 Status = Parser->Callback (
1167 BodyParseEventOnComplete,
1168 Body,
1169 0,
1170 Parser->Context
1171 );
1172 if (EFI_ERROR (Status)) {
1173 return Status;
1174 }
1175 }
1176 return EFI_SUCCESS;
1177 }
1178
1179 if (Parser->State == BodyParserBodyStart) {
1180 Parser->ParsedBodyLength = 0;
1181 if (Parser->IsChunked) {
1182 Parser->State = BodyParserChunkSizeStart;
1183 } else {
1184 Parser->State = BodyParserBodyIdentity;
1185 }
1186 }
1187
1188 //
1189 // The message body might be truncated in anywhere, so we need to parse is byte-by-byte.
1190 //
1191 for (Char = Body; Char < Body + BodyLength; ) {
1192
1193 switch (Parser->State) {
1194 case BodyParserStateMax:
1195 return EFI_ABORTED;
1196
1197 case BodyParserBodyIdentity:
1198 //
1199 // Identity transfer-coding, just notify user to save the body data.
1200 //
1201 if (Parser->Callback != NULL) {
1202 Status = Parser->Callback (
1203 BodyParseEventOnData,
1204 Char,
1205 MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength),
1206 Parser->Context
1207 );
1208 if (EFI_ERROR (Status)) {
1209 return Status;
1210 }
1211 }
1212 Char += MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength);
1213 Parser->ParsedBodyLength += MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength);
1214 if (Parser->ParsedBodyLength == Parser->ContentLength) {
1215 Parser->State = BodyParserComplete;
1216 if (Parser->Callback != NULL) {
1217 Status = Parser->Callback (
1218 BodyParseEventOnComplete,
1219 Char,
1220 0,
1221 Parser->Context
1222 );
1223 if (EFI_ERROR (Status)) {
1224 return Status;
1225 }
1226 }
1227 }
1228 break;
1229
1230 case BodyParserChunkSizeStart:
1231 //
1232 // First byte of chunk-size, the chunk-size might be truncated.
1233 //
1234 Parser->CurrentChunkSize = 0;
1235 Parser->State = BodyParserChunkSize;
1236 case BodyParserChunkSize:
1237 if (!NET_IS_HEX_CHAR (*Char)) {
1238 if (*Char == ';') {
1239 Parser->State = BodyParserChunkExtStart;
1240 Char++;
1241 } else if (*Char == '\r') {
1242 Parser->State = BodyParserChunkSizeEndCR;
1243 Char++;
1244 } else {
1245 Parser->State = BodyParserStateMax;
1246 }
1247 break;
1248 }
1249
1250 if (Parser->CurrentChunkSize > (((~((UINTN) 0)) - 16) / 16)) {
1251 return EFI_INVALID_PARAMETER;
1252 }
1253 Parser->CurrentChunkSize = Parser->CurrentChunkSize * 16 + HttpIoHexCharToUintn (*Char);
1254 Char++;
1255 break;
1256
1257 case BodyParserChunkExtStart:
1258 //
1259 // Ignore all the chunk extensions.
1260 //
1261 if (*Char == '\r') {
1262 Parser->State = BodyParserChunkSizeEndCR;
1263 }
1264 Char++;
1265 break;
1266
1267 case BodyParserChunkSizeEndCR:
1268 if (*Char != '\n') {
1269 Parser->State = BodyParserStateMax;
1270 break;
1271 }
1272 Char++;
1273 if (Parser->CurrentChunkSize == 0) {
1274 //
1275 // The last chunk has been parsed and now assumed the state
1276 // of HttpBodyParse is ParserLastCRLF. So it need to decide
1277 // whether the rest message is trailer or last CRLF in the next round.
1278 //
1279 Parser->ContentLengthIsValid = TRUE;
1280 Parser->State = BodyParserLastCRLF;
1281 break;
1282 }
1283 Parser->State = BodyParserChunkDataStart;
1284 Parser->CurrentChunkParsedSize = 0;
1285 break;
1286
1287 case BodyParserLastCRLF:
1288 //
1289 // Judge the byte is belong to the Last CRLF or trailer, and then
1290 // configure the state of HttpBodyParse to corresponding state.
1291 //
1292 if (*Char == '\r') {
1293 Char++;
1294 Parser->State = BodyParserLastCRLFEnd;
1295 break;
1296 } else {
1297 Parser->State = BodyParserTrailer;
1298 break;
1299 }
1300
1301 case BodyParserLastCRLFEnd:
1302 if (*Char == '\n') {
1303 Parser->State = BodyParserComplete;
1304 Char++;
1305 if (Parser->Callback != NULL) {
1306 Status = Parser->Callback (
1307 BodyParseEventOnComplete,
1308 Char,
1309 0,
1310 Parser->Context
1311 );
1312 if (EFI_ERROR (Status)) {
1313 return Status;
1314 }
1315 }
1316 break;
1317 } else {
1318 Parser->State = BodyParserStateMax;
1319 break;
1320 }
1321
1322 case BodyParserTrailer:
1323 if (*Char == '\r') {
1324 Parser->State = BodyParserChunkSizeEndCR;
1325 }
1326 Char++;
1327 break;
1328
1329 case BodyParserChunkDataStart:
1330 //
1331 // First byte of chunk-data, the chunk data also might be truncated.
1332 //
1333 RemainderLengthInThis = BodyLength - (Char - Body);
1334 LengthForCallback = MIN (Parser->CurrentChunkSize - Parser->CurrentChunkParsedSize, RemainderLengthInThis);
1335 if (Parser->Callback != NULL) {
1336 Status = Parser->Callback (
1337 BodyParseEventOnData,
1338 Char,
1339 LengthForCallback,
1340 Parser->Context
1341 );
1342 if (EFI_ERROR (Status)) {
1343 return Status;
1344 }
1345 }
1346 Char += LengthForCallback;
1347 Parser->ContentLength += LengthForCallback;
1348 Parser->CurrentChunkParsedSize += LengthForCallback;
1349 if (Parser->CurrentChunkParsedSize == Parser->CurrentChunkSize) {
1350 Parser->State = BodyParserChunkDataEnd;
1351 }
1352 break;
1353
1354 case BodyParserChunkDataEnd:
1355 if (*Char == '\r') {
1356 Parser->State = BodyParserChunkDataEndCR;
1357 } else {
1358 Parser->State = BodyParserStateMax;
1359 }
1360 Char++;
1361 break;
1362
1363 case BodyParserChunkDataEndCR:
1364 if (*Char != '\n') {
1365 Parser->State = BodyParserStateMax;
1366 break;
1367 }
1368 Char++;
1369 Parser->State = BodyParserChunkSizeStart;
1370 break;
1371
1372 default:
1373 break;
1374 }
1375
1376 }
1377
1378 if (Parser->State == BodyParserStateMax) {
1379 return EFI_ABORTED;
1380 }
1381
1382 return EFI_SUCCESS;
1383 }
1384
1385 /**
1386 Check whether the message-body is complete or not.
1387
1388 @param[in] MsgParser Pointer to the message parser.
1389
1390 @retval TRUE Message-body is complete.
1391 @retval FALSE Message-body is not complete.
1392
1393 **/
1394 BOOLEAN
1395 EFIAPI
1396 HttpIsMessageComplete (
1397 IN VOID *MsgParser
1398 )
1399 {
1400 HTTP_BODY_PARSER *Parser;
1401
1402 if (MsgParser == NULL) {
1403 return FALSE;
1404 }
1405
1406 Parser = (HTTP_BODY_PARSER*) MsgParser;
1407
1408 if (Parser->State == BodyParserComplete) {
1409 return TRUE;
1410 }
1411 return FALSE;
1412 }
1413
1414 /**
1415 Get the content length of the entity.
1416
1417 Note that in trunk transfer, the entity length is not valid until the whole message body is received.
1418
1419 @param[in] MsgParser Pointer to the message parser.
1420 @param[out] ContentLength Pointer to store the length of the entity.
1421
1422 @retval EFI_SUCCESS Successfully to get the entity length.
1423 @retval EFI_NOT_READY Entity length is not valid yet.
1424 @retval EFI_INVALID_PARAMETER MsgParser is NULL or ContentLength is NULL.
1425
1426 **/
1427 EFI_STATUS
1428 EFIAPI
1429 HttpGetEntityLength (
1430 IN VOID *MsgParser,
1431 OUT UINTN *ContentLength
1432 )
1433 {
1434 HTTP_BODY_PARSER *Parser;
1435
1436 if (MsgParser == NULL || ContentLength == NULL) {
1437 return EFI_INVALID_PARAMETER;
1438 }
1439
1440 Parser = (HTTP_BODY_PARSER*) MsgParser;
1441
1442 if (!Parser->ContentLengthIsValid) {
1443 return EFI_NOT_READY;
1444 }
1445
1446 *ContentLength = Parser->ContentLength;
1447 return EFI_SUCCESS;
1448 }
1449
1450 /**
1451 Release the resource of the message parser.
1452
1453 @param[in] MsgParser Pointer to the message parser.
1454
1455 **/
1456 VOID
1457 EFIAPI
1458 HttpFreeMsgParser (
1459 IN VOID *MsgParser
1460 )
1461 {
1462 FreePool (MsgParser);
1463 }
1464
1465
1466 /**
1467 Get the next string, which is distinguished by specified separator.
1468
1469 @param[in] String Pointer to the string.
1470 @param[in] Separator Specified separator used to distinguish where is the beginning
1471 of next string.
1472
1473 @return Pointer to the next string.
1474 @return NULL if not find or String is NULL.
1475
1476 **/
1477 CHAR8 *
1478 EFIAPI
1479 AsciiStrGetNextToken (
1480 IN CONST CHAR8 *String,
1481 IN CHAR8 Separator
1482 )
1483 {
1484 CONST CHAR8 *Token;
1485
1486 Token = String;
1487 while (TRUE) {
1488 if (*Token == 0) {
1489 return NULL;
1490 }
1491 if (*Token == Separator) {
1492 return (CHAR8 *)(Token + 1);
1493 }
1494 Token++;
1495 }
1496 }
1497
1498 /**
1499 Set FieldName and FieldValue into specified HttpHeader.
1500
1501 @param[in,out] HttpHeader Specified HttpHeader.
1502 @param[in] FieldName FieldName of this HttpHeader, a NULL terminated ASCII string.
1503 @param[in] FieldValue FieldValue of this HttpHeader, a NULL terminated ASCII string.
1504
1505
1506 @retval EFI_SUCCESS The FieldName and FieldValue are set into HttpHeader successfully.
1507 @retval EFI_INVALID_PARAMETER The parameter is invalid.
1508 @retval EFI_OUT_OF_RESOURCES Failed to allocate resources.
1509
1510 **/
1511 EFI_STATUS
1512 EFIAPI
1513 HttpSetFieldNameAndValue (
1514 IN OUT EFI_HTTP_HEADER *HttpHeader,
1515 IN CONST CHAR8 *FieldName,
1516 IN CONST CHAR8 *FieldValue
1517 )
1518 {
1519 UINTN FieldNameSize;
1520 UINTN FieldValueSize;
1521
1522 if (HttpHeader == NULL || FieldName == NULL || FieldValue == NULL) {
1523 return EFI_INVALID_PARAMETER;
1524 }
1525
1526 if (HttpHeader->FieldName != NULL) {
1527 FreePool (HttpHeader->FieldName);
1528 }
1529 if (HttpHeader->FieldValue != NULL) {
1530 FreePool (HttpHeader->FieldValue);
1531 }
1532
1533 FieldNameSize = AsciiStrSize (FieldName);
1534 HttpHeader->FieldName = AllocateZeroPool (FieldNameSize);
1535 if (HttpHeader->FieldName == NULL) {
1536 return EFI_OUT_OF_RESOURCES;
1537 }
1538 CopyMem (HttpHeader->FieldName, FieldName, FieldNameSize);
1539 HttpHeader->FieldName[FieldNameSize - 1] = 0;
1540
1541 FieldValueSize = AsciiStrSize (FieldValue);
1542 HttpHeader->FieldValue = AllocateZeroPool (FieldValueSize);
1543 if (HttpHeader->FieldValue == NULL) {
1544 FreePool (HttpHeader->FieldName);
1545 return EFI_OUT_OF_RESOURCES;
1546 }
1547 CopyMem (HttpHeader->FieldValue, FieldValue, FieldValueSize);
1548 HttpHeader->FieldValue[FieldValueSize - 1] = 0;
1549
1550 return EFI_SUCCESS;
1551 }
1552
1553 /**
1554 Get one key/value header pair from the raw string.
1555
1556 @param[in] String Pointer to the raw string.
1557 @param[out] FieldName Points directly to field name within 'HttpHeader'.
1558 @param[out] FieldValue Points directly to field value within 'HttpHeader'.
1559
1560 @return Pointer to the next raw string.
1561 @return NULL if no key/value header pair from this raw string.
1562
1563 **/
1564 CHAR8 *
1565 EFIAPI
1566 HttpGetFieldNameAndValue (
1567 IN CHAR8 *String,
1568 OUT CHAR8 **FieldName,
1569 OUT CHAR8 **FieldValue
1570 )
1571 {
1572 CHAR8 *FieldNameStr;
1573 CHAR8 *FieldValueStr;
1574 CHAR8 *StrPtr;
1575 CHAR8 *EndofHeader;
1576
1577 if (String == NULL || FieldName == NULL || FieldValue == NULL) {
1578 return NULL;
1579 }
1580
1581 *FieldName = NULL;
1582 *FieldValue = NULL;
1583 FieldNameStr = NULL;
1584 FieldValueStr = NULL;
1585 StrPtr = NULL;
1586 EndofHeader = NULL;
1587
1588
1589 //
1590 // Check whether the raw HTTP header string is valid or not.
1591 //
1592 EndofHeader = AsciiStrStr (String, "\r\n\r\n");
1593 if (EndofHeader == NULL) {
1594 return NULL;
1595 }
1596
1597 //
1598 // Each header field consists of a name followed by a colon (":") and the field value.
1599 //
1600 FieldNameStr = String;
1601 FieldValueStr = AsciiStrGetNextToken (FieldNameStr, ':');
1602 if (FieldValueStr == NULL) {
1603 return NULL;
1604 }
1605
1606 //
1607 // Replace ':' with 0
1608 //
1609 *(FieldValueStr - 1) = 0;
1610
1611 //
1612 // The field value MAY be preceded by any amount of LWS, though a single SP is preferred.
1613 // Note: LWS = [CRLF] 1*(SP|HT), it can be '\r\n ' or '\r\n\t' or ' ' or '\t'.
1614 // CRLF = '\r\n'.
1615 // SP = ' '.
1616 // HT = '\t' (Tab).
1617 //
1618 while (TRUE) {
1619 if (*FieldValueStr == ' ' || *FieldValueStr == '\t') {
1620 //
1621 // Boundary condition check.
1622 //
1623 if ((UINTN)EndofHeader - (UINTN)(FieldValueStr) < 1) {
1624 return NULL;
1625 }
1626
1627 FieldValueStr ++;
1628 } else if (*FieldValueStr == '\r') {
1629 //
1630 // Boundary condition check.
1631 //
1632 if ((UINTN)EndofHeader - (UINTN)(FieldValueStr) < 3) {
1633 return NULL;
1634 }
1635
1636 if (*(FieldValueStr + 1) == '\n' && (*(FieldValueStr + 2) == ' ' || *(FieldValueStr + 2) == '\t')) {
1637 FieldValueStr = FieldValueStr + 3;
1638 }
1639 } else {
1640 break;
1641 }
1642 }
1643
1644 //
1645 // Header fields can be extended over multiple lines by preceding each extra
1646 // line with at least one SP or HT.
1647 //
1648 StrPtr = FieldValueStr;
1649 do {
1650 StrPtr = AsciiStrGetNextToken (StrPtr, '\r');
1651 if (StrPtr == NULL || *StrPtr != '\n') {
1652 return NULL;
1653 }
1654
1655 StrPtr++;
1656 } while (*StrPtr == ' ' || *StrPtr == '\t');
1657
1658 //
1659 // Replace '\r' with 0
1660 //
1661 *(StrPtr - 2) = 0;
1662
1663 //
1664 // Get FieldName and FieldValue.
1665 //
1666 *FieldName = FieldNameStr;
1667 *FieldValue = FieldValueStr;
1668
1669 return StrPtr;
1670 }
1671
1672 /**
1673 Free existing HeaderFields.
1674
1675 @param[in] HeaderFields Pointer to array of key/value header pairs waitting for free.
1676 @param[in] FieldCount The number of header pairs in HeaderFields.
1677
1678 **/
1679 VOID
1680 EFIAPI
1681 HttpFreeHeaderFields (
1682 IN EFI_HTTP_HEADER *HeaderFields,
1683 IN UINTN FieldCount
1684 )
1685 {
1686 UINTN Index;
1687
1688 if (HeaderFields != NULL) {
1689 for (Index = 0; Index < FieldCount; Index++) {
1690 if (HeaderFields[Index].FieldName != NULL) {
1691 FreePool (HeaderFields[Index].FieldName);
1692 }
1693 if (HeaderFields[Index].FieldValue != NULL) {
1694 FreePool (HeaderFields[Index].FieldValue);
1695 }
1696 }
1697
1698 FreePool (HeaderFields);
1699 }
1700 }
1701
1702 /**
1703 Generate HTTP request message.
1704
1705 This function will allocate memory for the whole HTTP message and generate a
1706 well formatted HTTP Request message in it, include the Request-Line, header
1707 fields and also the message body. It is the caller's responsibility to free
1708 the buffer returned in *RequestMsg.
1709
1710 @param[in] Message Pointer to the EFI_HTTP_MESSAGE structure which
1711 contains the required information to generate
1712 the HTTP request message.
1713 @param[in] Url The URL of a remote host.
1714 @param[out] RequestMsg Pointer to the created HTTP request message.
1715 NULL if any error occured.
1716 @param[out] RequestMsgSize Size of the RequestMsg (in bytes).
1717
1718 @return EFI_SUCCESS If HTTP request string was created successfully
1719 @retval EFI_OUT_OF_RESOURCES Failed to allocate resources.
1720 @retval EFI_INVALID_PARAMETER The input arguments are invalid
1721
1722 **/
1723 EFI_STATUS
1724 EFIAPI
1725 HttpGenRequestMessage (
1726 IN CONST EFI_HTTP_MESSAGE *Message,
1727 IN CONST CHAR8 *Url,
1728 OUT CHAR8 **RequestMsg,
1729 OUT UINTN *RequestMsgSize
1730 )
1731 {
1732 EFI_STATUS Status;
1733 UINTN StrLength;
1734 CHAR8 *RequestPtr;
1735 UINTN HttpHdrSize;
1736 UINTN MsgSize;
1737 BOOLEAN Success;
1738 VOID *HttpHdr;
1739 EFI_HTTP_HEADER **AppendList;
1740 UINTN Index;
1741 EFI_HTTP_UTILITIES_PROTOCOL *HttpUtilitiesProtocol;
1742
1743 Status = EFI_SUCCESS;
1744 HttpHdrSize = 0;
1745 MsgSize = 0;
1746 Success = FALSE;
1747 HttpHdr = NULL;
1748 AppendList = NULL;
1749 HttpUtilitiesProtocol = NULL;
1750
1751 //
1752 // 1. If we have a Request, we cannot have a NULL Url
1753 // 2. If we have a Request, HeaderCount can not be non-zero
1754 // 3. If we do not have a Request, HeaderCount should be zero
1755 // 4. If we do not have Request and Headers, we need at least a message-body
1756 //
1757 if ((Message == NULL || RequestMsg == NULL || RequestMsgSize == NULL) ||
1758 (Message->Data.Request != NULL && Url == NULL) ||
1759 (Message->Data.Request != NULL && Message->HeaderCount == 0) ||
1760 (Message->Data.Request == NULL && Message->HeaderCount != 0) ||
1761 (Message->Data.Request == NULL && Message->HeaderCount == 0 && Message->BodyLength == 0)) {
1762 return EFI_INVALID_PARAMETER;
1763 }
1764
1765 if (Message->HeaderCount != 0) {
1766 //
1767 // Locate the HTTP_UTILITIES protocol.
1768 //
1769 Status = gBS->LocateProtocol (
1770 &gEfiHttpUtilitiesProtocolGuid,
1771 NULL,
1772 (VOID **)&HttpUtilitiesProtocol
1773 );
1774
1775 if (EFI_ERROR (Status)) {
1776 DEBUG ((DEBUG_ERROR,"Failed to locate Http Utilities protocol. Status = %r.\n", Status));
1777 return Status;
1778 }
1779
1780 //
1781 // Build AppendList to send into HttpUtilitiesBuild
1782 //
1783 AppendList = AllocateZeroPool (sizeof (EFI_HTTP_HEADER *) * (Message->HeaderCount));
1784 if (AppendList == NULL) {
1785 return EFI_OUT_OF_RESOURCES;
1786 }
1787
1788 for(Index = 0; Index < Message->HeaderCount; Index++){
1789 AppendList[Index] = &Message->Headers[Index];
1790 }
1791
1792 //
1793 // Build raw HTTP Headers
1794 //
1795 Status = HttpUtilitiesProtocol->Build (
1796 HttpUtilitiesProtocol,
1797 0,
1798 NULL,
1799 0,
1800 NULL,
1801 Message->HeaderCount,
1802 AppendList,
1803 &HttpHdrSize,
1804 &HttpHdr
1805 );
1806
1807 if (AppendList != NULL) {
1808 FreePool (AppendList);
1809 }
1810
1811 if (EFI_ERROR (Status) || HttpHdr == NULL){
1812 return Status;
1813 }
1814 }
1815
1816 //
1817 // If we have headers to be sent, account for it.
1818 //
1819 if (Message->HeaderCount != 0) {
1820 MsgSize = HttpHdrSize;
1821 }
1822
1823 //
1824 // If we have a request line, account for the fields.
1825 //
1826 if (Message->Data.Request != NULL) {
1827 MsgSize += HTTP_METHOD_MAXIMUM_LEN + AsciiStrLen (HTTP_VERSION_CRLF_STR) + AsciiStrLen (Url);
1828 }
1829
1830
1831 //
1832 // If we have a message body to be sent, account for it.
1833 //
1834 MsgSize += Message->BodyLength;
1835
1836 //
1837 // memory for the string that needs to be sent to TCP
1838 //
1839 *RequestMsg = NULL;
1840 *RequestMsg = AllocateZeroPool (MsgSize);
1841 if (*RequestMsg == NULL) {
1842 Status = EFI_OUT_OF_RESOURCES;
1843 goto Exit;
1844 }
1845
1846 RequestPtr = *RequestMsg;
1847 //
1848 // Construct header request
1849 //
1850 if (Message->Data.Request != NULL) {
1851 switch (Message->Data.Request->Method) {
1852 case HttpMethodGet:
1853 StrLength = sizeof (HTTP_METHOD_GET) - 1;
1854 CopyMem (RequestPtr, HTTP_METHOD_GET, StrLength);
1855 RequestPtr += StrLength;
1856 break;
1857 case HttpMethodPut:
1858 StrLength = sizeof (HTTP_METHOD_PUT) - 1;
1859 CopyMem (RequestPtr, HTTP_METHOD_PUT, StrLength);
1860 RequestPtr += StrLength;
1861 break;
1862 case HttpMethodPatch:
1863 StrLength = sizeof (HTTP_METHOD_PATCH) - 1;
1864 CopyMem (RequestPtr, HTTP_METHOD_PATCH, StrLength);
1865 RequestPtr += StrLength;
1866 break;
1867 case HttpMethodPost:
1868 StrLength = sizeof (HTTP_METHOD_POST) - 1;
1869 CopyMem (RequestPtr, HTTP_METHOD_POST, StrLength);
1870 RequestPtr += StrLength;
1871 break;
1872 case HttpMethodHead:
1873 StrLength = sizeof (HTTP_METHOD_HEAD) - 1;
1874 CopyMem (RequestPtr, HTTP_METHOD_HEAD, StrLength);
1875 RequestPtr += StrLength;
1876 break;
1877 case HttpMethodDelete:
1878 StrLength = sizeof (HTTP_METHOD_DELETE) - 1;
1879 CopyMem (RequestPtr, HTTP_METHOD_DELETE, StrLength);
1880 RequestPtr += StrLength;
1881 break;
1882 default:
1883 ASSERT (FALSE);
1884 Status = EFI_INVALID_PARAMETER;
1885 goto Exit;
1886 }
1887
1888 StrLength = AsciiStrLen(EMPTY_SPACE);
1889 CopyMem (RequestPtr, EMPTY_SPACE, StrLength);
1890 RequestPtr += StrLength;
1891
1892 StrLength = AsciiStrLen (Url);
1893 CopyMem (RequestPtr, Url, StrLength);
1894 RequestPtr += StrLength;
1895
1896 StrLength = sizeof (HTTP_VERSION_CRLF_STR) - 1;
1897 CopyMem (RequestPtr, HTTP_VERSION_CRLF_STR, StrLength);
1898 RequestPtr += StrLength;
1899
1900 if (HttpHdr != NULL) {
1901 //
1902 // Construct header
1903 //
1904 CopyMem (RequestPtr, HttpHdr, HttpHdrSize);
1905 RequestPtr += HttpHdrSize;
1906 }
1907 }
1908
1909 //
1910 // Construct body
1911 //
1912 if (Message->Body != NULL) {
1913 CopyMem (RequestPtr, Message->Body, Message->BodyLength);
1914 RequestPtr += Message->BodyLength;
1915 }
1916
1917 //
1918 // Done
1919 //
1920 (*RequestMsgSize) = (UINTN)(RequestPtr) - (UINTN)(*RequestMsg);
1921 Success = TRUE;
1922
1923 Exit:
1924
1925 if (!Success) {
1926 if (*RequestMsg != NULL) {
1927 FreePool (*RequestMsg);
1928 }
1929 *RequestMsg = NULL;
1930 return Status;
1931 }
1932
1933 if (HttpHdr != NULL) {
1934 FreePool (HttpHdr);
1935 }
1936
1937 return EFI_SUCCESS;
1938 }
1939
1940 /**
1941 Translate the status code in HTTP message to EFI_HTTP_STATUS_CODE defined
1942 in UEFI 2.5 specification.
1943
1944 @param[in] StatusCode The status code value in HTTP message.
1945
1946 @return Value defined in EFI_HTTP_STATUS_CODE .
1947
1948 **/
1949 EFI_HTTP_STATUS_CODE
1950 EFIAPI
1951 HttpMappingToStatusCode (
1952 IN UINTN StatusCode
1953 )
1954 {
1955 switch (StatusCode) {
1956 case 100:
1957 return HTTP_STATUS_100_CONTINUE;
1958 case 101:
1959 return HTTP_STATUS_101_SWITCHING_PROTOCOLS;
1960 case 200:
1961 return HTTP_STATUS_200_OK;
1962 case 201:
1963 return HTTP_STATUS_201_CREATED;
1964 case 202:
1965 return HTTP_STATUS_202_ACCEPTED;
1966 case 203:
1967 return HTTP_STATUS_203_NON_AUTHORITATIVE_INFORMATION;
1968 case 204:
1969 return HTTP_STATUS_204_NO_CONTENT;
1970 case 205:
1971 return HTTP_STATUS_205_RESET_CONTENT;
1972 case 206:
1973 return HTTP_STATUS_206_PARTIAL_CONTENT;
1974 case 300:
1975 return HTTP_STATUS_300_MULTIPLE_CHOICES;
1976 case 301:
1977 return HTTP_STATUS_301_MOVED_PERMANENTLY;
1978 case 302:
1979 return HTTP_STATUS_302_FOUND;
1980 case 303:
1981 return HTTP_STATUS_303_SEE_OTHER;
1982 case 304:
1983 return HTTP_STATUS_304_NOT_MODIFIED;
1984 case 305:
1985 return HTTP_STATUS_305_USE_PROXY;
1986 case 307:
1987 return HTTP_STATUS_307_TEMPORARY_REDIRECT;
1988 case 308:
1989 return HTTP_STATUS_308_PERMANENT_REDIRECT;
1990 case 400:
1991 return HTTP_STATUS_400_BAD_REQUEST;
1992 case 401:
1993 return HTTP_STATUS_401_UNAUTHORIZED;
1994 case 402:
1995 return HTTP_STATUS_402_PAYMENT_REQUIRED;
1996 case 403:
1997 return HTTP_STATUS_403_FORBIDDEN;
1998 case 404:
1999 return HTTP_STATUS_404_NOT_FOUND;
2000 case 405:
2001 return HTTP_STATUS_405_METHOD_NOT_ALLOWED;
2002 case 406:
2003 return HTTP_STATUS_406_NOT_ACCEPTABLE;
2004 case 407:
2005 return HTTP_STATUS_407_PROXY_AUTHENTICATION_REQUIRED;
2006 case 408:
2007 return HTTP_STATUS_408_REQUEST_TIME_OUT;
2008 case 409:
2009 return HTTP_STATUS_409_CONFLICT;
2010 case 410:
2011 return HTTP_STATUS_410_GONE;
2012 case 411:
2013 return HTTP_STATUS_411_LENGTH_REQUIRED;
2014 case 412:
2015 return HTTP_STATUS_412_PRECONDITION_FAILED;
2016 case 413:
2017 return HTTP_STATUS_413_REQUEST_ENTITY_TOO_LARGE;
2018 case 414:
2019 return HTTP_STATUS_414_REQUEST_URI_TOO_LARGE;
2020 case 415:
2021 return HTTP_STATUS_415_UNSUPPORTED_MEDIA_TYPE;
2022 case 416:
2023 return HTTP_STATUS_416_REQUESTED_RANGE_NOT_SATISFIED;
2024 case 417:
2025 return HTTP_STATUS_417_EXPECTATION_FAILED;
2026 case 500:
2027 return HTTP_STATUS_500_INTERNAL_SERVER_ERROR;
2028 case 501:
2029 return HTTP_STATUS_501_NOT_IMPLEMENTED;
2030 case 502:
2031 return HTTP_STATUS_502_BAD_GATEWAY;
2032 case 503:
2033 return HTTP_STATUS_503_SERVICE_UNAVAILABLE;
2034 case 504:
2035 return HTTP_STATUS_504_GATEWAY_TIME_OUT;
2036 case 505:
2037 return HTTP_STATUS_505_HTTP_VERSION_NOT_SUPPORTED;
2038
2039 default:
2040 return HTTP_STATUS_UNSUPPORTED_STATUS;
2041 }
2042 }
2043
2044 /**
2045 Check whether header field called FieldName is in DeleteList.
2046
2047 @param[in] DeleteList Pointer to array of key/value header pairs.
2048 @param[in] DeleteCount The number of header pairs.
2049 @param[in] FieldName Pointer to header field's name.
2050
2051 @return TRUE if FieldName is not in DeleteList, that means this header field is valid.
2052 @return FALSE if FieldName is in DeleteList, that means this header field is invalid.
2053
2054 **/
2055 BOOLEAN
2056 EFIAPI
2057 HttpIsValidHttpHeader (
2058 IN CHAR8 *DeleteList[],
2059 IN UINTN DeleteCount,
2060 IN CHAR8 *FieldName
2061 )
2062 {
2063 UINTN Index;
2064
2065 if (FieldName == NULL) {
2066 return FALSE;
2067 }
2068
2069 for (Index = 0; Index < DeleteCount; Index++) {
2070 if (DeleteList[Index] == NULL) {
2071 continue;
2072 }
2073
2074 if (AsciiStrCmp (FieldName, DeleteList[Index]) == 0) {
2075 return FALSE;
2076 }
2077 }
2078
2079 return TRUE;
2080 }
2081