]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeHttpLib/DxeHttpLib.c
774bf7d7e56a39fd3b9e4226b16c264f8e4ef2eb
[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 Parser = (HTTP_BODY_PARSER*) MsgParser;
1403
1404 if (Parser->State == BodyParserComplete) {
1405 return TRUE;
1406 }
1407 return FALSE;
1408 }
1409
1410 /**
1411 Get the content length of the entity.
1412
1413 Note that in trunk transfer, the entity length is not valid until the whole message body is received.
1414
1415 @param[in] MsgParser Pointer to the message parser.
1416 @param[out] ContentLength Pointer to store the length of the entity.
1417
1418 @retval EFI_SUCCESS Successfully to get the entity length.
1419 @retval EFI_NOT_READY Entity length is not valid yet.
1420 @retval EFI_INVALID_PARAMETER MsgParser is NULL or ContentLength is NULL.
1421
1422 **/
1423 EFI_STATUS
1424 EFIAPI
1425 HttpGetEntityLength (
1426 IN VOID *MsgParser,
1427 OUT UINTN *ContentLength
1428 )
1429 {
1430 HTTP_BODY_PARSER *Parser;
1431
1432 if (MsgParser == NULL || ContentLength == NULL) {
1433 return EFI_INVALID_PARAMETER;
1434 }
1435
1436 Parser = (HTTP_BODY_PARSER*) MsgParser;
1437
1438 if (!Parser->ContentLengthIsValid) {
1439 return EFI_NOT_READY;
1440 }
1441
1442 *ContentLength = Parser->ContentLength;
1443 return EFI_SUCCESS;
1444 }
1445
1446 /**
1447 Release the resource of the message parser.
1448
1449 @param[in] MsgParser Pointer to the message parser.
1450
1451 **/
1452 VOID
1453 EFIAPI
1454 HttpFreeMsgParser (
1455 IN VOID *MsgParser
1456 )
1457 {
1458 FreePool (MsgParser);
1459 }
1460
1461
1462 /**
1463 Get the next string, which is distinguished by specified separator.
1464
1465 @param[in] String Pointer to the string.
1466 @param[in] Separator Specified separator used to distinguish where is the beginning
1467 of next string.
1468
1469 @return Pointer to the next string.
1470 @return NULL if not find or String is NULL.
1471
1472 **/
1473 CHAR8 *
1474 EFIAPI
1475 AsciiStrGetNextToken (
1476 IN CONST CHAR8 *String,
1477 IN CHAR8 Separator
1478 )
1479 {
1480 CONST CHAR8 *Token;
1481
1482 Token = String;
1483 while (TRUE) {
1484 if (*Token == 0) {
1485 return NULL;
1486 }
1487 if (*Token == Separator) {
1488 return (CHAR8 *)(Token + 1);
1489 }
1490 Token++;
1491 }
1492 }
1493
1494 /**
1495 Set FieldName and FieldValue into specified HttpHeader.
1496
1497 @param[in,out] HttpHeader Specified HttpHeader.
1498 @param[in] FieldName FieldName of this HttpHeader, a NULL terminated ASCII string.
1499 @param[in] FieldValue FieldValue of this HttpHeader, a NULL terminated ASCII string.
1500
1501
1502 @retval EFI_SUCCESS The FieldName and FieldValue are set into HttpHeader successfully.
1503 @retval EFI_OUT_OF_RESOURCES Failed to allocate resources.
1504
1505 **/
1506 EFI_STATUS
1507 EFIAPI
1508 HttpSetFieldNameAndValue (
1509 IN OUT EFI_HTTP_HEADER *HttpHeader,
1510 IN CONST CHAR8 *FieldName,
1511 IN CONST CHAR8 *FieldValue
1512 )
1513 {
1514 UINTN FieldNameSize;
1515 UINTN FieldValueSize;
1516
1517 if (HttpHeader->FieldName != NULL) {
1518 FreePool (HttpHeader->FieldName);
1519 }
1520 if (HttpHeader->FieldValue != NULL) {
1521 FreePool (HttpHeader->FieldValue);
1522 }
1523
1524 FieldNameSize = AsciiStrSize (FieldName);
1525 HttpHeader->FieldName = AllocateZeroPool (FieldNameSize);
1526 if (HttpHeader->FieldName == NULL) {
1527 return EFI_OUT_OF_RESOURCES;
1528 }
1529 CopyMem (HttpHeader->FieldName, FieldName, FieldNameSize);
1530 HttpHeader->FieldName[FieldNameSize - 1] = 0;
1531
1532 FieldValueSize = AsciiStrSize (FieldValue);
1533 HttpHeader->FieldValue = AllocateZeroPool (FieldValueSize);
1534 if (HttpHeader->FieldValue == NULL) {
1535 FreePool (HttpHeader->FieldName);
1536 return EFI_OUT_OF_RESOURCES;
1537 }
1538 CopyMem (HttpHeader->FieldValue, FieldValue, FieldValueSize);
1539 HttpHeader->FieldValue[FieldValueSize - 1] = 0;
1540
1541 return EFI_SUCCESS;
1542 }
1543
1544 /**
1545 Get one key/value header pair from the raw string.
1546
1547 @param[in] String Pointer to the raw string.
1548 @param[out] FieldName Points directly to field name within 'HttpHeader'.
1549 @param[out] FieldValue Points directly to field value within 'HttpHeader'.
1550
1551 @return Pointer to the next raw string.
1552 @return NULL if no key/value header pair from this raw string.
1553
1554 **/
1555 CHAR8 *
1556 EFIAPI
1557 HttpGetFieldNameAndValue (
1558 IN CHAR8 *String,
1559 OUT CHAR8 **FieldName,
1560 OUT CHAR8 **FieldValue
1561 )
1562 {
1563 CHAR8 *FieldNameStr;
1564 CHAR8 *FieldValueStr;
1565 CHAR8 *StrPtr;
1566 CHAR8 *EndofHeader;
1567
1568 if (String == NULL || FieldName == NULL || FieldValue == NULL) {
1569 return NULL;
1570 }
1571
1572 *FieldName = NULL;
1573 *FieldValue = NULL;
1574 FieldNameStr = NULL;
1575 FieldValueStr = NULL;
1576 StrPtr = NULL;
1577 EndofHeader = NULL;
1578
1579
1580 //
1581 // Check whether the raw HTTP header string is valid or not.
1582 //
1583 EndofHeader = AsciiStrStr (String, "\r\n\r\n");
1584 if (EndofHeader == NULL) {
1585 return NULL;
1586 }
1587
1588 //
1589 // Each header field consists of a name followed by a colon (":") and the field value.
1590 //
1591 FieldNameStr = String;
1592 FieldValueStr = AsciiStrGetNextToken (FieldNameStr, ':');
1593 if (FieldValueStr == NULL) {
1594 return NULL;
1595 }
1596
1597 //
1598 // Replace ':' with 0
1599 //
1600 *(FieldValueStr - 1) = 0;
1601
1602 //
1603 // The field value MAY be preceded by any amount of LWS, though a single SP is preferred.
1604 // Note: LWS = [CRLF] 1*(SP|HT), it can be '\r\n ' or '\r\n\t' or ' ' or '\t'.
1605 // CRLF = '\r\n'.
1606 // SP = ' '.
1607 // HT = '\t' (Tab).
1608 //
1609 while (TRUE) {
1610 if (*FieldValueStr == ' ' || *FieldValueStr == '\t') {
1611 //
1612 // Boundary condition check.
1613 //
1614 if ((UINTN)EndofHeader - (UINTN)(FieldValueStr) < 1) {
1615 return NULL;
1616 }
1617
1618 FieldValueStr ++;
1619 } else if (*FieldValueStr == '\r') {
1620 //
1621 // Boundary condition check.
1622 //
1623 if ((UINTN)EndofHeader - (UINTN)(FieldValueStr) < 3) {
1624 return NULL;
1625 }
1626
1627 if (*(FieldValueStr + 1) == '\n' && (*(FieldValueStr + 2) == ' ' || *(FieldValueStr + 2) == '\t')) {
1628 FieldValueStr = FieldValueStr + 3;
1629 }
1630 } else {
1631 break;
1632 }
1633 }
1634
1635 //
1636 // Header fields can be extended over multiple lines by preceding each extra
1637 // line with at least one SP or HT.
1638 //
1639 StrPtr = FieldValueStr;
1640 do {
1641 StrPtr = AsciiStrGetNextToken (StrPtr, '\r');
1642 if (StrPtr == NULL || *StrPtr != '\n') {
1643 return NULL;
1644 }
1645
1646 StrPtr++;
1647 } while (*StrPtr == ' ' || *StrPtr == '\t');
1648
1649 //
1650 // Replace '\r' with 0
1651 //
1652 *(StrPtr - 2) = 0;
1653
1654 //
1655 // Get FieldName and FieldValue.
1656 //
1657 *FieldName = FieldNameStr;
1658 *FieldValue = FieldValueStr;
1659
1660 return StrPtr;
1661 }
1662
1663 /**
1664 Free existing HeaderFields.
1665
1666 @param[in] HeaderFields Pointer to array of key/value header pairs waitting for free.
1667 @param[in] FieldCount The number of header pairs in HeaderFields.
1668
1669 **/
1670 VOID
1671 EFIAPI
1672 HttpFreeHeaderFields (
1673 IN EFI_HTTP_HEADER *HeaderFields,
1674 IN UINTN FieldCount
1675 )
1676 {
1677 UINTN Index;
1678
1679 if (HeaderFields != NULL) {
1680 for (Index = 0; Index < FieldCount; Index++) {
1681 if (HeaderFields[Index].FieldName != NULL) {
1682 FreePool (HeaderFields[Index].FieldName);
1683 }
1684 if (HeaderFields[Index].FieldValue != NULL) {
1685 FreePool (HeaderFields[Index].FieldValue);
1686 }
1687 }
1688
1689 FreePool (HeaderFields);
1690 }
1691 }
1692
1693 /**
1694 Generate HTTP request message.
1695
1696 This function will allocate memory for the whole HTTP message and generate a
1697 well formatted HTTP Request message in it, include the Request-Line, header
1698 fields and also the message body. It is the caller's responsibility to free
1699 the buffer returned in *RequestMsg.
1700
1701 @param[in] Message Pointer to the EFI_HTTP_MESSAGE structure which
1702 contains the required information to generate
1703 the HTTP request message.
1704 @param[in] Url The URL of a remote host.
1705 @param[out] RequestMsg Pointer to the created HTTP request message.
1706 NULL if any error occured.
1707 @param[out] RequestMsgSize Size of the RequestMsg (in bytes).
1708
1709 @return EFI_SUCCESS If HTTP request string was created successfully
1710 @retval EFI_OUT_OF_RESOURCES Failed to allocate resources.
1711 @retval EFI_INVALID_PARAMETER The input arguments are invalid
1712
1713 **/
1714 EFI_STATUS
1715 EFIAPI
1716 HttpGenRequestMessage (
1717 IN CONST EFI_HTTP_MESSAGE *Message,
1718 IN CONST CHAR8 *Url,
1719 OUT CHAR8 **RequestMsg,
1720 OUT UINTN *RequestMsgSize
1721 )
1722 {
1723 EFI_STATUS Status;
1724 UINTN StrLength;
1725 CHAR8 *RequestPtr;
1726 UINTN HttpHdrSize;
1727 UINTN MsgSize;
1728 BOOLEAN Success;
1729 VOID *HttpHdr;
1730 EFI_HTTP_HEADER **AppendList;
1731 UINTN Index;
1732 EFI_HTTP_UTILITIES_PROTOCOL *HttpUtilitiesProtocol;
1733
1734
1735 ASSERT (Message != NULL);
1736
1737 *RequestMsg = NULL;
1738 Status = EFI_SUCCESS;
1739 HttpHdrSize = 0;
1740 MsgSize = 0;
1741 Success = FALSE;
1742 HttpHdr = NULL;
1743 AppendList = NULL;
1744 HttpUtilitiesProtocol = NULL;
1745
1746 //
1747 // 1. If we have a Request, we cannot have a NULL Url
1748 // 2. If we have a Request, HeaderCount can not be non-zero
1749 // 3. If we do not have a Request, HeaderCount should be zero
1750 // 4. If we do not have Request and Headers, we need at least a message-body
1751 //
1752 if ((Message->Data.Request != NULL && Url == NULL) ||
1753 (Message->Data.Request != NULL && Message->HeaderCount == 0) ||
1754 (Message->Data.Request == NULL && Message->HeaderCount != 0) ||
1755 (Message->Data.Request == NULL && Message->HeaderCount == 0 && Message->BodyLength == 0)) {
1756 return EFI_INVALID_PARAMETER;
1757 }
1758
1759 if (Message->HeaderCount != 0) {
1760 //
1761 // Locate the HTTP_UTILITIES protocol.
1762 //
1763 Status = gBS->LocateProtocol (
1764 &gEfiHttpUtilitiesProtocolGuid,
1765 NULL,
1766 (VOID **)&HttpUtilitiesProtocol
1767 );
1768
1769 if (EFI_ERROR (Status)) {
1770 DEBUG ((DEBUG_ERROR,"Failed to locate Http Utilities protocol. Status = %r.\n", Status));
1771 return Status;
1772 }
1773
1774 //
1775 // Build AppendList to send into HttpUtilitiesBuild
1776 //
1777 AppendList = AllocateZeroPool (sizeof (EFI_HTTP_HEADER *) * (Message->HeaderCount));
1778 if (AppendList == NULL) {
1779 return EFI_OUT_OF_RESOURCES;
1780 }
1781
1782 for(Index = 0; Index < Message->HeaderCount; Index++){
1783 AppendList[Index] = &Message->Headers[Index];
1784 }
1785
1786 //
1787 // Build raw HTTP Headers
1788 //
1789 Status = HttpUtilitiesProtocol->Build (
1790 HttpUtilitiesProtocol,
1791 0,
1792 NULL,
1793 0,
1794 NULL,
1795 Message->HeaderCount,
1796 AppendList,
1797 &HttpHdrSize,
1798 &HttpHdr
1799 );
1800
1801 if (AppendList != NULL) {
1802 FreePool (AppendList);
1803 }
1804
1805 if (EFI_ERROR (Status) || HttpHdr == NULL){
1806 return Status;
1807 }
1808 }
1809
1810 //
1811 // If we have headers to be sent, account for it.
1812 //
1813 if (Message->HeaderCount != 0) {
1814 MsgSize = HttpHdrSize;
1815 }
1816
1817 //
1818 // If we have a request line, account for the fields.
1819 //
1820 if (Message->Data.Request != NULL) {
1821 MsgSize += HTTP_METHOD_MAXIMUM_LEN + AsciiStrLen (HTTP_VERSION_CRLF_STR) + AsciiStrLen (Url);
1822 }
1823
1824
1825 //
1826 // If we have a message body to be sent, account for it.
1827 //
1828 MsgSize += Message->BodyLength;
1829
1830 //
1831 // memory for the string that needs to be sent to TCP
1832 //
1833 *RequestMsg = AllocateZeroPool (MsgSize);
1834 if (*RequestMsg == NULL) {
1835 Status = EFI_OUT_OF_RESOURCES;
1836 goto Exit;
1837 }
1838
1839 RequestPtr = *RequestMsg;
1840 //
1841 // Construct header request
1842 //
1843 if (Message->Data.Request != NULL) {
1844 switch (Message->Data.Request->Method) {
1845 case HttpMethodGet:
1846 StrLength = sizeof (HTTP_METHOD_GET) - 1;
1847 CopyMem (RequestPtr, HTTP_METHOD_GET, StrLength);
1848 RequestPtr += StrLength;
1849 break;
1850 case HttpMethodPut:
1851 StrLength = sizeof (HTTP_METHOD_PUT) - 1;
1852 CopyMem (RequestPtr, HTTP_METHOD_PUT, StrLength);
1853 RequestPtr += StrLength;
1854 break;
1855 case HttpMethodPatch:
1856 StrLength = sizeof (HTTP_METHOD_PATCH) - 1;
1857 CopyMem (RequestPtr, HTTP_METHOD_PATCH, StrLength);
1858 RequestPtr += StrLength;
1859 break;
1860 case HttpMethodPost:
1861 StrLength = sizeof (HTTP_METHOD_POST) - 1;
1862 CopyMem (RequestPtr, HTTP_METHOD_POST, StrLength);
1863 RequestPtr += StrLength;
1864 break;
1865 case HttpMethodHead:
1866 StrLength = sizeof (HTTP_METHOD_HEAD) - 1;
1867 CopyMem (RequestPtr, HTTP_METHOD_HEAD, StrLength);
1868 RequestPtr += StrLength;
1869 break;
1870 case HttpMethodDelete:
1871 StrLength = sizeof (HTTP_METHOD_DELETE) - 1;
1872 CopyMem (RequestPtr, HTTP_METHOD_DELETE, StrLength);
1873 RequestPtr += StrLength;
1874 break;
1875 default:
1876 ASSERT (FALSE);
1877 Status = EFI_INVALID_PARAMETER;
1878 goto Exit;
1879 }
1880
1881 StrLength = AsciiStrLen(EMPTY_SPACE);
1882 CopyMem (RequestPtr, EMPTY_SPACE, StrLength);
1883 RequestPtr += StrLength;
1884
1885 StrLength = AsciiStrLen (Url);
1886 CopyMem (RequestPtr, Url, StrLength);
1887 RequestPtr += StrLength;
1888
1889 StrLength = sizeof (HTTP_VERSION_CRLF_STR) - 1;
1890 CopyMem (RequestPtr, HTTP_VERSION_CRLF_STR, StrLength);
1891 RequestPtr += StrLength;
1892
1893 if (HttpHdr != NULL) {
1894 //
1895 // Construct header
1896 //
1897 CopyMem (RequestPtr, HttpHdr, HttpHdrSize);
1898 RequestPtr += HttpHdrSize;
1899 }
1900 }
1901
1902 //
1903 // Construct body
1904 //
1905 if (Message->Body != NULL) {
1906 CopyMem (RequestPtr, Message->Body, Message->BodyLength);
1907 RequestPtr += Message->BodyLength;
1908 }
1909
1910 //
1911 // Done
1912 //
1913 (*RequestMsgSize) = (UINTN)(RequestPtr) - (UINTN)(*RequestMsg);
1914 Success = TRUE;
1915
1916 Exit:
1917
1918 if (!Success) {
1919 if (*RequestMsg != NULL) {
1920 FreePool (*RequestMsg);
1921 }
1922 *RequestMsg = NULL;
1923 return Status;
1924 }
1925
1926 if (HttpHdr != NULL) {
1927 FreePool (HttpHdr);
1928 }
1929
1930 return EFI_SUCCESS;
1931 }
1932
1933 /**
1934 Translate the status code in HTTP message to EFI_HTTP_STATUS_CODE defined
1935 in UEFI 2.5 specification.
1936
1937 @param[in] StatusCode The status code value in HTTP message.
1938
1939 @return Value defined in EFI_HTTP_STATUS_CODE .
1940
1941 **/
1942 EFI_HTTP_STATUS_CODE
1943 EFIAPI
1944 HttpMappingToStatusCode (
1945 IN UINTN StatusCode
1946 )
1947 {
1948 switch (StatusCode) {
1949 case 100:
1950 return HTTP_STATUS_100_CONTINUE;
1951 case 101:
1952 return HTTP_STATUS_101_SWITCHING_PROTOCOLS;
1953 case 200:
1954 return HTTP_STATUS_200_OK;
1955 case 201:
1956 return HTTP_STATUS_201_CREATED;
1957 case 202:
1958 return HTTP_STATUS_202_ACCEPTED;
1959 case 203:
1960 return HTTP_STATUS_203_NON_AUTHORITATIVE_INFORMATION;
1961 case 204:
1962 return HTTP_STATUS_204_NO_CONTENT;
1963 case 205:
1964 return HTTP_STATUS_205_RESET_CONTENT;
1965 case 206:
1966 return HTTP_STATUS_206_PARTIAL_CONTENT;
1967 case 300:
1968 return HTTP_STATUS_300_MULTIPLE_CHOICES;
1969 case 301:
1970 return HTTP_STATUS_301_MOVED_PERMANENTLY;
1971 case 302:
1972 return HTTP_STATUS_302_FOUND;
1973 case 303:
1974 return HTTP_STATUS_303_SEE_OTHER;
1975 case 304:
1976 return HTTP_STATUS_304_NOT_MODIFIED;
1977 case 305:
1978 return HTTP_STATUS_305_USE_PROXY;
1979 case 307:
1980 return HTTP_STATUS_307_TEMPORARY_REDIRECT;
1981 case 308:
1982 return HTTP_STATUS_308_PERMANENT_REDIRECT;
1983 case 400:
1984 return HTTP_STATUS_400_BAD_REQUEST;
1985 case 401:
1986 return HTTP_STATUS_401_UNAUTHORIZED;
1987 case 402:
1988 return HTTP_STATUS_402_PAYMENT_REQUIRED;
1989 case 403:
1990 return HTTP_STATUS_403_FORBIDDEN;
1991 case 404:
1992 return HTTP_STATUS_404_NOT_FOUND;
1993 case 405:
1994 return HTTP_STATUS_405_METHOD_NOT_ALLOWED;
1995 case 406:
1996 return HTTP_STATUS_406_NOT_ACCEPTABLE;
1997 case 407:
1998 return HTTP_STATUS_407_PROXY_AUTHENTICATION_REQUIRED;
1999 case 408:
2000 return HTTP_STATUS_408_REQUEST_TIME_OUT;
2001 case 409:
2002 return HTTP_STATUS_409_CONFLICT;
2003 case 410:
2004 return HTTP_STATUS_410_GONE;
2005 case 411:
2006 return HTTP_STATUS_411_LENGTH_REQUIRED;
2007 case 412:
2008 return HTTP_STATUS_412_PRECONDITION_FAILED;
2009 case 413:
2010 return HTTP_STATUS_413_REQUEST_ENTITY_TOO_LARGE;
2011 case 414:
2012 return HTTP_STATUS_414_REQUEST_URI_TOO_LARGE;
2013 case 415:
2014 return HTTP_STATUS_415_UNSUPPORTED_MEDIA_TYPE;
2015 case 416:
2016 return HTTP_STATUS_416_REQUESTED_RANGE_NOT_SATISFIED;
2017 case 417:
2018 return HTTP_STATUS_417_EXPECTATION_FAILED;
2019 case 500:
2020 return HTTP_STATUS_500_INTERNAL_SERVER_ERROR;
2021 case 501:
2022 return HTTP_STATUS_501_NOT_IMPLEMENTED;
2023 case 502:
2024 return HTTP_STATUS_502_BAD_GATEWAY;
2025 case 503:
2026 return HTTP_STATUS_503_SERVICE_UNAVAILABLE;
2027 case 504:
2028 return HTTP_STATUS_504_GATEWAY_TIME_OUT;
2029 case 505:
2030 return HTTP_STATUS_505_HTTP_VERSION_NOT_SUPPORTED;
2031
2032 default:
2033 return HTTP_STATUS_UNSUPPORTED_STATUS;
2034 }
2035 }
2036
2037 /**
2038 Check whether header field called FieldName is in DeleteList.
2039
2040 @param[in] DeleteList Pointer to array of key/value header pairs.
2041 @param[in] DeleteCount The number of header pairs.
2042 @param[in] FieldName Pointer to header field's name.
2043
2044 @return TRUE if FieldName is not in DeleteList, that means this header field is valid.
2045 @return FALSE if FieldName is in DeleteList, that means this header field is invalid.
2046
2047 **/
2048 BOOLEAN
2049 EFIAPI
2050 HttpIsValidHttpHeader (
2051 IN CHAR8 *DeleteList[],
2052 IN UINTN DeleteCount,
2053 IN CHAR8 *FieldName
2054 )
2055 {
2056 UINTN Index;
2057
2058 for (Index = 0; Index < DeleteCount; Index++) {
2059 if (AsciiStrCmp (FieldName, DeleteList[Index]) == 0) {
2060 return FALSE;
2061 }
2062 }
2063
2064 return TRUE;
2065 }
2066