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.
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
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.
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>
24 #define BIT(x) (1 << x)
26 #define NET_IS_HEX_CHAR(Ch) \
27 ((('0' <= (Ch)) && ((Ch) <= '9')) || \
28 (('A' <= (Ch)) && ((Ch) <= 'F')) || \
29 (('a' <= (Ch)) && ((Ch) <= 'f')))
32 // Field index of the HTTP URL parse result.
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
45 // Structure to store the parse result of a HTTP URL.
50 } HTTP_URL_FILED_DATA
;
54 HTTP_URL_FILED_DATA FieldData
[HTTP_URI_FIELD_MAX
];
60 UrlParserSchemeColon
, // ":"
61 UrlParserSchemeColonSlash
, // ":/"
62 UrlParserSchemeColonSlashSlash
, // "://"
64 UrlParserAtInAuthority
,
66 UrlParserQueryStart
, // "?"
68 UrlParserFragmentStart
, // "#"
71 UrlParserHostStart
, // "@"
73 UrlParserHostIpv6
, // "["(Ipv6 address) "]"
74 UrlParserPortStart
, // ":"
77 } HTTP_URL_PARSE_STATE
;
80 Decode a percent-encoded URI component to the ASCII character.
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))
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.
91 @retval EFI_SUCCESS Successfully decoded the URI.
92 @retval EFI_INVALID_PARAMETER Buffer is not a valid percent-encoded string.
99 IN UINT32 BufferLength
,
100 OUT CHAR8
*ResultBuffer
,
101 OUT UINT32
*ResultLength
108 if (Buffer
== NULL
|| BufferLength
== 0 || ResultBuffer
== NULL
) {
109 return EFI_INVALID_PARAMETER
;
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
;
120 HexStr
[0] = Buffer
[Index
+1];
121 HexStr
[1] = Buffer
[Index
+2];
122 ResultBuffer
[Offset
] = (CHAR8
) AsciiStrHexToUintn (HexStr
);
125 ResultBuffer
[Offset
] = Buffer
[Index
];
131 *ResultLength
= (UINT32
) Offset
;
137 This function return the updated state according to the input state and next character of
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.
145 @return Updated state value.
148 NetHttpParseAuthorityChar (
150 IN HTTP_URL_PARSE_STATE State
,
151 IN BOOLEAN
*IsRightBracket
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.
161 if (Char
== ' ' || Char
== '\r' || Char
== '\n') {
162 return UrlParserStateMax
;
166 // authority = [ userinfo "@" ] host [ ":" port ]
169 case UrlParserUserInfo
:
171 return UrlParserHostStart
;
176 case UrlParserHostStart
:
178 return UrlParserHostIpv6
;
182 return UrlParserPortStart
;
185 return UrlParserHost
;
187 case UrlParserHostIpv6
:
189 *IsRightBracket
= TRUE
;
192 if (Char
== ':' && *IsRightBracket
) {
193 return UrlParserPortStart
;
195 return UrlParserHostIpv6
;
198 case UrlParserPortStart
:
199 return UrlParserPort
;
209 This function parse the authority component of the input URL and update the parser.
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.
215 @retval EFI_SUCCESS Successfully parse the authority.
216 @retval Other Error happened.
220 NetHttpParseAuthority (
223 IN OUT HTTP_URL_PARSER
*UrlParser
229 HTTP_URL_PARSE_STATE State
;
232 BOOLEAN IsrightBracket
;
234 ASSERT ((UrlParser
->FieldBitMap
& BIT (HTTP_URI_FIELD_AUTHORITY
)) != 0);
237 // authority = [ userinfo "@" ] host [ ":" port ]
240 State
= UrlParserUserInfo
;
242 State
= UrlParserHost
;
245 IsrightBracket
= FALSE
;
246 Field
= HTTP_URI_FIELD_MAX
;
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
);
253 case UrlParserStateMax
:
254 return EFI_INVALID_PARAMETER
;
256 case UrlParserHostStart
:
257 case UrlParserPortStart
:
260 case UrlParserUserInfo
:
261 Field
= HTTP_URI_FIELD_USERINFO
;
265 Field
= HTTP_URI_FIELD_HOST
;
268 case UrlParserHostIpv6
:
269 Field
= HTTP_URI_FIELD_HOST
;
273 Field
= HTTP_URI_FIELD_PORT
;
281 // Field not changed, count the length.
283 ASSERT (Field
< HTTP_URI_FIELD_MAX
);
284 if (Field
== OldField
) {
285 UrlParser
->FieldData
[Field
].Length
++;
292 UrlParser
->FieldBitMap
|= BIT (Field
);
293 UrlParser
->FieldData
[Field
].Offset
= (UINT32
) (Char
- Url
);
294 UrlParser
->FieldData
[Field
].Length
= 1;
302 This function return the updated state according to the input state and next character of a URL.
304 @param[in] Char Next character.
305 @param[in] State Current value of the parser state machine.
307 @return Updated state value.
311 NetHttpParseUrlChar (
313 IN HTTP_URL_PARSE_STATE State
316 if (Char
== ' ' || Char
== '\r' || Char
== '\n') {
317 return UrlParserStateMax
;
321 // http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
323 // Request-URI = "*" | absolute-URI | path-absolute | authority
325 // absolute-URI = scheme ":" hier-part [ "?" query ]
326 // path-absolute = "/" [ segment-nz *( "/" segment ) ]
327 // authority = [ userinfo "@" ] host [ ":" port ]
330 case UrlParserUrlStart
:
331 if (Char
== '*' || Char
== '/') {
332 return UrlParserPath
;
334 return UrlParserScheme
;
336 case UrlParserScheme
:
338 return UrlParserSchemeColon
;
342 case UrlParserSchemeColon
:
344 return UrlParserSchemeColonSlash
;
348 case UrlParserSchemeColonSlash
:
350 return UrlParserSchemeColonSlashSlash
;
354 case UrlParserAtInAuthority
:
356 return UrlParserStateMax
;
359 case UrlParserAuthority
:
360 case UrlParserSchemeColonSlashSlash
:
362 return UrlParserAtInAuthority
;
365 return UrlParserPath
;
368 return UrlParserQueryStart
;
371 return UrlParserFragmentStart
;
373 return UrlParserAuthority
;
377 return UrlParserQueryStart
;
380 return UrlParserFragmentStart
;
385 case UrlParserQueryStart
:
387 return UrlParserFragmentStart
;
389 return UrlParserQuery
;
391 case UrlParserFragmentStart
:
392 return UrlParserFragment
;
401 Create a URL parser for the input URL string.
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().
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.
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.
422 IN BOOLEAN IsConnectMethod
,
426 HTTP_URL_PARSE_STATE State
;
432 HTTP_URL_PARSER
*Parser
;
434 if (Url
== NULL
|| Length
== 0 || UrlParser
== NULL
) {
435 return EFI_INVALID_PARAMETER
;
438 Parser
= AllocateZeroPool (sizeof (HTTP_URL_PARSER
));
439 if (Parser
== NULL
) {
440 return EFI_OUT_OF_RESOURCES
;
443 if (IsConnectMethod
) {
445 // According to RFC 2616, the authority form is only used by the CONNECT method.
447 State
= UrlParserAuthority
;
449 State
= UrlParserUrlStart
;
452 Field
= HTTP_URI_FIELD_MAX
;
455 for (Char
= Url
; Char
< Url
+ Length
; Char
++) {
457 // Update state machine accoring to next char.
459 State
= NetHttpParseUrlChar (*Char
, State
);
462 case UrlParserStateMax
:
463 return EFI_INVALID_PARAMETER
;
465 case UrlParserSchemeColon
:
466 case UrlParserSchemeColonSlash
:
467 case UrlParserSchemeColonSlashSlash
:
468 case UrlParserQueryStart
:
469 case UrlParserFragmentStart
:
471 // Skip all the delimiting char: "://" "?" "@"
475 case UrlParserScheme
:
476 Field
= HTTP_URI_FIELD_SCHEME
;
479 case UrlParserAtInAuthority
:
481 case UrlParserAuthority
:
482 Field
= HTTP_URI_FIELD_AUTHORITY
;
486 Field
= HTTP_URI_FIELD_PATH
;
490 Field
= HTTP_URI_FIELD_QUERY
;
493 case UrlParserFragment
:
494 Field
= HTTP_URI_FIELD_FRAGMENT
;
502 // Field not changed, count the length.
504 ASSERT (Field
< HTTP_URI_FIELD_MAX
);
505 if (Field
== OldField
) {
506 Parser
->FieldData
[Field
].Length
++;
513 Parser
->FieldBitMap
|= BIT (Field
);
514 Parser
->FieldData
[Field
].Offset
= (UINT32
) (Char
- Url
);
515 Parser
->FieldData
[Field
].Length
= 1;
520 // If has authority component, continue to parse the username, host and port.
522 if ((Parser
->FieldBitMap
& BIT (HTTP_URI_FIELD_AUTHORITY
)) != 0) {
523 Status
= NetHttpParseAuthority (Url
, FoundAt
, Parser
);
524 if (EFI_ERROR (Status
)) {
534 Get the Hostname from a HTTP URL.
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.
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.
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.
560 HTTP_URL_PARSER
*Parser
;
562 if (Url
== NULL
|| UrlParser
== NULL
|| HostName
== NULL
) {
563 return EFI_INVALID_PARAMETER
;
566 Parser
= (HTTP_URL_PARSER
*) UrlParser
;
568 if ((Parser
->FieldBitMap
& BIT (HTTP_URI_FIELD_HOST
)) == 0) {
569 return EFI_NOT_FOUND
;
572 Name
= AllocatePool (Parser
->FieldData
[HTTP_URI_FIELD_HOST
].Length
+ 1);
574 return EFI_OUT_OF_RESOURCES
;
577 Status
= UriPercentDecode (
578 Url
+ Parser
->FieldData
[HTTP_URI_FIELD_HOST
].Offset
,
579 Parser
->FieldData
[HTTP_URI_FIELD_HOST
].Length
,
583 if (EFI_ERROR (Status
)) {
587 Name
[ResultLength
] = '\0';
594 Get the IPv4 address from a HTTP URL.
596 This function will return the IPv4 address according to the Url and previous parse result.
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.
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.
613 OUT EFI_IPv4_ADDRESS
*Ip4Address
619 HTTP_URL_PARSER
*Parser
;
621 if (Url
== NULL
|| UrlParser
== NULL
|| Ip4Address
== NULL
) {
622 return EFI_INVALID_PARAMETER
;
625 Parser
= (HTTP_URL_PARSER
*) UrlParser
;
627 if ((Parser
->FieldBitMap
& BIT (HTTP_URI_FIELD_HOST
)) == 0) {
628 return EFI_INVALID_PARAMETER
;
631 Ip4String
= AllocatePool (Parser
->FieldData
[HTTP_URI_FIELD_HOST
].Length
+ 1);
632 if (Ip4String
== NULL
) {
633 return EFI_OUT_OF_RESOURCES
;
636 Status
= UriPercentDecode (
637 Url
+ Parser
->FieldData
[HTTP_URI_FIELD_HOST
].Offset
,
638 Parser
->FieldData
[HTTP_URI_FIELD_HOST
].Length
,
642 if (EFI_ERROR (Status
)) {
646 Ip4String
[ResultLength
] = '\0';
647 Status
= NetLibAsciiStrToIp4 (Ip4String
, Ip4Address
);
648 FreePool (Ip4String
);
654 Get the IPv6 address from a HTTP URL.
656 This function will return the IPv6 address according to the Url and previous parse result.
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.
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.
673 OUT EFI_IPv6_ADDRESS
*Ip6Address
681 HTTP_URL_PARSER
*Parser
;
683 if (Url
== NULL
|| UrlParser
== NULL
|| Ip6Address
== NULL
) {
684 return EFI_INVALID_PARAMETER
;
687 Parser
= (HTTP_URL_PARSER
*) UrlParser
;
689 if ((Parser
->FieldBitMap
& BIT (HTTP_URI_FIELD_HOST
)) == 0) {
690 return EFI_INVALID_PARAMETER
;
694 // IP-literal = "[" ( IPv6address / IPvFuture ) "]"
696 Length
= Parser
->FieldData
[HTTP_URI_FIELD_HOST
].Length
;
698 return EFI_INVALID_PARAMETER
;
701 Ptr
= Url
+ Parser
->FieldData
[HTTP_URI_FIELD_HOST
].Offset
;
702 if ((Ptr
[0] != '[') || (Ptr
[Length
- 1] != ']')) {
703 return EFI_INVALID_PARAMETER
;
706 Ip6String
= AllocatePool (Length
);
707 if (Ip6String
== NULL
) {
708 return EFI_OUT_OF_RESOURCES
;
711 Status
= UriPercentDecode (
717 if (EFI_ERROR (Status
)) {
721 Ip6String
[ResultLength
] = '\0';
722 Status
= NetLibAsciiStrToIp6 (Ip6String
, Ip6Address
);
723 FreePool (Ip6String
);
729 Get the port number from a HTTP URL.
731 This function will return the port number according to the Url and previous parse result.
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.
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.
754 HTTP_URL_PARSER
*Parser
;
756 if (Url
== NULL
|| UrlParser
== NULL
|| Port
== NULL
) {
757 return EFI_INVALID_PARAMETER
;
760 Parser
= (HTTP_URL_PARSER
*) UrlParser
;
762 if ((Parser
->FieldBitMap
& BIT (HTTP_URI_FIELD_PORT
)) == 0) {
763 return EFI_INVALID_PARAMETER
;
766 PortString
= AllocatePool (Parser
->FieldData
[HTTP_URI_FIELD_PORT
].Length
+ 1);
767 if (PortString
== NULL
) {
768 return EFI_OUT_OF_RESOURCES
;
771 Status
= UriPercentDecode (
772 Url
+ Parser
->FieldData
[HTTP_URI_FIELD_PORT
].Offset
,
773 Parser
->FieldData
[HTTP_URI_FIELD_PORT
].Length
,
777 if (EFI_ERROR (Status
)) {
781 PortString
[ResultLength
] = '\0';
782 *Port
= (UINT16
) AsciiStrDecimalToUintn (Url
+ Parser
->FieldData
[HTTP_URI_FIELD_PORT
].Offset
);
788 Get the Path from a HTTP URL.
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.
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.
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.
814 HTTP_URL_PARSER
*Parser
;
816 if (Url
== NULL
|| UrlParser
== NULL
|| Path
== NULL
) {
817 return EFI_INVALID_PARAMETER
;
820 Parser
= (HTTP_URL_PARSER
*) UrlParser
;
822 if ((Parser
->FieldBitMap
& BIT (HTTP_URI_FIELD_PATH
)) == 0) {
823 return EFI_NOT_FOUND
;
826 PathStr
= AllocatePool (Parser
->FieldData
[HTTP_URI_FIELD_PATH
].Length
+ 1);
827 if (PathStr
== NULL
) {
828 return EFI_OUT_OF_RESOURCES
;
831 Status
= UriPercentDecode (
832 Url
+ Parser
->FieldData
[HTTP_URI_FIELD_PATH
].Offset
,
833 Parser
->FieldData
[HTTP_URI_FIELD_PATH
].Length
,
837 if (EFI_ERROR (Status
)) {
841 PathStr
[ResultLength
] = '\0';
847 Release the resource of the URL parser.
849 @param[in] UrlParser Pointer to the parser.
858 FreePool (UrlParser
);
862 Find a specified header field according to the field name.
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.
868 @return Pointer to the found header or NULL.
873 IN UINTN HeaderCount
,
874 IN EFI_HTTP_HEADER
*Headers
,
880 if (HeaderCount
== 0 || Headers
== NULL
|| FieldName
== NULL
) {
884 for (Index
= 0; Index
< HeaderCount
; Index
++){
886 // Field names are case-insensitive (RFC 2616).
888 if (AsciiStriCmp (Headers
[Index
].FieldName
, FieldName
) == 0) {
889 return &Headers
[Index
];
897 BodyParserBodyIdentity
,
898 BodyParserChunkSizeStart
,
900 BodyParserChunkSizeEndCR
,
901 BodyParserChunkExtStart
,
902 BodyParserChunkDataStart
,
903 BodyParserChunkDataEnd
,
904 BodyParserChunkDataEndCR
,
907 BodyParserLastCRLFEnd
,
910 } HTTP_BODY_PARSE_STATE
;
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
918 HTTP_BODY_PARSER_CALLBACK Callback
;
920 UINTN ParsedBodyLength
;
921 HTTP_BODY_PARSE_STATE State
;
922 UINTN CurrentChunkSize
;
923 UINTN CurrentChunkParsedSize
;
928 Convert an Ascii char to its uppercase.
930 @param[in] Char Ascii character.
932 @return Uppercase value of the input Char.
940 if (Char
>= 'a' && Char
<= 'z') {
941 return Char
- ('a' - 'A');
948 Convert an hexadecimal char to a value of type UINTN.
950 @param[in] Char Ascii character.
952 @return Value translated from Char.
956 HttpIoHexCharToUintn (
960 if (Char
>= '0' && Char
<= '9') {
964 return (10 + HttpIoCharToUpper (Char
) - 'A');
968 Get the value of the content length if there is a "Content-Length" header.
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.
974 @retval EFI_SUCCESS Successfully get the content length.
975 @retval EFI_NOT_FOUND No "Content-Length" header in the Headers.
979 HttpIoParseContentLengthHeader (
980 IN UINTN HeaderCount
,
981 IN EFI_HTTP_HEADER
*Headers
,
982 OUT UINTN
*ContentLength
985 EFI_HTTP_HEADER
*Header
;
987 Header
= HttpIoFindHeader (HeaderCount
, Headers
, "Content-Length");
988 if (Header
== NULL
) {
989 return EFI_NOT_FOUND
;
992 *ContentLength
= AsciiStrDecimalToUintn (Header
->FieldValue
);
998 Check whether the HTTP message is using the "chunked" transfer-coding.
1000 @param[in] HeaderCount Number of HTTP header structures in Headers.
1001 @param[in] Headers Array containing list of HTTP headers.
1003 @return The message is "chunked" transfer-coding (TRUE) or not (FALSE).
1008 IN UINTN HeaderCount
,
1009 IN EFI_HTTP_HEADER
*Headers
1012 EFI_HTTP_HEADER
*Header
;
1015 Header
= HttpIoFindHeader (HeaderCount
, Headers
, "Transfer-Encoding");
1016 if (Header
== NULL
) {
1020 if (AsciiStriCmp (Header
->FieldValue
, "identity") != 0) {
1028 Check whether the HTTP message should have a message-body.
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.
1033 @return The message should have a message-body (FALSE) or not (TRUE).
1037 HttpIoNoMessageBody (
1038 IN EFI_HTTP_METHOD Method
,
1039 IN EFI_HTTP_STATUS_CODE StatusCode
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.
1051 if (Method
== HttpMethodHead
) {
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
))
1067 Initialize a HTTP message-body parser.
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().
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.
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.
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
,
1096 OUT VOID
**MsgParser
1100 HTTP_BODY_PARSER
*Parser
;
1102 if (HeaderCount
!= 0 && Headers
== NULL
) {
1103 return EFI_INVALID_PARAMETER
;
1106 if (MsgParser
== NULL
) {
1107 return EFI_INVALID_PARAMETER
;
1110 Parser
= AllocateZeroPool (sizeof (HTTP_BODY_PARSER
));
1111 if (Parser
== NULL
) {
1112 return EFI_OUT_OF_RESOURCES
;
1115 Parser
->State
= BodyParserBodyStart
;
1118 // Determine the message length according to RFC 2616.
1119 // 1. Check whether the message "MUST NOT" have a message-body.
1121 Parser
->IgnoreBody
= HttpIoNoMessageBody (Method
, StatusCode
);
1123 // 2. Check whether the message using "chunked" transfer-coding.
1125 Parser
->IsChunked
= HttpIoIsChunked (HeaderCount
, Headers
);
1127 // 3. Check whether the message has a Content-Length header field.
1129 Status
= HttpIoParseContentLengthHeader (HeaderCount
, Headers
, &Parser
->ContentLength
);
1130 if (!EFI_ERROR (Status
)) {
1131 Parser
->ContentLengthIsValid
= TRUE
;
1134 // 4. Range header is not supported now, so we won't meet media type "multipart/byteranges".
1135 // 5. By server closing the connection
1139 // Set state to skip body parser if the message shouldn't have a message body.
1141 if (Parser
->IgnoreBody
) {
1142 Parser
->State
= BodyParserComplete
;
1144 Parser
->Callback
= Callback
;
1145 Parser
->Context
= Context
;
1148 *MsgParser
= Parser
;
1155 Parse BodyLength of message-body. This function can be called repeatedly to parse the message-body partially.
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.
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.
1168 HttpParseMessageBody (
1169 IN OUT VOID
*MsgParser
,
1170 IN UINTN BodyLength
,
1175 UINTN RemainderLengthInThis
;
1176 UINTN LengthForCallback
;
1178 HTTP_BODY_PARSER
*Parser
;
1180 if (BodyLength
== 0 || Body
== NULL
) {
1181 return EFI_INVALID_PARAMETER
;
1184 if (MsgParser
== NULL
) {
1185 return EFI_INVALID_PARAMETER
;
1188 Parser
= (HTTP_BODY_PARSER
*) MsgParser
;
1190 if (Parser
->IgnoreBody
) {
1191 Parser
->State
= BodyParserComplete
;
1192 if (Parser
->Callback
!= NULL
) {
1193 Status
= Parser
->Callback (
1194 BodyParseEventOnComplete
,
1199 if (EFI_ERROR (Status
)) {
1206 if (Parser
->State
== BodyParserBodyStart
) {
1207 Parser
->ParsedBodyLength
= 0;
1208 if (Parser
->IsChunked
) {
1209 Parser
->State
= BodyParserChunkSizeStart
;
1211 Parser
->State
= BodyParserBodyIdentity
;
1216 // The message body might be truncated in anywhere, so we need to parse is byte-by-byte.
1218 for (Char
= Body
; Char
< Body
+ BodyLength
; ) {
1220 switch (Parser
->State
) {
1221 case BodyParserStateMax
:
1224 case BodyParserBodyIdentity
:
1226 // Identity transfer-coding, just notify user to save the body data.
1228 if (Parser
->Callback
!= NULL
) {
1229 Status
= Parser
->Callback (
1230 BodyParseEventOnData
,
1232 MIN (BodyLength
, Parser
->ContentLength
- Parser
->ParsedBodyLength
),
1235 if (EFI_ERROR (Status
)) {
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
,
1250 if (EFI_ERROR (Status
)) {
1257 case BodyParserChunkSizeStart
:
1259 // First byte of chunk-size, the chunk-size might be truncated.
1261 Parser
->CurrentChunkSize
= 0;
1262 Parser
->State
= BodyParserChunkSize
;
1263 case BodyParserChunkSize
:
1264 if (!NET_IS_HEX_CHAR (*Char
)) {
1266 Parser
->State
= BodyParserChunkExtStart
;
1268 } else if (*Char
== '\r') {
1269 Parser
->State
= BodyParserChunkSizeEndCR
;
1272 Parser
->State
= BodyParserStateMax
;
1277 if (Parser
->CurrentChunkSize
> (((~((UINTN
) 0)) - 16) / 16)) {
1278 return EFI_INVALID_PARAMETER
;
1280 Parser
->CurrentChunkSize
= Parser
->CurrentChunkSize
* 16 + HttpIoHexCharToUintn (*Char
);
1284 case BodyParserChunkExtStart
:
1286 // Ignore all the chunk extensions.
1288 if (*Char
== '\r') {
1289 Parser
->State
= BodyParserChunkSizeEndCR
;
1294 case BodyParserChunkSizeEndCR
:
1295 if (*Char
!= '\n') {
1296 Parser
->State
= BodyParserStateMax
;
1300 if (Parser
->CurrentChunkSize
== 0) {
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.
1306 Parser
->ContentLengthIsValid
= TRUE
;
1307 Parser
->State
= BodyParserLastCRLF
;
1310 Parser
->State
= BodyParserChunkDataStart
;
1311 Parser
->CurrentChunkParsedSize
= 0;
1314 case BodyParserLastCRLF
:
1316 // Judge the byte is belong to the Last CRLF or trailer, and then
1317 // configure the state of HttpBodyParse to corresponding state.
1319 if (*Char
== '\r') {
1321 Parser
->State
= BodyParserLastCRLFEnd
;
1324 Parser
->State
= BodyParserTrailer
;
1328 case BodyParserLastCRLFEnd
:
1329 if (*Char
== '\n') {
1330 Parser
->State
= BodyParserComplete
;
1332 if (Parser
->Callback
!= NULL
) {
1333 Status
= Parser
->Callback (
1334 BodyParseEventOnComplete
,
1339 if (EFI_ERROR (Status
)) {
1345 Parser
->State
= BodyParserStateMax
;
1349 case BodyParserTrailer
:
1350 if (*Char
== '\r') {
1351 Parser
->State
= BodyParserChunkSizeEndCR
;
1356 case BodyParserChunkDataStart
:
1358 // First byte of chunk-data, the chunk data also might be truncated.
1360 RemainderLengthInThis
= BodyLength
- (Char
- Body
);
1361 LengthForCallback
= MIN (Parser
->CurrentChunkSize
- Parser
->CurrentChunkParsedSize
, RemainderLengthInThis
);
1362 if (Parser
->Callback
!= NULL
) {
1363 Status
= Parser
->Callback (
1364 BodyParseEventOnData
,
1369 if (EFI_ERROR (Status
)) {
1373 Char
+= LengthForCallback
;
1374 Parser
->ContentLength
+= LengthForCallback
;
1375 Parser
->CurrentChunkParsedSize
+= LengthForCallback
;
1376 if (Parser
->CurrentChunkParsedSize
== Parser
->CurrentChunkSize
) {
1377 Parser
->State
= BodyParserChunkDataEnd
;
1381 case BodyParserChunkDataEnd
:
1382 if (*Char
== '\r') {
1383 Parser
->State
= BodyParserChunkDataEndCR
;
1385 Parser
->State
= BodyParserStateMax
;
1390 case BodyParserChunkDataEndCR
:
1391 if (*Char
!= '\n') {
1392 Parser
->State
= BodyParserStateMax
;
1396 Parser
->State
= BodyParserChunkSizeStart
;
1405 if (Parser
->State
== BodyParserStateMax
) {
1413 Check whether the message-body is complete or not.
1415 @param[in] MsgParser Pointer to the message parser.
1417 @retval TRUE Message-body is complete.
1418 @retval FALSE Message-body is not complete.
1423 HttpIsMessageComplete (
1427 HTTP_BODY_PARSER
*Parser
;
1429 Parser
= (HTTP_BODY_PARSER
*) MsgParser
;
1431 if (Parser
->State
== BodyParserComplete
) {
1438 Get the content length of the entity.
1440 Note that in trunk transfer, the entity length is not valid until the whole message body is received.
1442 @param[in] MsgParser Pointer to the message parser.
1443 @param[out] ContentLength Pointer to store the length of the entity.
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.
1452 HttpGetEntityLength (
1454 OUT UINTN
*ContentLength
1457 HTTP_BODY_PARSER
*Parser
;
1459 if (MsgParser
== NULL
|| ContentLength
== NULL
) {
1460 return EFI_INVALID_PARAMETER
;
1463 Parser
= (HTTP_BODY_PARSER
*) MsgParser
;
1465 if (!Parser
->ContentLengthIsValid
) {
1466 return EFI_NOT_READY
;
1469 *ContentLength
= Parser
->ContentLength
;
1474 Release the resource of the message parser.
1476 @param[in] MsgParser Pointer to the message parser.
1485 FreePool (MsgParser
);