]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeHttpLib/DxeHttpLib.c
MdeModulePkg: Add new API HttpUrlGetPath() to HttpLib.h
[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 - 2016, Intel Corporation. All rights reserved.<BR>
6 This program and the accompanying materials
7 are licensed and made available under the terms and conditions of the BSD License
8 which accompanies this distribution. The full text of the license may be found at<BR>
9 http://opensource.org/licenses/bsd-license.php
10
11 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
12 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
13
14 **/
15
16 #include <Uefi.h>
17 #include <Library/NetLib.h>
18 #include <Library/HttpLib.h>
19 #include <Library/BaseLib.h>
20 #include <Library/DebugLib.h>
21 #include <Library/MemoryAllocationLib.h>
22 #include <Library/UefiBootServicesTableLib.h>
23
24 #define BIT(x) (1 << x)
25
26 #define NET_IS_HEX_CHAR(Ch) \
27 ((('0' <= (Ch)) && ((Ch) <= '9')) || \
28 (('A' <= (Ch)) && ((Ch) <= 'F')) || \
29 (('a' <= (Ch)) && ((Ch) <= 'f')))
30
31 //
32 // Field index of the HTTP URL parse result.
33 //
34 #define HTTP_URI_FIELD_SCHEME 0
35 #define HTTP_URI_FIELD_AUTHORITY 1
36 #define HTTP_URI_FIELD_PATH 2
37 #define HTTP_URI_FIELD_QUERY 3
38 #define HTTP_URI_FIELD_FRAGMENT 4
39 #define HTTP_URI_FIELD_USERINFO 5
40 #define HTTP_URI_FIELD_HOST 6
41 #define HTTP_URI_FIELD_PORT 7
42 #define HTTP_URI_FIELD_MAX 8
43
44 //
45 // Structure to store the parse result of a HTTP URL.
46 //
47 typedef struct {
48 UINT32 Offset;
49 UINT32 Length;
50 } HTTP_URL_FILED_DATA;
51
52 typedef struct {
53 UINT16 FieldBitMap;
54 HTTP_URL_FILED_DATA FieldData[HTTP_URI_FIELD_MAX];
55 } HTTP_URL_PARSER;
56
57 typedef enum {
58 UrlParserUrlStart,
59 UrlParserScheme,
60 UrlParserSchemeColon, // ":"
61 UrlParserSchemeColonSlash, // ":/"
62 UrlParserSchemeColonSlashSlash, // "://"
63 UrlParserAuthority,
64 UrlParserAtInAuthority,
65 UrlParserPath,
66 UrlParserQueryStart, // "?"
67 UrlParserQuery,
68 UrlParserFragmentStart, // "#"
69 UrlParserFragment,
70 UrlParserUserInfo,
71 UrlParserHostStart, // "@"
72 UrlParserHost,
73 UrlParserHostIpv6, // "["(Ipv6 address) "]"
74 UrlParserPortStart, // ":"
75 UrlParserPort,
76 UrlParserStateMax
77 } HTTP_URL_PARSE_STATE;
78
79 /**
80 Decode a percent-encoded URI component to the ASCII character.
81
82 Decode the input component in Buffer according to RFC 3986. The caller is responsible to make
83 sure ResultBuffer points to a buffer with size equal or greater than ((AsciiStrSize (Buffer))
84 in bytes.
85
86 @param[in] Buffer The pointer to a percent-encoded URI component.
87 @param[in] BufferLength Length of Buffer in bytes.
88 @param[out] ResultBuffer Point to the buffer to store the decode result.
89 @param[out] ResultLength Length of decoded string in ResultBuffer in bytes.
90
91 @retval EFI_SUCCESS Successfully decoded the URI.
92 @retval EFI_INVALID_PARAMETER Buffer is not a valid percent-encoded string.
93
94 **/
95 EFI_STATUS
96 EFIAPI
97 UriPercentDecode (
98 IN CHAR8 *Buffer,
99 IN UINT32 BufferLength,
100 OUT CHAR8 *ResultBuffer,
101 OUT UINT32 *ResultLength
102 )
103 {
104 UINTN Index;
105 UINTN Offset;
106 CHAR8 HexStr[3];
107
108 if (Buffer == NULL || BufferLength == 0 || ResultBuffer == NULL) {
109 return EFI_INVALID_PARAMETER;
110 }
111
112 Index = 0;
113 Offset = 0;
114 HexStr[2] = '\0';
115 while (Index < BufferLength) {
116 if (Buffer[Index] == '%') {
117 if (!NET_IS_HEX_CHAR (Buffer[Index+1]) || !NET_IS_HEX_CHAR (Buffer[Index+2])) {
118 return EFI_INVALID_PARAMETER;
119 }
120 HexStr[0] = Buffer[Index+1];
121 HexStr[1] = Buffer[Index+2];
122 ResultBuffer[Offset] = (CHAR8) AsciiStrHexToUintn (HexStr);
123 Index += 3;
124 } else {
125 ResultBuffer[Offset] = Buffer[Index];
126 Index++;
127 }
128 Offset++;
129 }
130
131 *ResultLength = (UINT32) Offset;
132
133 return EFI_SUCCESS;
134 }
135
136 /**
137 This function return the updated state according to the input state and next character of
138 the authority.
139
140 @param[in] Char Next character.
141 @param[in] State Current value of the parser state machine.
142 @param[in] IsRightBracket TRUE if there is an sign ']' in the authority component and
143 indicates the next part is ':' before Port.
144
145 @return Updated state value.
146 **/
147 HTTP_URL_PARSE_STATE
148 NetHttpParseAuthorityChar (
149 IN CHAR8 Char,
150 IN HTTP_URL_PARSE_STATE State,
151 IN BOOLEAN *IsRightBracket
152 )
153 {
154
155 //
156 // RFC 3986:
157 // The authority component is preceded by a double slash ("//") and is
158 // terminated by the next slash ("/"), question mark ("?"), or number
159 // sign ("#") character, or by the end of the URI.
160 //
161 if (Char == ' ' || Char == '\r' || Char == '\n') {
162 return UrlParserStateMax;
163 }
164
165 //
166 // authority = [ userinfo "@" ] host [ ":" port ]
167 //
168 switch (State) {
169 case UrlParserUserInfo:
170 if (Char == '@') {
171 return UrlParserHostStart;
172 }
173 break;
174
175 case UrlParserHost:
176 case UrlParserHostStart:
177 if (Char == '[') {
178 return UrlParserHostIpv6;
179 }
180
181 if (Char == ':') {
182 return UrlParserPortStart;
183 }
184
185 return UrlParserHost;
186
187 case UrlParserHostIpv6:
188 if (Char == ']') {
189 *IsRightBracket = TRUE;
190 }
191
192 if (Char == ':' && *IsRightBracket) {
193 return UrlParserPortStart;
194 }
195 return UrlParserHostIpv6;
196
197 case UrlParserPort:
198 case UrlParserPortStart:
199 return UrlParserPort;
200
201 default:
202 break;
203 }
204
205 return State;
206 }
207
208 /**
209 This function parse the authority component of the input URL and update the parser.
210
211 @param[in] Url The pointer to a HTTP URL string.
212 @param[in] FoundAt TRUE if there is an at sign ('@') in the authority component.
213 @param[in, out] UrlParser Pointer to the buffer of the parse result.
214
215 @retval EFI_SUCCESS Successfully parse the authority.
216 @retval Other Error happened.
217
218 **/
219 EFI_STATUS
220 NetHttpParseAuthority (
221 IN CHAR8 *Url,
222 IN BOOLEAN FoundAt,
223 IN OUT HTTP_URL_PARSER *UrlParser
224 )
225 {
226 CHAR8 *Char;
227 CHAR8 *Authority;
228 UINT32 Length;
229 HTTP_URL_PARSE_STATE State;
230 UINT32 Field;
231 UINT32 OldField;
232 BOOLEAN IsrightBracket;
233
234 ASSERT ((UrlParser->FieldBitMap & BIT (HTTP_URI_FIELD_AUTHORITY)) != 0);
235
236 //
237 // authority = [ userinfo "@" ] host [ ":" port ]
238 //
239 if (FoundAt) {
240 State = UrlParserUserInfo;
241 } else {
242 State = UrlParserHost;
243 }
244
245 IsrightBracket = FALSE;
246 Field = HTTP_URI_FIELD_MAX;
247 OldField = Field;
248 Authority = Url + UrlParser->FieldData[HTTP_URI_FIELD_AUTHORITY].Offset;
249 Length = UrlParser->FieldData[HTTP_URI_FIELD_AUTHORITY].Length;
250 for (Char = Authority; Char < Authority + Length; Char++) {
251 State = NetHttpParseAuthorityChar (*Char, State, &IsrightBracket);
252 switch (State) {
253 case UrlParserStateMax:
254 return EFI_INVALID_PARAMETER;
255
256 case UrlParserHostStart:
257 case UrlParserPortStart:
258 continue;
259
260 case UrlParserUserInfo:
261 Field = HTTP_URI_FIELD_USERINFO;
262 break;
263
264 case UrlParserHost:
265 Field = HTTP_URI_FIELD_HOST;
266 break;
267
268 case UrlParserHostIpv6:
269 Field = HTTP_URI_FIELD_HOST;
270 break;
271
272 case UrlParserPort:
273 Field = HTTP_URI_FIELD_PORT;
274 break;
275
276 default:
277 ASSERT (FALSE);
278 }
279
280 //
281 // Field not changed, count the length.
282 //
283 ASSERT (Field < HTTP_URI_FIELD_MAX);
284 if (Field == OldField) {
285 UrlParser->FieldData[Field].Length++;
286 continue;
287 }
288
289 //
290 // New field start
291 //
292 UrlParser->FieldBitMap |= BIT (Field);
293 UrlParser->FieldData[Field].Offset = (UINT32) (Char - Url);
294 UrlParser->FieldData[Field].Length = 1;
295 OldField = Field;
296 }
297
298 return EFI_SUCCESS;
299 }
300
301 /**
302 This function return the updated state according to the input state and next character of a URL.
303
304 @param[in] Char Next character.
305 @param[in] State Current value of the parser state machine.
306
307 @return Updated state value.
308
309 **/
310 HTTP_URL_PARSE_STATE
311 NetHttpParseUrlChar (
312 IN CHAR8 Char,
313 IN HTTP_URL_PARSE_STATE State
314 )
315 {
316 if (Char == ' ' || Char == '\r' || Char == '\n') {
317 return UrlParserStateMax;
318 }
319
320 //
321 // http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
322 //
323 // Request-URI = "*" | absolute-URI | path-absolute | authority
324 //
325 // absolute-URI = scheme ":" hier-part [ "?" query ]
326 // path-absolute = "/" [ segment-nz *( "/" segment ) ]
327 // authority = [ userinfo "@" ] host [ ":" port ]
328 //
329 switch (State) {
330 case UrlParserUrlStart:
331 if (Char == '*' || Char == '/') {
332 return UrlParserPath;
333 }
334 return UrlParserScheme;
335
336 case UrlParserScheme:
337 if (Char == ':') {
338 return UrlParserSchemeColon;
339 }
340 break;
341
342 case UrlParserSchemeColon:
343 if (Char == '/') {
344 return UrlParserSchemeColonSlash;
345 }
346 break;
347
348 case UrlParserSchemeColonSlash:
349 if (Char == '/') {
350 return UrlParserSchemeColonSlashSlash;
351 }
352 break;
353
354 case UrlParserAtInAuthority:
355 if (Char == '@') {
356 return UrlParserStateMax;
357 }
358
359 case UrlParserAuthority:
360 case UrlParserSchemeColonSlashSlash:
361 if (Char == '@') {
362 return UrlParserAtInAuthority;
363 }
364 if (Char == '/') {
365 return UrlParserPath;
366 }
367 if (Char == '?') {
368 return UrlParserQueryStart;
369 }
370 if (Char == '#') {
371 return UrlParserFragmentStart;
372 }
373 return UrlParserAuthority;
374
375 case UrlParserPath:
376 if (Char == '?') {
377 return UrlParserQueryStart;
378 }
379 if (Char == '#') {
380 return UrlParserFragmentStart;
381 }
382 break;
383
384 case UrlParserQuery:
385 case UrlParserQueryStart:
386 if (Char == '#') {
387 return UrlParserFragmentStart;
388 }
389 return UrlParserQuery;
390
391 case UrlParserFragmentStart:
392 return UrlParserFragment;
393
394 default:
395 break;
396 }
397
398 return State;
399 }
400 /**
401 Create a URL parser for the input URL string.
402
403 This function will parse and dereference the input HTTP URL into it components. The original
404 content of the URL won't be modified and the result will be returned in UrlParser, which can
405 be used in other functions like NetHttpUrlGetHostName().
406
407 @param[in] Url The pointer to a HTTP URL string.
408 @param[in] Length Length of Url in bytes.
409 @param[in] IsConnectMethod Whether the Url is used in HTTP CONNECT method or not.
410 @param[out] UrlParser Pointer to the returned buffer to store the parse result.
411
412 @retval EFI_SUCCESS Successfully dereferenced the HTTP URL.
413 @retval EFI_INVALID_PARAMETER UrlParser is NULL or Url is not a valid HTTP URL.
414 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
415
416 **/
417 EFI_STATUS
418 EFIAPI
419 HttpParseUrl (
420 IN CHAR8 *Url,
421 IN UINT32 Length,
422 IN BOOLEAN IsConnectMethod,
423 OUT VOID **UrlParser
424 )
425 {
426 HTTP_URL_PARSE_STATE State;
427 CHAR8 *Char;
428 UINT32 Field;
429 UINT32 OldField;
430 BOOLEAN FoundAt;
431 EFI_STATUS Status;
432 HTTP_URL_PARSER *Parser;
433
434 if (Url == NULL || Length == 0 || UrlParser == NULL) {
435 return EFI_INVALID_PARAMETER;
436 }
437
438 Parser = AllocateZeroPool (sizeof (HTTP_URL_PARSER));
439 if (Parser == NULL) {
440 return EFI_OUT_OF_RESOURCES;
441 }
442
443 if (IsConnectMethod) {
444 //
445 // According to RFC 2616, the authority form is only used by the CONNECT method.
446 //
447 State = UrlParserAuthority;
448 } else {
449 State = UrlParserUrlStart;
450 }
451
452 Field = HTTP_URI_FIELD_MAX;
453 OldField = Field;
454 FoundAt = FALSE;
455 for (Char = Url; Char < Url + Length; Char++) {
456 //
457 // Update state machine accoring to next char.
458 //
459 State = NetHttpParseUrlChar (*Char, State);
460
461 switch (State) {
462 case UrlParserStateMax:
463 return EFI_INVALID_PARAMETER;
464
465 case UrlParserSchemeColon:
466 case UrlParserSchemeColonSlash:
467 case UrlParserSchemeColonSlashSlash:
468 case UrlParserQueryStart:
469 case UrlParserFragmentStart:
470 //
471 // Skip all the delimiting char: "://" "?" "@"
472 //
473 continue;
474
475 case UrlParserScheme:
476 Field = HTTP_URI_FIELD_SCHEME;
477 break;
478
479 case UrlParserAtInAuthority:
480 FoundAt = TRUE;
481 case UrlParserAuthority:
482 Field = HTTP_URI_FIELD_AUTHORITY;
483 break;
484
485 case UrlParserPath:
486 Field = HTTP_URI_FIELD_PATH;
487 break;
488
489 case UrlParserQuery:
490 Field = HTTP_URI_FIELD_QUERY;
491 break;
492
493 case UrlParserFragment:
494 Field = HTTP_URI_FIELD_FRAGMENT;
495 break;
496
497 default:
498 ASSERT (FALSE);
499 }
500
501 //
502 // Field not changed, count the length.
503 //
504 ASSERT (Field < HTTP_URI_FIELD_MAX);
505 if (Field == OldField) {
506 Parser->FieldData[Field].Length++;
507 continue;
508 }
509
510 //
511 // New field start
512 //
513 Parser->FieldBitMap |= BIT (Field);
514 Parser->FieldData[Field].Offset = (UINT32) (Char - Url);
515 Parser->FieldData[Field].Length = 1;
516 OldField = Field;
517 }
518
519 //
520 // If has authority component, continue to parse the username, host and port.
521 //
522 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_AUTHORITY)) != 0) {
523 Status = NetHttpParseAuthority (Url, FoundAt, Parser);
524 if (EFI_ERROR (Status)) {
525 return Status;
526 }
527 }
528
529 *UrlParser = Parser;
530 return EFI_SUCCESS;
531 }
532
533 /**
534 Get the Hostname from a HTTP URL.
535
536 This function will return the HostName according to the Url and previous parse result ,and
537 it is the caller's responsibility to free the buffer returned in *HostName.
538
539 @param[in] Url The pointer to a HTTP URL string.
540 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
541 @param[out] HostName Pointer to a buffer to store the HostName.
542
543 @retval EFI_SUCCESS Successfully get the required component.
544 @retval EFI_INVALID_PARAMETER Uri is NULL or HostName is NULL or UrlParser is invalid.
545 @retval EFI_NOT_FOUND No hostName component in the URL.
546 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
547
548 **/
549 EFI_STATUS
550 EFIAPI
551 HttpUrlGetHostName (
552 IN CHAR8 *Url,
553 IN VOID *UrlParser,
554 OUT CHAR8 **HostName
555 )
556 {
557 CHAR8 *Name;
558 EFI_STATUS Status;
559 UINT32 ResultLength;
560 HTTP_URL_PARSER *Parser;
561
562 if (Url == NULL || UrlParser == NULL || HostName == NULL) {
563 return EFI_INVALID_PARAMETER;
564 }
565
566 Parser = (HTTP_URL_PARSER*) UrlParser;
567
568 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_HOST)) == 0) {
569 return EFI_NOT_FOUND;
570 }
571
572 Name = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_HOST].Length + 1);
573 if (Name == NULL) {
574 return EFI_OUT_OF_RESOURCES;
575 }
576
577 Status = UriPercentDecode (
578 Url + Parser->FieldData[HTTP_URI_FIELD_HOST].Offset,
579 Parser->FieldData[HTTP_URI_FIELD_HOST].Length,
580 Name,
581 &ResultLength
582 );
583 if (EFI_ERROR (Status)) {
584 return Status;
585 }
586
587 Name[ResultLength] = '\0';
588 *HostName = Name;
589 return EFI_SUCCESS;
590 }
591
592
593 /**
594 Get the IPv4 address from a HTTP URL.
595
596 This function will return the IPv4 address according to the Url and previous parse result.
597
598 @param[in] Url The pointer to a HTTP URL string.
599 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
600 @param[out] Ip4Address Pointer to a buffer to store the IP address.
601
602 @retval EFI_SUCCESS Successfully get the required component.
603 @retval EFI_INVALID_PARAMETER Uri is NULL or Ip4Address is NULL or UrlParser is invalid.
604 @retval EFI_NOT_FOUND No IPv4 address component in the URL.
605 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
606
607 **/
608 EFI_STATUS
609 EFIAPI
610 HttpUrlGetIp4 (
611 IN CHAR8 *Url,
612 IN VOID *UrlParser,
613 OUT EFI_IPv4_ADDRESS *Ip4Address
614 )
615 {
616 CHAR8 *Ip4String;
617 EFI_STATUS Status;
618 UINT32 ResultLength;
619 HTTP_URL_PARSER *Parser;
620
621 if (Url == NULL || UrlParser == NULL || Ip4Address == NULL) {
622 return EFI_INVALID_PARAMETER;
623 }
624
625 Parser = (HTTP_URL_PARSER*) UrlParser;
626
627 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_HOST)) == 0) {
628 return EFI_INVALID_PARAMETER;
629 }
630
631 Ip4String = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_HOST].Length + 1);
632 if (Ip4String == NULL) {
633 return EFI_OUT_OF_RESOURCES;
634 }
635
636 Status = UriPercentDecode (
637 Url + Parser->FieldData[HTTP_URI_FIELD_HOST].Offset,
638 Parser->FieldData[HTTP_URI_FIELD_HOST].Length,
639 Ip4String,
640 &ResultLength
641 );
642 if (EFI_ERROR (Status)) {
643 return Status;
644 }
645
646 Ip4String[ResultLength] = '\0';
647 Status = NetLibAsciiStrToIp4 (Ip4String, Ip4Address);
648 FreePool (Ip4String);
649
650 return Status;
651 }
652
653 /**
654 Get the IPv6 address from a HTTP URL.
655
656 This function will return the IPv6 address according to the Url and previous parse result.
657
658 @param[in] Url The pointer to a HTTP URL string.
659 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
660 @param[out] Ip6Address Pointer to a buffer to store the IP address.
661
662 @retval EFI_SUCCESS Successfully get the required component.
663 @retval EFI_INVALID_PARAMETER Uri is NULL or Ip6Address is NULL or UrlParser is invalid.
664 @retval EFI_NOT_FOUND No IPv6 address component in the URL.
665 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
666
667 **/
668 EFI_STATUS
669 EFIAPI
670 HttpUrlGetIp6 (
671 IN CHAR8 *Url,
672 IN VOID *UrlParser,
673 OUT EFI_IPv6_ADDRESS *Ip6Address
674 )
675 {
676 CHAR8 *Ip6String;
677 CHAR8 *Ptr;
678 UINT32 Length;
679 EFI_STATUS Status;
680 UINT32 ResultLength;
681 HTTP_URL_PARSER *Parser;
682
683 if (Url == NULL || UrlParser == NULL || Ip6Address == NULL) {
684 return EFI_INVALID_PARAMETER;
685 }
686
687 Parser = (HTTP_URL_PARSER*) UrlParser;
688
689 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_HOST)) == 0) {
690 return EFI_INVALID_PARAMETER;
691 }
692
693 //
694 // IP-literal = "[" ( IPv6address / IPvFuture ) "]"
695 //
696 Length = Parser->FieldData[HTTP_URI_FIELD_HOST].Length;
697 if (Length < 2) {
698 return EFI_INVALID_PARAMETER;
699 }
700
701 Ptr = Url + Parser->FieldData[HTTP_URI_FIELD_HOST].Offset;
702 if ((Ptr[0] != '[') || (Ptr[Length - 1] != ']')) {
703 return EFI_INVALID_PARAMETER;
704 }
705
706 Ip6String = AllocatePool (Length);
707 if (Ip6String == NULL) {
708 return EFI_OUT_OF_RESOURCES;
709 }
710
711 Status = UriPercentDecode (
712 Ptr + 1,
713 Length - 2,
714 Ip6String,
715 &ResultLength
716 );
717 if (EFI_ERROR (Status)) {
718 return Status;
719 }
720
721 Ip6String[ResultLength] = '\0';
722 Status = NetLibAsciiStrToIp6 (Ip6String, Ip6Address);
723 FreePool (Ip6String);
724
725 return Status;
726 }
727
728 /**
729 Get the port number from a HTTP URL.
730
731 This function will return the port number according to the Url and previous parse result.
732
733 @param[in] Url The pointer to a HTTP URL string.
734 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
735 @param[out] Port Pointer to a buffer to store the port number.
736
737 @retval EFI_SUCCESS Successfully get the required component.
738 @retval EFI_INVALID_PARAMETER Uri is NULL or Port is NULL or UrlParser is invalid.
739 @retval EFI_NOT_FOUND No port number in the URL.
740 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
741
742 **/
743 EFI_STATUS
744 EFIAPI
745 HttpUrlGetPort (
746 IN CHAR8 *Url,
747 IN VOID *UrlParser,
748 OUT UINT16 *Port
749 )
750 {
751 CHAR8 *PortString;
752 EFI_STATUS Status;
753 UINT32 ResultLength;
754 HTTP_URL_PARSER *Parser;
755
756 if (Url == NULL || UrlParser == NULL || Port == NULL) {
757 return EFI_INVALID_PARAMETER;
758 }
759
760 Parser = (HTTP_URL_PARSER*) UrlParser;
761
762 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_PORT)) == 0) {
763 return EFI_INVALID_PARAMETER;
764 }
765
766 PortString = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_PORT].Length + 1);
767 if (PortString == NULL) {
768 return EFI_OUT_OF_RESOURCES;
769 }
770
771 Status = UriPercentDecode (
772 Url + Parser->FieldData[HTTP_URI_FIELD_PORT].Offset,
773 Parser->FieldData[HTTP_URI_FIELD_PORT].Length,
774 PortString,
775 &ResultLength
776 );
777 if (EFI_ERROR (Status)) {
778 return Status;
779 }
780
781 PortString[ResultLength] = '\0';
782 *Port = (UINT16) AsciiStrDecimalToUintn (Url + Parser->FieldData[HTTP_URI_FIELD_PORT].Offset);
783
784 return EFI_SUCCESS;
785 }
786
787 /**
788 Get the Path from a HTTP URL.
789
790 This function will return the Path according to the Url and previous parse result,and
791 it is the caller's responsibility to free the buffer returned in *Path.
792
793 @param[in] Url The pointer to a HTTP URL string.
794 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
795 @param[out] Path Pointer to a buffer to store the Path.
796
797 @retval EFI_SUCCESS Successfully get the required component.
798 @retval EFI_INVALID_PARAMETER Uri is NULL or HostName is NULL or UrlParser is invalid.
799 @retval EFI_NOT_FOUND No hostName component in the URL.
800 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
801
802 **/
803 EFI_STATUS
804 EFIAPI
805 HttpUrlGetPath (
806 IN CHAR8 *Url,
807 IN VOID *UrlParser,
808 OUT CHAR8 **Path
809 )
810 {
811 CHAR8 *PathStr;
812 EFI_STATUS Status;
813 UINT32 ResultLength;
814 HTTP_URL_PARSER *Parser;
815
816 if (Url == NULL || UrlParser == NULL || Path == NULL) {
817 return EFI_INVALID_PARAMETER;
818 }
819
820 Parser = (HTTP_URL_PARSER*) UrlParser;
821
822 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_PATH)) == 0) {
823 return EFI_NOT_FOUND;
824 }
825
826 PathStr = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_PATH].Length + 1);
827 if (PathStr == NULL) {
828 return EFI_OUT_OF_RESOURCES;
829 }
830
831 Status = UriPercentDecode (
832 Url + Parser->FieldData[HTTP_URI_FIELD_PATH].Offset,
833 Parser->FieldData[HTTP_URI_FIELD_PATH].Length,
834 PathStr,
835 &ResultLength
836 );
837 if (EFI_ERROR (Status)) {
838 return Status;
839 }
840
841 PathStr[ResultLength] = '\0';
842 *Path = PathStr;
843 return EFI_SUCCESS;
844 }
845
846 /**
847 Release the resource of the URL parser.
848
849 @param[in] UrlParser Pointer to the parser.
850
851 **/
852 VOID
853 EFIAPI
854 HttpUrlFreeParser (
855 IN VOID *UrlParser
856 )
857 {
858 FreePool (UrlParser);
859 }
860
861 /**
862 Find a specified header field according to the field name.
863
864 @param[in] HeaderCount Number of HTTP header structures in Headers list.
865 @param[in] Headers Array containing list of HTTP headers.
866 @param[in] FieldName Null terminated string which describes a field name.
867
868 @return Pointer to the found header or NULL.
869
870 **/
871 EFI_HTTP_HEADER *
872 HttpIoFindHeader (
873 IN UINTN HeaderCount,
874 IN EFI_HTTP_HEADER *Headers,
875 IN CHAR8 *FieldName
876 )
877 {
878 UINTN Index;
879
880 if (HeaderCount == 0 || Headers == NULL || FieldName == NULL) {
881 return NULL;
882 }
883
884 for (Index = 0; Index < HeaderCount; Index++){
885 //
886 // Field names are case-insensitive (RFC 2616).
887 //
888 if (AsciiStriCmp (Headers[Index].FieldName, FieldName) == 0) {
889 return &Headers[Index];
890 }
891 }
892 return NULL;
893 }
894
895 typedef enum {
896 BodyParserBodyStart,
897 BodyParserBodyIdentity,
898 BodyParserChunkSizeStart,
899 BodyParserChunkSize,
900 BodyParserChunkSizeEndCR,
901 BodyParserChunkExtStart,
902 BodyParserChunkDataStart,
903 BodyParserChunkDataEnd,
904 BodyParserChunkDataEndCR,
905 BodyParserTrailer,
906 BodyParserLastCRLF,
907 BodyParserLastCRLFEnd,
908 BodyParserComplete,
909 BodyParserStateMax
910 } HTTP_BODY_PARSE_STATE;
911
912 typedef struct {
913 BOOLEAN IgnoreBody; // "MUST NOT" include a message-body
914 BOOLEAN IsChunked; // "chunked" transfer-coding.
915 BOOLEAN ContentLengthIsValid;
916 UINTN ContentLength; // Entity length (not the message-body length), invalid until ContentLengthIsValid is TRUE
917
918 HTTP_BODY_PARSER_CALLBACK Callback;
919 VOID *Context;
920 UINTN ParsedBodyLength;
921 HTTP_BODY_PARSE_STATE State;
922 UINTN CurrentChunkSize;
923 UINTN CurrentChunkParsedSize;
924 } HTTP_BODY_PARSER;
925
926 /**
927
928 Convert an Ascii char to its uppercase.
929
930 @param[in] Char Ascii character.
931
932 @return Uppercase value of the input Char.
933
934 **/
935 CHAR8
936 HttpIoCharToUpper (
937 IN CHAR8 Char
938 )
939 {
940 if (Char >= 'a' && Char <= 'z') {
941 return Char - ('a' - 'A');
942 }
943
944 return Char;
945 }
946
947 /**
948 Convert an hexadecimal char to a value of type UINTN.
949
950 @param[in] Char Ascii character.
951
952 @return Value translated from Char.
953
954 **/
955 UINTN
956 HttpIoHexCharToUintn (
957 IN CHAR8 Char
958 )
959 {
960 if (Char >= '0' && Char <= '9') {
961 return Char - '0';
962 }
963
964 return (10 + HttpIoCharToUpper (Char) - 'A');
965 }
966
967 /**
968 Get the value of the content length if there is a "Content-Length" header.
969
970 @param[in] HeaderCount Number of HTTP header structures in Headers.
971 @param[in] Headers Array containing list of HTTP headers.
972 @param[out] ContentLength Pointer to save the value of the content length.
973
974 @retval EFI_SUCCESS Successfully get the content length.
975 @retval EFI_NOT_FOUND No "Content-Length" header in the Headers.
976
977 **/
978 EFI_STATUS
979 HttpIoParseContentLengthHeader (
980 IN UINTN HeaderCount,
981 IN EFI_HTTP_HEADER *Headers,
982 OUT UINTN *ContentLength
983 )
984 {
985 EFI_HTTP_HEADER *Header;
986
987 Header = HttpIoFindHeader (HeaderCount, Headers, "Content-Length");
988 if (Header == NULL) {
989 return EFI_NOT_FOUND;
990 }
991
992 *ContentLength = AsciiStrDecimalToUintn (Header->FieldValue);
993 return EFI_SUCCESS;
994 }
995
996 /**
997
998 Check whether the HTTP message is using the "chunked" transfer-coding.
999
1000 @param[in] HeaderCount Number of HTTP header structures in Headers.
1001 @param[in] Headers Array containing list of HTTP headers.
1002
1003 @return The message is "chunked" transfer-coding (TRUE) or not (FALSE).
1004
1005 **/
1006 BOOLEAN
1007 HttpIoIsChunked (
1008 IN UINTN HeaderCount,
1009 IN EFI_HTTP_HEADER *Headers
1010 )
1011 {
1012 EFI_HTTP_HEADER *Header;
1013
1014
1015 Header = HttpIoFindHeader (HeaderCount, Headers, "Transfer-Encoding");
1016 if (Header == NULL) {
1017 return FALSE;
1018 }
1019
1020 if (AsciiStriCmp (Header->FieldValue, "identity") != 0) {
1021 return TRUE;
1022 }
1023
1024 return FALSE;
1025 }
1026
1027 /**
1028 Check whether the HTTP message should have a message-body.
1029
1030 @param[in] Method The HTTP method (e.g. GET, POST) for this HTTP message.
1031 @param[in] StatusCode Response status code returned by the remote host.
1032
1033 @return The message should have a message-body (FALSE) or not (TRUE).
1034
1035 **/
1036 BOOLEAN
1037 HttpIoNoMessageBody (
1038 IN EFI_HTTP_METHOD Method,
1039 IN EFI_HTTP_STATUS_CODE StatusCode
1040 )
1041 {
1042 //
1043 // RFC 2616:
1044 // All responses to the HEAD request method
1045 // MUST NOT include a message-body, even though the presence of entity-
1046 // header fields might lead one to believe they do. All 1xx
1047 // (informational), 204 (no content), and 304 (not modified) responses
1048 // MUST NOT include a message-body. All other responses do include a
1049 // message-body, although it MAY be of zero length.
1050 //
1051 if (Method == HttpMethodHead) {
1052 return TRUE;
1053 }
1054
1055 if ((StatusCode == HTTP_STATUS_100_CONTINUE) ||
1056 (StatusCode == HTTP_STATUS_101_SWITCHING_PROTOCOLS) ||
1057 (StatusCode == HTTP_STATUS_204_NO_CONTENT) ||
1058 (StatusCode == HTTP_STATUS_304_NOT_MODIFIED))
1059 {
1060 return TRUE;
1061 }
1062
1063 return FALSE;
1064 }
1065
1066 /**
1067 Initialize a HTTP message-body parser.
1068
1069 This function will create and initialize a HTTP message parser according to caller provided HTTP message
1070 header information. It is the caller's responsibility to free the buffer returned in *UrlParser by HttpFreeMsgParser().
1071
1072 @param[in] Method The HTTP method (e.g. GET, POST) for this HTTP message.
1073 @param[in] StatusCode Response status code returned by the remote host.
1074 @param[in] HeaderCount Number of HTTP header structures in Headers.
1075 @param[in] Headers Array containing list of HTTP headers.
1076 @param[in] Callback Callback function that is invoked when parsing the HTTP message-body,
1077 set to NULL to ignore all events.
1078 @param[in] Context Pointer to the context that will be passed to Callback.
1079 @param[out] MsgParser Pointer to the returned buffer to store the message parser.
1080
1081 @retval EFI_SUCCESS Successfully initialized the parser.
1082 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
1083 @retval EFI_INVALID_PARAMETER MsgParser is NULL or HeaderCount is not NULL but Headers is NULL.
1084 @retval Others Failed to initialize the parser.
1085
1086 **/
1087 EFI_STATUS
1088 EFIAPI
1089 HttpInitMsgParser (
1090 IN EFI_HTTP_METHOD Method,
1091 IN EFI_HTTP_STATUS_CODE StatusCode,
1092 IN UINTN HeaderCount,
1093 IN EFI_HTTP_HEADER *Headers,
1094 IN HTTP_BODY_PARSER_CALLBACK Callback,
1095 IN VOID *Context,
1096 OUT VOID **MsgParser
1097 )
1098 {
1099 EFI_STATUS Status;
1100 HTTP_BODY_PARSER *Parser;
1101
1102 if (HeaderCount != 0 && Headers == NULL) {
1103 return EFI_INVALID_PARAMETER;
1104 }
1105
1106 if (MsgParser == NULL) {
1107 return EFI_INVALID_PARAMETER;
1108 }
1109
1110 Parser = AllocateZeroPool (sizeof (HTTP_BODY_PARSER));
1111 if (Parser == NULL) {
1112 return EFI_OUT_OF_RESOURCES;
1113 }
1114
1115 Parser->State = BodyParserBodyStart;
1116
1117 //
1118 // Determine the message length according to RFC 2616.
1119 // 1. Check whether the message "MUST NOT" have a message-body.
1120 //
1121 Parser->IgnoreBody = HttpIoNoMessageBody (Method, StatusCode);
1122 //
1123 // 2. Check whether the message using "chunked" transfer-coding.
1124 //
1125 Parser->IsChunked = HttpIoIsChunked (HeaderCount, Headers);
1126 //
1127 // 3. Check whether the message has a Content-Length header field.
1128 //
1129 Status = HttpIoParseContentLengthHeader (HeaderCount, Headers, &Parser->ContentLength);
1130 if (!EFI_ERROR (Status)) {
1131 Parser->ContentLengthIsValid = TRUE;
1132 }
1133 //
1134 // 4. Range header is not supported now, so we won't meet media type "multipart/byteranges".
1135 // 5. By server closing the connection
1136 //
1137
1138 //
1139 // Set state to skip body parser if the message shouldn't have a message body.
1140 //
1141 if (Parser->IgnoreBody) {
1142 Parser->State = BodyParserComplete;
1143 } else {
1144 Parser->Callback = Callback;
1145 Parser->Context = Context;
1146 }
1147
1148 *MsgParser = Parser;
1149 return EFI_SUCCESS;
1150 }
1151
1152 /**
1153 Parse message body.
1154
1155 Parse BodyLength of message-body. This function can be called repeatedly to parse the message-body partially.
1156
1157 @param[in, out] MsgParser Pointer to the message parser.
1158 @param[in] BodyLength Length in bytes of the Body.
1159 @param[in] Body Pointer to the buffer of the message-body to be parsed.
1160
1161 @retval EFI_SUCCESS Successfully parse the message-body.
1162 @retval EFI_INVALID_PARAMETER MsgParser is NULL or Body is NULL or BodyLength is 0.
1163 @retval Others Operation aborted.
1164
1165 **/
1166 EFI_STATUS
1167 EFIAPI
1168 HttpParseMessageBody (
1169 IN OUT VOID *MsgParser,
1170 IN UINTN BodyLength,
1171 IN CHAR8 *Body
1172 )
1173 {
1174 CHAR8 *Char;
1175 UINTN RemainderLengthInThis;
1176 UINTN LengthForCallback;
1177 EFI_STATUS Status;
1178 HTTP_BODY_PARSER *Parser;
1179
1180 if (BodyLength == 0 || Body == NULL) {
1181 return EFI_INVALID_PARAMETER;
1182 }
1183
1184 if (MsgParser == NULL) {
1185 return EFI_INVALID_PARAMETER;
1186 }
1187
1188 Parser = (HTTP_BODY_PARSER*) MsgParser;
1189
1190 if (Parser->IgnoreBody) {
1191 Parser->State = BodyParserComplete;
1192 if (Parser->Callback != NULL) {
1193 Status = Parser->Callback (
1194 BodyParseEventOnComplete,
1195 Body,
1196 0,
1197 Parser->Context
1198 );
1199 if (EFI_ERROR (Status)) {
1200 return Status;
1201 }
1202 }
1203 return EFI_SUCCESS;
1204 }
1205
1206 if (Parser->State == BodyParserBodyStart) {
1207 Parser->ParsedBodyLength = 0;
1208 if (Parser->IsChunked) {
1209 Parser->State = BodyParserChunkSizeStart;
1210 } else {
1211 Parser->State = BodyParserBodyIdentity;
1212 }
1213 }
1214
1215 //
1216 // The message body might be truncated in anywhere, so we need to parse is byte-by-byte.
1217 //
1218 for (Char = Body; Char < Body + BodyLength; ) {
1219
1220 switch (Parser->State) {
1221 case BodyParserStateMax:
1222 return EFI_ABORTED;
1223
1224 case BodyParserBodyIdentity:
1225 //
1226 // Identity transfer-coding, just notify user to save the body data.
1227 //
1228 if (Parser->Callback != NULL) {
1229 Status = Parser->Callback (
1230 BodyParseEventOnData,
1231 Char,
1232 MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength),
1233 Parser->Context
1234 );
1235 if (EFI_ERROR (Status)) {
1236 return Status;
1237 }
1238 }
1239 Char += MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength);
1240 Parser->ParsedBodyLength += MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength);
1241 if (Parser->ParsedBodyLength == Parser->ContentLength) {
1242 Parser->State = BodyParserComplete;
1243 if (Parser->Callback != NULL) {
1244 Status = Parser->Callback (
1245 BodyParseEventOnComplete,
1246 Char,
1247 0,
1248 Parser->Context
1249 );
1250 if (EFI_ERROR (Status)) {
1251 return Status;
1252 }
1253 }
1254 }
1255 break;
1256
1257 case BodyParserChunkSizeStart:
1258 //
1259 // First byte of chunk-size, the chunk-size might be truncated.
1260 //
1261 Parser->CurrentChunkSize = 0;
1262 Parser->State = BodyParserChunkSize;
1263 case BodyParserChunkSize:
1264 if (!NET_IS_HEX_CHAR (*Char)) {
1265 if (*Char == ';') {
1266 Parser->State = BodyParserChunkExtStart;
1267 Char++;
1268 } else if (*Char == '\r') {
1269 Parser->State = BodyParserChunkSizeEndCR;
1270 Char++;
1271 } else {
1272 Parser->State = BodyParserStateMax;
1273 }
1274 break;
1275 }
1276
1277 if (Parser->CurrentChunkSize > (((~((UINTN) 0)) - 16) / 16)) {
1278 return EFI_INVALID_PARAMETER;
1279 }
1280 Parser->CurrentChunkSize = Parser->CurrentChunkSize * 16 + HttpIoHexCharToUintn (*Char);
1281 Char++;
1282 break;
1283
1284 case BodyParserChunkExtStart:
1285 //
1286 // Ignore all the chunk extensions.
1287 //
1288 if (*Char == '\r') {
1289 Parser->State = BodyParserChunkSizeEndCR;
1290 }
1291 Char++;
1292 break;
1293
1294 case BodyParserChunkSizeEndCR:
1295 if (*Char != '\n') {
1296 Parser->State = BodyParserStateMax;
1297 break;
1298 }
1299 Char++;
1300 if (Parser->CurrentChunkSize == 0) {
1301 //
1302 // The last chunk has been parsed and now assumed the state
1303 // of HttpBodyParse is ParserLastCRLF. So it need to decide
1304 // whether the rest message is trailer or last CRLF in the next round.
1305 //
1306 Parser->ContentLengthIsValid = TRUE;
1307 Parser->State = BodyParserLastCRLF;
1308 break;
1309 }
1310 Parser->State = BodyParserChunkDataStart;
1311 Parser->CurrentChunkParsedSize = 0;
1312 break;
1313
1314 case BodyParserLastCRLF:
1315 //
1316 // Judge the byte is belong to the Last CRLF or trailer, and then
1317 // configure the state of HttpBodyParse to corresponding state.
1318 //
1319 if (*Char == '\r') {
1320 Char++;
1321 Parser->State = BodyParserLastCRLFEnd;
1322 break;
1323 } else {
1324 Parser->State = BodyParserTrailer;
1325 break;
1326 }
1327
1328 case BodyParserLastCRLFEnd:
1329 if (*Char == '\n') {
1330 Parser->State = BodyParserComplete;
1331 Char++;
1332 if (Parser->Callback != NULL) {
1333 Status = Parser->Callback (
1334 BodyParseEventOnComplete,
1335 Char,
1336 0,
1337 Parser->Context
1338 );
1339 if (EFI_ERROR (Status)) {
1340 return Status;
1341 }
1342 }
1343 break;
1344 } else {
1345 Parser->State = BodyParserStateMax;
1346 break;
1347 }
1348
1349 case BodyParserTrailer:
1350 if (*Char == '\r') {
1351 Parser->State = BodyParserChunkSizeEndCR;
1352 }
1353 Char++;
1354 break;
1355
1356 case BodyParserChunkDataStart:
1357 //
1358 // First byte of chunk-data, the chunk data also might be truncated.
1359 //
1360 RemainderLengthInThis = BodyLength - (Char - Body);
1361 LengthForCallback = MIN (Parser->CurrentChunkSize - Parser->CurrentChunkParsedSize, RemainderLengthInThis);
1362 if (Parser->Callback != NULL) {
1363 Status = Parser->Callback (
1364 BodyParseEventOnData,
1365 Char,
1366 LengthForCallback,
1367 Parser->Context
1368 );
1369 if (EFI_ERROR (Status)) {
1370 return Status;
1371 }
1372 }
1373 Char += LengthForCallback;
1374 Parser->ContentLength += LengthForCallback;
1375 Parser->CurrentChunkParsedSize += LengthForCallback;
1376 if (Parser->CurrentChunkParsedSize == Parser->CurrentChunkSize) {
1377 Parser->State = BodyParserChunkDataEnd;
1378 }
1379 break;
1380
1381 case BodyParserChunkDataEnd:
1382 if (*Char == '\r') {
1383 Parser->State = BodyParserChunkDataEndCR;
1384 } else {
1385 Parser->State = BodyParserStateMax;
1386 }
1387 Char++;
1388 break;
1389
1390 case BodyParserChunkDataEndCR:
1391 if (*Char != '\n') {
1392 Parser->State = BodyParserStateMax;
1393 break;
1394 }
1395 Char++;
1396 Parser->State = BodyParserChunkSizeStart;
1397 break;
1398
1399 default:
1400 break;
1401 }
1402
1403 }
1404
1405 if (Parser->State == BodyParserStateMax) {
1406 return EFI_ABORTED;
1407 }
1408
1409 return EFI_SUCCESS;
1410 }
1411
1412 /**
1413 Check whether the message-body is complete or not.
1414
1415 @param[in] MsgParser Pointer to the message parser.
1416
1417 @retval TRUE Message-body is complete.
1418 @retval FALSE Message-body is not complete.
1419
1420 **/
1421 BOOLEAN
1422 EFIAPI
1423 HttpIsMessageComplete (
1424 IN VOID *MsgParser
1425 )
1426 {
1427 HTTP_BODY_PARSER *Parser;
1428
1429 Parser = (HTTP_BODY_PARSER*) MsgParser;
1430
1431 if (Parser->State == BodyParserComplete) {
1432 return TRUE;
1433 }
1434 return FALSE;
1435 }
1436
1437 /**
1438 Get the content length of the entity.
1439
1440 Note that in trunk transfer, the entity length is not valid until the whole message body is received.
1441
1442 @param[in] MsgParser Pointer to the message parser.
1443 @param[out] ContentLength Pointer to store the length of the entity.
1444
1445 @retval EFI_SUCCESS Successfully to get the entity length.
1446 @retval EFI_NOT_READY Entity length is not valid yet.
1447 @retval EFI_INVALID_PARAMETER MsgParser is NULL or ContentLength is NULL.
1448
1449 **/
1450 EFI_STATUS
1451 EFIAPI
1452 HttpGetEntityLength (
1453 IN VOID *MsgParser,
1454 OUT UINTN *ContentLength
1455 )
1456 {
1457 HTTP_BODY_PARSER *Parser;
1458
1459 if (MsgParser == NULL || ContentLength == NULL) {
1460 return EFI_INVALID_PARAMETER;
1461 }
1462
1463 Parser = (HTTP_BODY_PARSER*) MsgParser;
1464
1465 if (!Parser->ContentLengthIsValid) {
1466 return EFI_NOT_READY;
1467 }
1468
1469 *ContentLength = Parser->ContentLength;
1470 return EFI_SUCCESS;
1471 }
1472
1473 /**
1474 Release the resource of the message parser.
1475
1476 @param[in] MsgParser Pointer to the message parser.
1477
1478 **/
1479 VOID
1480 EFIAPI
1481 HttpFreeMsgParser (
1482 IN VOID *MsgParser
1483 )
1484 {
1485 FreePool (MsgParser);
1486 }