]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeHttpLib/DxeHttpLib.c
MdeModulePkg/DxeHttpLib: Avoid the pointless comparison of UINTN with zero
[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 (!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 if (Url == NULL || Length == 0 || UrlParser == NULL) {
377 return EFI_INVALID_PARAMETER;
378 }
379
380 Parser = AllocateZeroPool (sizeof (HTTP_URL_PARSER));
381 if (Parser == NULL) {
382 return EFI_OUT_OF_RESOURCES;
383 }
384
385 if (IsConnectMethod) {
386 //
387 // According to RFC 2616, the authority form is only used by the CONNECT method.
388 //
389 State = UrlParserAuthority;
390 } else {
391 State = UrlParserUrlStart;
392 }
393
394 Field = HTTP_URI_FIELD_MAX;
395 OldField = Field;
396 FoundAt = FALSE;
397 for (Char = Url; Char < Url + Length; Char++) {
398 //
399 // Update state machine according to next char.
400 //
401 State = NetHttpParseUrlChar (*Char, State);
402
403 switch (State) {
404 case UrlParserStateMax:
405 return EFI_INVALID_PARAMETER;
406
407 case UrlParserSchemeColon:
408 case UrlParserSchemeColonSlash:
409 case UrlParserSchemeColonSlashSlash:
410 case UrlParserQueryStart:
411 case UrlParserFragmentStart:
412 //
413 // Skip all the delimiting char: "://" "?" "@"
414 //
415 continue;
416
417 case UrlParserScheme:
418 Field = HTTP_URI_FIELD_SCHEME;
419 break;
420
421 case UrlParserAtInAuthority:
422 FoundAt = TRUE;
423 case UrlParserAuthority:
424 Field = HTTP_URI_FIELD_AUTHORITY;
425 break;
426
427 case UrlParserPath:
428 Field = HTTP_URI_FIELD_PATH;
429 break;
430
431 case UrlParserQuery:
432 Field = HTTP_URI_FIELD_QUERY;
433 break;
434
435 case UrlParserFragment:
436 Field = HTTP_URI_FIELD_FRAGMENT;
437 break;
438
439 default:
440 ASSERT (FALSE);
441 }
442
443 //
444 // Field not changed, count the length.
445 //
446 ASSERT (Field < HTTP_URI_FIELD_MAX);
447 if (Field == OldField) {
448 Parser->FieldData[Field].Length++;
449 continue;
450 }
451
452 //
453 // New field start
454 //
455 Parser->FieldBitMap |= BIT (Field);
456 Parser->FieldData[Field].Offset = (UINT32) (Char - Url);
457 Parser->FieldData[Field].Length = 1;
458 OldField = Field;
459 }
460
461 //
462 // If has authority component, continue to parse the username, host and port.
463 //
464 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_AUTHORITY)) != 0) {
465 Status = NetHttpParseAuthority (Url, FoundAt, Parser);
466 if (EFI_ERROR (Status)) {
467 return Status;
468 }
469 }
470
471 *UrlParser = Parser;
472 return EFI_SUCCESS;
473 }
474
475 /**
476 Get the Hostname from a HTTP URL.
477
478 This function will return the HostName according to the Url and previous parse result ,and
479 it is the caller's responsibility to free the buffer returned in *HostName.
480
481 @param[in] Url The pointer to a HTTP URL string.
482 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
483 @param[out] HostName Pointer to a buffer to store the HostName.
484
485 @retval EFI_SUCCESS Successfully get the required component.
486 @retval EFI_INVALID_PARAMETER Uri is NULL or HostName is NULL or UrlParser is invalid.
487 @retval EFI_NOT_FOUND No hostName component in the URL.
488 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
489
490 **/
491 EFI_STATUS
492 EFIAPI
493 HttpUrlGetHostName (
494 IN CHAR8 *Url,
495 IN VOID *UrlParser,
496 OUT CHAR8 **HostName
497 )
498 {
499 CHAR8 *Name;
500 EFI_STATUS Status;
501 UINT32 ResultLength;
502 HTTP_URL_PARSER *Parser;
503
504 if (Url == NULL || UrlParser == NULL || HostName == NULL) {
505 return EFI_INVALID_PARAMETER;
506 }
507
508 Parser = (HTTP_URL_PARSER*) UrlParser;
509
510 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_HOST)) == 0) {
511 return EFI_NOT_FOUND;
512 }
513
514 Name = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_HOST].Length + 1);
515 if (Name == NULL) {
516 return EFI_OUT_OF_RESOURCES;
517 }
518
519 Status = UriPercentDecode (
520 Url + Parser->FieldData[HTTP_URI_FIELD_HOST].Offset,
521 Parser->FieldData[HTTP_URI_FIELD_HOST].Length,
522 Name,
523 &ResultLength
524 );
525 if (EFI_ERROR (Status)) {
526 return Status;
527 }
528
529 Name[ResultLength] = '\0';
530 *HostName = Name;
531 return EFI_SUCCESS;
532 }
533
534
535 /**
536 Get the IPv4 address from a HTTP URL.
537
538 This function will return the IPv4 address according to the Url and previous parse result.
539
540 @param[in] Url The pointer to a HTTP URL string.
541 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
542 @param[out] Ip4Address Pointer to a buffer to store the IP address.
543
544 @retval EFI_SUCCESS Successfully get the required component.
545 @retval EFI_INVALID_PARAMETER Uri is NULL or Ip4Address is NULL or UrlParser is invalid.
546 @retval EFI_NOT_FOUND No IPv4 address component in the URL.
547 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
548
549 **/
550 EFI_STATUS
551 EFIAPI
552 HttpUrlGetIp4 (
553 IN CHAR8 *Url,
554 IN VOID *UrlParser,
555 OUT EFI_IPv4_ADDRESS *Ip4Address
556 )
557 {
558 CHAR8 *Ip4String;
559 EFI_STATUS Status;
560 UINT32 ResultLength;
561 HTTP_URL_PARSER *Parser;
562
563 if (Url == NULL || UrlParser == NULL || Ip4Address == NULL) {
564 return EFI_INVALID_PARAMETER;
565 }
566
567 Parser = (HTTP_URL_PARSER*) UrlParser;
568
569 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_HOST)) == 0) {
570 return EFI_INVALID_PARAMETER;
571 }
572
573 Ip4String = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_HOST].Length + 1);
574 if (Ip4String == NULL) {
575 return EFI_OUT_OF_RESOURCES;
576 }
577
578 Status = UriPercentDecode (
579 Url + Parser->FieldData[HTTP_URI_FIELD_HOST].Offset,
580 Parser->FieldData[HTTP_URI_FIELD_HOST].Length,
581 Ip4String,
582 &ResultLength
583 );
584 if (EFI_ERROR (Status)) {
585 return Status;
586 }
587
588 Ip4String[ResultLength] = '\0';
589 Status = NetLibAsciiStrToIp4 (Ip4String, Ip4Address);
590 FreePool (Ip4String);
591
592 return Status;
593 }
594
595 /**
596 Get the IPv6 address from a HTTP URL.
597
598 This function will return the IPv6 address according to the Url and previous parse result.
599
600 @param[in] Url The pointer to a HTTP URL string.
601 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
602 @param[out] Ip6Address Pointer to a buffer to store the IP address.
603
604 @retval EFI_SUCCESS Successfully get the required component.
605 @retval EFI_INVALID_PARAMETER Uri is NULL or Ip6Address is NULL or UrlParser is invalid.
606 @retval EFI_NOT_FOUND No IPv6 address component in the URL.
607 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
608
609 **/
610 EFI_STATUS
611 EFIAPI
612 HttpUrlGetIp6 (
613 IN CHAR8 *Url,
614 IN VOID *UrlParser,
615 OUT EFI_IPv6_ADDRESS *Ip6Address
616 )
617 {
618 CHAR8 *Ip6String;
619 CHAR8 *Ptr;
620 UINT32 Length;
621 EFI_STATUS Status;
622 UINT32 ResultLength;
623 HTTP_URL_PARSER *Parser;
624
625 if (Url == NULL || UrlParser == NULL || Ip6Address == NULL) {
626 return EFI_INVALID_PARAMETER;
627 }
628
629 Parser = (HTTP_URL_PARSER*) UrlParser;
630
631 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_HOST)) == 0) {
632 return EFI_INVALID_PARAMETER;
633 }
634
635 //
636 // IP-literal = "[" ( IPv6address / IPvFuture ) "]"
637 //
638 Length = Parser->FieldData[HTTP_URI_FIELD_HOST].Length;
639 if (Length < 2) {
640 return EFI_INVALID_PARAMETER;
641 }
642
643 Ptr = Url + Parser->FieldData[HTTP_URI_FIELD_HOST].Offset;
644 if ((Ptr[0] != '[') || (Ptr[Length - 1] != ']')) {
645 return EFI_INVALID_PARAMETER;
646 }
647
648 Ip6String = AllocatePool (Length);
649 if (Ip6String == NULL) {
650 return EFI_OUT_OF_RESOURCES;
651 }
652
653 Status = UriPercentDecode (
654 Ptr + 1,
655 Length - 2,
656 Ip6String,
657 &ResultLength
658 );
659 if (EFI_ERROR (Status)) {
660 return Status;
661 }
662
663 Ip6String[ResultLength] = '\0';
664 Status = NetLibAsciiStrToIp6 (Ip6String, Ip6Address);
665 FreePool (Ip6String);
666
667 return Status;
668 }
669
670 /**
671 Get the port number from a HTTP URL.
672
673 This function will return the port number according to the Url and previous parse result.
674
675 @param[in] Url The pointer to a HTTP URL string.
676 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
677 @param[out] Port Pointer to a buffer to store the port number.
678
679 @retval EFI_SUCCESS Successfully get the required component.
680 @retval EFI_INVALID_PARAMETER Uri is NULL or Port is NULL or UrlParser is invalid.
681 @retval EFI_NOT_FOUND No port number in the URL.
682 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
683
684 **/
685 EFI_STATUS
686 EFIAPI
687 HttpUrlGetPort (
688 IN CHAR8 *Url,
689 IN VOID *UrlParser,
690 OUT UINT16 *Port
691 )
692 {
693 CHAR8 *PortString;
694 EFI_STATUS Status;
695 UINTN Index;
696 UINTN Data;
697 UINT32 ResultLength;
698 HTTP_URL_PARSER *Parser;
699
700 if (Url == NULL || UrlParser == NULL || Port == NULL) {
701 return EFI_INVALID_PARAMETER;
702 }
703
704 *Port = 0;
705 Index = 0;
706
707 Parser = (HTTP_URL_PARSER*) UrlParser;
708
709 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_PORT)) == 0) {
710 return EFI_INVALID_PARAMETER;
711 }
712
713 PortString = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_PORT].Length + 1);
714 if (PortString == NULL) {
715 return EFI_OUT_OF_RESOURCES;
716 }
717
718 Status = UriPercentDecode (
719 Url + Parser->FieldData[HTTP_URI_FIELD_PORT].Offset,
720 Parser->FieldData[HTTP_URI_FIELD_PORT].Length,
721 PortString,
722 &ResultLength
723 );
724 if (EFI_ERROR (Status)) {
725 return Status;
726 }
727
728 PortString[ResultLength] = '\0';
729
730 while (Index < ResultLength) {
731 if (!NET_IS_DIGIT (PortString[Index])) {
732 return EFI_INVALID_PARAMETER;
733 }
734 Index ++;
735 }
736
737 Status = AsciiStrDecimalToUintnS (Url + Parser->FieldData[HTTP_URI_FIELD_PORT].Offset, (CHAR8 **) NULL, &Data);
738
739 if (Data > HTTP_URI_PORT_MAX_NUM) {
740 return EFI_INVALID_PARAMETER;
741 }
742
743 *Port = (UINT16) Data;
744 return Status;
745 }
746
747 /**
748 Get the Path from a HTTP URL.
749
750 This function will return the Path according to the Url and previous parse result,and
751 it is the caller's responsibility to free the buffer returned in *Path.
752
753 @param[in] Url The pointer to a HTTP URL string.
754 @param[in] UrlParser URL Parse result returned by NetHttpParseUrl().
755 @param[out] Path Pointer to a buffer to store the Path.
756
757 @retval EFI_SUCCESS Successfully get the required component.
758 @retval EFI_INVALID_PARAMETER Uri is NULL or HostName is NULL or UrlParser is invalid.
759 @retval EFI_NOT_FOUND No hostName component in the URL.
760 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
761
762 **/
763 EFI_STATUS
764 EFIAPI
765 HttpUrlGetPath (
766 IN CHAR8 *Url,
767 IN VOID *UrlParser,
768 OUT CHAR8 **Path
769 )
770 {
771 CHAR8 *PathStr;
772 EFI_STATUS Status;
773 UINT32 ResultLength;
774 HTTP_URL_PARSER *Parser;
775
776 if (Url == NULL || UrlParser == NULL || Path == NULL) {
777 return EFI_INVALID_PARAMETER;
778 }
779
780 Parser = (HTTP_URL_PARSER*) UrlParser;
781
782 if ((Parser->FieldBitMap & BIT (HTTP_URI_FIELD_PATH)) == 0) {
783 return EFI_NOT_FOUND;
784 }
785
786 PathStr = AllocatePool (Parser->FieldData[HTTP_URI_FIELD_PATH].Length + 1);
787 if (PathStr == NULL) {
788 return EFI_OUT_OF_RESOURCES;
789 }
790
791 Status = UriPercentDecode (
792 Url + Parser->FieldData[HTTP_URI_FIELD_PATH].Offset,
793 Parser->FieldData[HTTP_URI_FIELD_PATH].Length,
794 PathStr,
795 &ResultLength
796 );
797 if (EFI_ERROR (Status)) {
798 return Status;
799 }
800
801 PathStr[ResultLength] = '\0';
802 *Path = PathStr;
803 return EFI_SUCCESS;
804 }
805
806 /**
807 Release the resource of the URL parser.
808
809 @param[in] UrlParser Pointer to the parser.
810
811 **/
812 VOID
813 EFIAPI
814 HttpUrlFreeParser (
815 IN VOID *UrlParser
816 )
817 {
818 FreePool (UrlParser);
819 }
820
821 /**
822 Find a specified header field according to the field name.
823
824 @param[in] HeaderCount Number of HTTP header structures in Headers list.
825 @param[in] Headers Array containing list of HTTP headers.
826 @param[in] FieldName Null terminated string which describes a field name.
827
828 @return Pointer to the found header or NULL.
829
830 **/
831 EFI_HTTP_HEADER *
832 EFIAPI
833 HttpFindHeader (
834 IN UINTN HeaderCount,
835 IN EFI_HTTP_HEADER *Headers,
836 IN CHAR8 *FieldName
837 )
838 {
839 UINTN Index;
840
841 if (HeaderCount == 0 || Headers == NULL || FieldName == NULL) {
842 return NULL;
843 }
844
845 for (Index = 0; Index < HeaderCount; Index++){
846 //
847 // Field names are case-insensitive (RFC 2616).
848 //
849 if (AsciiStriCmp (Headers[Index].FieldName, FieldName) == 0) {
850 return &Headers[Index];
851 }
852 }
853 return NULL;
854 }
855
856 typedef enum {
857 BodyParserBodyStart,
858 BodyParserBodyIdentity,
859 BodyParserChunkSizeStart,
860 BodyParserChunkSize,
861 BodyParserChunkSizeEndCR,
862 BodyParserChunkExtStart,
863 BodyParserChunkDataStart,
864 BodyParserChunkDataEnd,
865 BodyParserChunkDataEndCR,
866 BodyParserTrailer,
867 BodyParserLastCRLF,
868 BodyParserLastCRLFEnd,
869 BodyParserComplete,
870 BodyParserStateMax
871 } HTTP_BODY_PARSE_STATE;
872
873 typedef struct {
874 BOOLEAN IgnoreBody; // "MUST NOT" include a message-body
875 BOOLEAN IsChunked; // "chunked" transfer-coding.
876 BOOLEAN ContentLengthIsValid;
877 UINTN ContentLength; // Entity length (not the message-body length), invalid until ContentLengthIsValid is TRUE
878
879 HTTP_BODY_PARSER_CALLBACK Callback;
880 VOID *Context;
881 UINTN ParsedBodyLength;
882 HTTP_BODY_PARSE_STATE State;
883 UINTN CurrentChunkSize;
884 UINTN CurrentChunkParsedSize;
885 } HTTP_BODY_PARSER;
886
887 /**
888
889 Convert an Ascii char to its uppercase.
890
891 @param[in] Char Ascii character.
892
893 @return Uppercase value of the input Char.
894
895 **/
896 CHAR8
897 HttpIoCharToUpper (
898 IN CHAR8 Char
899 )
900 {
901 if (Char >= 'a' && Char <= 'z') {
902 return Char - ('a' - 'A');
903 }
904
905 return Char;
906 }
907
908 /**
909 Convert an hexadecimal char to a value of type UINTN.
910
911 @param[in] Char Ascii character.
912
913 @return Value translated from Char.
914
915 **/
916 UINTN
917 HttpIoHexCharToUintn (
918 IN CHAR8 Char
919 )
920 {
921 if (Char >= '0' && Char <= '9') {
922 return Char - '0';
923 }
924
925 return (10 + HttpIoCharToUpper (Char) - 'A');
926 }
927
928 /**
929 Get the value of the content length if there is a "Content-Length" header.
930
931 @param[in] HeaderCount Number of HTTP header structures in Headers.
932 @param[in] Headers Array containing list of HTTP headers.
933 @param[out] ContentLength Pointer to save the value of the content length.
934
935 @retval EFI_SUCCESS Successfully get the content length.
936 @retval EFI_NOT_FOUND No "Content-Length" header in the Headers.
937
938 **/
939 EFI_STATUS
940 HttpIoParseContentLengthHeader (
941 IN UINTN HeaderCount,
942 IN EFI_HTTP_HEADER *Headers,
943 OUT UINTN *ContentLength
944 )
945 {
946 EFI_HTTP_HEADER *Header;
947
948 Header = HttpFindHeader (HeaderCount, Headers, HTTP_HEADER_CONTENT_LENGTH);
949 if (Header == NULL) {
950 return EFI_NOT_FOUND;
951 }
952
953 return AsciiStrDecimalToUintnS (Header->FieldValue, (CHAR8 **) NULL, ContentLength);
954 }
955
956 /**
957
958 Check whether the HTTP message is using the "chunked" transfer-coding.
959
960 @param[in] HeaderCount Number of HTTP header structures in Headers.
961 @param[in] Headers Array containing list of HTTP headers.
962
963 @return The message is "chunked" transfer-coding (TRUE) or not (FALSE).
964
965 **/
966 BOOLEAN
967 HttpIoIsChunked (
968 IN UINTN HeaderCount,
969 IN EFI_HTTP_HEADER *Headers
970 )
971 {
972 EFI_HTTP_HEADER *Header;
973
974
975 Header = HttpFindHeader (HeaderCount, Headers, HTTP_HEADER_TRANSFER_ENCODING);
976 if (Header == NULL) {
977 return FALSE;
978 }
979
980 if (AsciiStriCmp (Header->FieldValue, "identity") != 0) {
981 return TRUE;
982 }
983
984 return FALSE;
985 }
986
987 /**
988 Check whether the HTTP message should have a message-body.
989
990 @param[in] Method The HTTP method (e.g. GET, POST) for this HTTP message.
991 @param[in] StatusCode Response status code returned by the remote host.
992
993 @return The message should have a message-body (FALSE) or not (TRUE).
994
995 **/
996 BOOLEAN
997 HttpIoNoMessageBody (
998 IN EFI_HTTP_METHOD Method,
999 IN EFI_HTTP_STATUS_CODE StatusCode
1000 )
1001 {
1002 //
1003 // RFC 2616:
1004 // All responses to the HEAD request method
1005 // MUST NOT include a message-body, even though the presence of entity-
1006 // header fields might lead one to believe they do. All 1xx
1007 // (informational), 204 (no content), and 304 (not modified) responses
1008 // MUST NOT include a message-body. All other responses do include a
1009 // message-body, although it MAY be of zero length.
1010 //
1011 if (Method == HttpMethodHead) {
1012 return TRUE;
1013 }
1014
1015 if ((StatusCode == HTTP_STATUS_100_CONTINUE) ||
1016 (StatusCode == HTTP_STATUS_101_SWITCHING_PROTOCOLS) ||
1017 (StatusCode == HTTP_STATUS_204_NO_CONTENT) ||
1018 (StatusCode == HTTP_STATUS_304_NOT_MODIFIED))
1019 {
1020 return TRUE;
1021 }
1022
1023 return FALSE;
1024 }
1025
1026 /**
1027 Initialize a HTTP message-body parser.
1028
1029 This function will create and initialize a HTTP message parser according to caller provided HTTP message
1030 header information. It is the caller's responsibility to free the buffer returned in *UrlParser by HttpFreeMsgParser().
1031
1032 @param[in] Method The HTTP method (e.g. GET, POST) for this HTTP message.
1033 @param[in] StatusCode Response status code returned by the remote host.
1034 @param[in] HeaderCount Number of HTTP header structures in Headers.
1035 @param[in] Headers Array containing list of HTTP headers.
1036 @param[in] Callback Callback function that is invoked when parsing the HTTP message-body,
1037 set to NULL to ignore all events.
1038 @param[in] Context Pointer to the context that will be passed to Callback.
1039 @param[out] MsgParser Pointer to the returned buffer to store the message parser.
1040
1041 @retval EFI_SUCCESS Successfully initialized the parser.
1042 @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources.
1043 @retval EFI_INVALID_PARAMETER MsgParser is NULL or HeaderCount is not NULL but Headers is NULL.
1044 @retval Others Failed to initialize the parser.
1045
1046 **/
1047 EFI_STATUS
1048 EFIAPI
1049 HttpInitMsgParser (
1050 IN EFI_HTTP_METHOD Method,
1051 IN EFI_HTTP_STATUS_CODE StatusCode,
1052 IN UINTN HeaderCount,
1053 IN EFI_HTTP_HEADER *Headers,
1054 IN HTTP_BODY_PARSER_CALLBACK Callback,
1055 IN VOID *Context,
1056 OUT VOID **MsgParser
1057 )
1058 {
1059 EFI_STATUS Status;
1060 HTTP_BODY_PARSER *Parser;
1061
1062 if (HeaderCount != 0 && Headers == NULL) {
1063 return EFI_INVALID_PARAMETER;
1064 }
1065
1066 if (MsgParser == NULL) {
1067 return EFI_INVALID_PARAMETER;
1068 }
1069
1070 Parser = AllocateZeroPool (sizeof (HTTP_BODY_PARSER));
1071 if (Parser == NULL) {
1072 return EFI_OUT_OF_RESOURCES;
1073 }
1074
1075 Parser->State = BodyParserBodyStart;
1076
1077 //
1078 // Determine the message length according to RFC 2616.
1079 // 1. Check whether the message "MUST NOT" have a message-body.
1080 //
1081 Parser->IgnoreBody = HttpIoNoMessageBody (Method, StatusCode);
1082 //
1083 // 2. Check whether the message using "chunked" transfer-coding.
1084 //
1085 Parser->IsChunked = HttpIoIsChunked (HeaderCount, Headers);
1086 //
1087 // 3. Check whether the message has a Content-Length header field.
1088 //
1089 Status = HttpIoParseContentLengthHeader (HeaderCount, Headers, &Parser->ContentLength);
1090 if (!EFI_ERROR (Status)) {
1091 Parser->ContentLengthIsValid = TRUE;
1092 }
1093 //
1094 // 4. Range header is not supported now, so we won't meet media type "multipart/byteranges".
1095 // 5. By server closing the connection
1096 //
1097
1098 //
1099 // Set state to skip body parser if the message shouldn't have a message body.
1100 //
1101 if (Parser->IgnoreBody) {
1102 Parser->State = BodyParserComplete;
1103 } else {
1104 Parser->Callback = Callback;
1105 Parser->Context = Context;
1106 }
1107
1108 *MsgParser = Parser;
1109 return EFI_SUCCESS;
1110 }
1111
1112 /**
1113 Parse message body.
1114
1115 Parse BodyLength of message-body. This function can be called repeatedly to parse the message-body partially.
1116
1117 @param[in, out] MsgParser Pointer to the message parser.
1118 @param[in] BodyLength Length in bytes of the Body.
1119 @param[in] Body Pointer to the buffer of the message-body to be parsed.
1120
1121 @retval EFI_SUCCESS Successfully parse the message-body.
1122 @retval EFI_INVALID_PARAMETER MsgParser is NULL or Body is NULL or BodyLength is 0.
1123 @retval Others Operation aborted.
1124
1125 **/
1126 EFI_STATUS
1127 EFIAPI
1128 HttpParseMessageBody (
1129 IN OUT VOID *MsgParser,
1130 IN UINTN BodyLength,
1131 IN CHAR8 *Body
1132 )
1133 {
1134 CHAR8 *Char;
1135 UINTN RemainderLengthInThis;
1136 UINTN LengthForCallback;
1137 EFI_STATUS Status;
1138 HTTP_BODY_PARSER *Parser;
1139
1140 if (BodyLength == 0 || Body == NULL) {
1141 return EFI_INVALID_PARAMETER;
1142 }
1143
1144 if (MsgParser == NULL) {
1145 return EFI_INVALID_PARAMETER;
1146 }
1147
1148 Parser = (HTTP_BODY_PARSER*) MsgParser;
1149
1150 if (Parser->IgnoreBody) {
1151 Parser->State = BodyParserComplete;
1152 if (Parser->Callback != NULL) {
1153 Status = Parser->Callback (
1154 BodyParseEventOnComplete,
1155 Body,
1156 0,
1157 Parser->Context
1158 );
1159 if (EFI_ERROR (Status)) {
1160 return Status;
1161 }
1162 }
1163 return EFI_SUCCESS;
1164 }
1165
1166 if (Parser->State == BodyParserBodyStart) {
1167 Parser->ParsedBodyLength = 0;
1168 if (Parser->IsChunked) {
1169 Parser->State = BodyParserChunkSizeStart;
1170 } else {
1171 Parser->State = BodyParserBodyIdentity;
1172 }
1173 }
1174
1175 //
1176 // The message body might be truncated in anywhere, so we need to parse is byte-by-byte.
1177 //
1178 for (Char = Body; Char < Body + BodyLength; ) {
1179
1180 switch (Parser->State) {
1181 case BodyParserStateMax:
1182 return EFI_ABORTED;
1183
1184 case BodyParserBodyIdentity:
1185 //
1186 // Identity transfer-coding, just notify user to save the body data.
1187 //
1188 if (Parser->Callback != NULL) {
1189 Status = Parser->Callback (
1190 BodyParseEventOnData,
1191 Char,
1192 MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength),
1193 Parser->Context
1194 );
1195 if (EFI_ERROR (Status)) {
1196 return Status;
1197 }
1198 }
1199 Char += MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength);
1200 Parser->ParsedBodyLength += MIN (BodyLength, Parser->ContentLength - Parser->ParsedBodyLength);
1201 if (Parser->ParsedBodyLength == Parser->ContentLength) {
1202 Parser->State = BodyParserComplete;
1203 if (Parser->Callback != NULL) {
1204 Status = Parser->Callback (
1205 BodyParseEventOnComplete,
1206 Char,
1207 0,
1208 Parser->Context
1209 );
1210 if (EFI_ERROR (Status)) {
1211 return Status;
1212 }
1213 }
1214 }
1215 break;
1216
1217 case BodyParserChunkSizeStart:
1218 //
1219 // First byte of chunk-size, the chunk-size might be truncated.
1220 //
1221 Parser->CurrentChunkSize = 0;
1222 Parser->State = BodyParserChunkSize;
1223 case BodyParserChunkSize:
1224 if (!NET_IS_HEX_CHAR (*Char)) {
1225 if (*Char == ';') {
1226 Parser->State = BodyParserChunkExtStart;
1227 Char++;
1228 } else if (*Char == '\r') {
1229 Parser->State = BodyParserChunkSizeEndCR;
1230 Char++;
1231 } else {
1232 Parser->State = BodyParserStateMax;
1233 }
1234 break;
1235 }
1236
1237 if (Parser->CurrentChunkSize > (((~((UINTN) 0)) - 16) / 16)) {
1238 return EFI_INVALID_PARAMETER;
1239 }
1240 Parser->CurrentChunkSize = Parser->CurrentChunkSize * 16 + HttpIoHexCharToUintn (*Char);
1241 Char++;
1242 break;
1243
1244 case BodyParserChunkExtStart:
1245 //
1246 // Ignore all the chunk extensions.
1247 //
1248 if (*Char == '\r') {
1249 Parser->State = BodyParserChunkSizeEndCR;
1250 }
1251 Char++;
1252 break;
1253
1254 case BodyParserChunkSizeEndCR:
1255 if (*Char != '\n') {
1256 Parser->State = BodyParserStateMax;
1257 break;
1258 }
1259 Char++;
1260 if (Parser->CurrentChunkSize == 0) {
1261 //
1262 // The last chunk has been parsed and now assumed the state
1263 // of HttpBodyParse is ParserLastCRLF. So it need to decide
1264 // whether the rest message is trailer or last CRLF in the next round.
1265 //
1266 Parser->ContentLengthIsValid = TRUE;
1267 Parser->State = BodyParserLastCRLF;
1268 break;
1269 }
1270 Parser->State = BodyParserChunkDataStart;
1271 Parser->CurrentChunkParsedSize = 0;
1272 break;
1273
1274 case BodyParserLastCRLF:
1275 //
1276 // Judge the byte is belong to the Last CRLF or trailer, and then
1277 // configure the state of HttpBodyParse to corresponding state.
1278 //
1279 if (*Char == '\r') {
1280 Char++;
1281 Parser->State = BodyParserLastCRLFEnd;
1282 break;
1283 } else {
1284 Parser->State = BodyParserTrailer;
1285 break;
1286 }
1287
1288 case BodyParserLastCRLFEnd:
1289 if (*Char == '\n') {
1290 Parser->State = BodyParserComplete;
1291 Char++;
1292 if (Parser->Callback != NULL) {
1293 Status = Parser->Callback (
1294 BodyParseEventOnComplete,
1295 Char,
1296 0,
1297 Parser->Context
1298 );
1299 if (EFI_ERROR (Status)) {
1300 return Status;
1301 }
1302 }
1303 break;
1304 } else {
1305 Parser->State = BodyParserStateMax;
1306 break;
1307 }
1308
1309 case BodyParserTrailer:
1310 if (*Char == '\r') {
1311 Parser->State = BodyParserChunkSizeEndCR;
1312 }
1313 Char++;
1314 break;
1315
1316 case BodyParserChunkDataStart:
1317 //
1318 // First byte of chunk-data, the chunk data also might be truncated.
1319 //
1320 RemainderLengthInThis = BodyLength - (Char - Body);
1321 LengthForCallback = MIN (Parser->CurrentChunkSize - Parser->CurrentChunkParsedSize, RemainderLengthInThis);
1322 if (Parser->Callback != NULL) {
1323 Status = Parser->Callback (
1324 BodyParseEventOnData,
1325 Char,
1326 LengthForCallback,
1327 Parser->Context
1328 );
1329 if (EFI_ERROR (Status)) {
1330 return Status;
1331 }
1332 }
1333 Char += LengthForCallback;
1334 Parser->ContentLength += LengthForCallback;
1335 Parser->CurrentChunkParsedSize += LengthForCallback;
1336 if (Parser->CurrentChunkParsedSize == Parser->CurrentChunkSize) {
1337 Parser->State = BodyParserChunkDataEnd;
1338 }
1339 break;
1340
1341 case BodyParserChunkDataEnd:
1342 if (*Char == '\r') {
1343 Parser->State = BodyParserChunkDataEndCR;
1344 } else {
1345 Parser->State = BodyParserStateMax;
1346 }
1347 Char++;
1348 break;
1349
1350 case BodyParserChunkDataEndCR:
1351 if (*Char != '\n') {
1352 Parser->State = BodyParserStateMax;
1353 break;
1354 }
1355 Char++;
1356 Parser->State = BodyParserChunkSizeStart;
1357 break;
1358
1359 default:
1360 break;
1361 }
1362
1363 }
1364
1365 if (Parser->State == BodyParserStateMax) {
1366 return EFI_ABORTED;
1367 }
1368
1369 return EFI_SUCCESS;
1370 }
1371
1372 /**
1373 Check whether the message-body is complete or not.
1374
1375 @param[in] MsgParser Pointer to the message parser.
1376
1377 @retval TRUE Message-body is complete.
1378 @retval FALSE Message-body is not complete.
1379
1380 **/
1381 BOOLEAN
1382 EFIAPI
1383 HttpIsMessageComplete (
1384 IN VOID *MsgParser
1385 )
1386 {
1387 HTTP_BODY_PARSER *Parser;
1388
1389 Parser = (HTTP_BODY_PARSER*) MsgParser;
1390
1391 if (Parser->State == BodyParserComplete) {
1392 return TRUE;
1393 }
1394 return FALSE;
1395 }
1396
1397 /**
1398 Get the content length of the entity.
1399
1400 Note that in trunk transfer, the entity length is not valid until the whole message body is received.
1401
1402 @param[in] MsgParser Pointer to the message parser.
1403 @param[out] ContentLength Pointer to store the length of the entity.
1404
1405 @retval EFI_SUCCESS Successfully to get the entity length.
1406 @retval EFI_NOT_READY Entity length is not valid yet.
1407 @retval EFI_INVALID_PARAMETER MsgParser is NULL or ContentLength is NULL.
1408
1409 **/
1410 EFI_STATUS
1411 EFIAPI
1412 HttpGetEntityLength (
1413 IN VOID *MsgParser,
1414 OUT UINTN *ContentLength
1415 )
1416 {
1417 HTTP_BODY_PARSER *Parser;
1418
1419 if (MsgParser == NULL || ContentLength == NULL) {
1420 return EFI_INVALID_PARAMETER;
1421 }
1422
1423 Parser = (HTTP_BODY_PARSER*) MsgParser;
1424
1425 if (!Parser->ContentLengthIsValid) {
1426 return EFI_NOT_READY;
1427 }
1428
1429 *ContentLength = Parser->ContentLength;
1430 return EFI_SUCCESS;
1431 }
1432
1433 /**
1434 Release the resource of the message parser.
1435
1436 @param[in] MsgParser Pointer to the message parser.
1437
1438 **/
1439 VOID
1440 EFIAPI
1441 HttpFreeMsgParser (
1442 IN VOID *MsgParser
1443 )
1444 {
1445 FreePool (MsgParser);
1446 }
1447
1448
1449 /**
1450 Get the next string, which is distinguished by specified separator.
1451
1452 @param[in] String Pointer to the string.
1453 @param[in] Separator Specified separator used to distinguish where is the beginning
1454 of next string.
1455
1456 @return Pointer to the next string.
1457 @return NULL if not find or String is NULL.
1458
1459 **/
1460 CHAR8 *
1461 EFIAPI
1462 AsciiStrGetNextToken (
1463 IN CONST CHAR8 *String,
1464 IN CHAR8 Separator
1465 )
1466 {
1467 CONST CHAR8 *Token;
1468
1469 Token = String;
1470 while (TRUE) {
1471 if (*Token == 0) {
1472 return NULL;
1473 }
1474 if (*Token == Separator) {
1475 return (CHAR8 *)(Token + 1);
1476 }
1477 Token++;
1478 }
1479 }
1480
1481 /**
1482 Set FieldName and FieldValue into specified HttpHeader.
1483
1484 @param[in,out] HttpHeader Specified HttpHeader.
1485 @param[in] FieldName FieldName of this HttpHeader, a NULL terminated ASCII string.
1486 @param[in] FieldValue FieldValue of this HttpHeader, a NULL terminated ASCII string.
1487
1488
1489 @retval EFI_SUCCESS The FieldName and FieldValue are set into HttpHeader successfully.
1490 @retval EFI_OUT_OF_RESOURCES Failed to allocate resources.
1491
1492 **/
1493 EFI_STATUS
1494 EFIAPI
1495 HttpSetFieldNameAndValue (
1496 IN OUT EFI_HTTP_HEADER *HttpHeader,
1497 IN CONST CHAR8 *FieldName,
1498 IN CONST CHAR8 *FieldValue
1499 )
1500 {
1501 UINTN FieldNameSize;
1502 UINTN FieldValueSize;
1503
1504 if (HttpHeader->FieldName != NULL) {
1505 FreePool (HttpHeader->FieldName);
1506 }
1507 if (HttpHeader->FieldValue != NULL) {
1508 FreePool (HttpHeader->FieldValue);
1509 }
1510
1511 FieldNameSize = AsciiStrSize (FieldName);
1512 HttpHeader->FieldName = AllocateZeroPool (FieldNameSize);
1513 if (HttpHeader->FieldName == NULL) {
1514 return EFI_OUT_OF_RESOURCES;
1515 }
1516 CopyMem (HttpHeader->FieldName, FieldName, FieldNameSize);
1517 HttpHeader->FieldName[FieldNameSize - 1] = 0;
1518
1519 FieldValueSize = AsciiStrSize (FieldValue);
1520 HttpHeader->FieldValue = AllocateZeroPool (FieldValueSize);
1521 if (HttpHeader->FieldValue == NULL) {
1522 return EFI_OUT_OF_RESOURCES;
1523 }
1524 CopyMem (HttpHeader->FieldValue, FieldValue, FieldValueSize);
1525 HttpHeader->FieldValue[FieldValueSize - 1] = 0;
1526
1527 return EFI_SUCCESS;
1528 }
1529
1530 /**
1531 Get one key/value header pair from the raw string.
1532
1533 @param[in] String Pointer to the raw string.
1534 @param[out] FieldName Points directly to field name within 'HttpHeader'.
1535 @param[out] FieldValue Points directly to field value within 'HttpHeader'.
1536
1537 @return Pointer to the next raw string.
1538 @return NULL if no key/value header pair from this raw string.
1539
1540 **/
1541 CHAR8 *
1542 EFIAPI
1543 HttpGetFieldNameAndValue (
1544 IN CHAR8 *String,
1545 OUT CHAR8 **FieldName,
1546 OUT CHAR8 **FieldValue
1547 )
1548 {
1549 CHAR8 *FieldNameStr;
1550 CHAR8 *FieldValueStr;
1551 CHAR8 *StrPtr;
1552
1553 if (String == NULL || FieldName == NULL || FieldValue == NULL) {
1554 return NULL;
1555 }
1556
1557 *FieldName = NULL;
1558 *FieldValue = NULL;
1559 FieldNameStr = NULL;
1560 FieldValueStr = NULL;
1561 StrPtr = NULL;
1562
1563 //
1564 // Each header field consists of a name followed by a colon (":") and the field value.
1565 //
1566 FieldNameStr = String;
1567 FieldValueStr = AsciiStrGetNextToken (FieldNameStr, ':');
1568 if (FieldValueStr == NULL) {
1569 return NULL;
1570 }
1571
1572 //
1573 // Replace ':' with 0
1574 //
1575 *(FieldValueStr - 1) = 0;
1576
1577 //
1578 // The field value MAY be preceded by any amount of LWS, though a single SP is preferred.
1579 //
1580 while (TRUE) {
1581 if (*FieldValueStr == ' ' || *FieldValueStr == '\t') {
1582 FieldValueStr ++;
1583 } else if (*FieldValueStr == '\r' && *(FieldValueStr + 1) == '\n' &&
1584 (*(FieldValueStr + 2) == ' ' || *(FieldValueStr + 2) == '\t')) {
1585 FieldValueStr = FieldValueStr + 3;
1586 } else {
1587 break;
1588 }
1589 }
1590
1591 //
1592 // Header fields can be extended over multiple lines by preceding each extra
1593 // line with at least one SP or HT.
1594 //
1595 StrPtr = FieldValueStr;
1596 do {
1597 StrPtr = AsciiStrGetNextToken (StrPtr, '\r');
1598 if (StrPtr == NULL || *StrPtr != '\n') {
1599 return NULL;
1600 }
1601
1602 StrPtr++;
1603 } while (*StrPtr == ' ' || *StrPtr == '\t');
1604
1605 //
1606 // Replace '\r' with 0
1607 //
1608 *(StrPtr - 2) = 0;
1609
1610 //
1611 // Get FieldName and FieldValue.
1612 //
1613 *FieldName = FieldNameStr;
1614 *FieldValue = FieldValueStr;
1615
1616 return StrPtr;
1617 }
1618
1619 /**
1620 Free existing HeaderFields.
1621
1622 @param[in] HeaderFields Pointer to array of key/value header pairs waitting for free.
1623 @param[in] FieldCount The number of header pairs in HeaderFields.
1624
1625 **/
1626 VOID
1627 EFIAPI
1628 HttpFreeHeaderFields (
1629 IN EFI_HTTP_HEADER *HeaderFields,
1630 IN UINTN FieldCount
1631 )
1632 {
1633 UINTN Index;
1634
1635 if (HeaderFields != NULL) {
1636 for (Index = 0; Index < FieldCount; Index++) {
1637 if (HeaderFields[Index].FieldName != NULL) {
1638 FreePool (HeaderFields[Index].FieldName);
1639 }
1640 if (HeaderFields[Index].FieldValue != NULL) {
1641 FreePool (HeaderFields[Index].FieldValue);
1642 }
1643 }
1644
1645 FreePool (HeaderFields);
1646 }
1647 }
1648
1649 /**
1650 Generate HTTP request message.
1651
1652 This function will allocate memory for the whole HTTP message and generate a
1653 well formatted HTTP Request message in it, include the Request-Line, header
1654 fields and also the message body. It is the caller's responsibility to free
1655 the buffer returned in *RequestMsg.
1656
1657 @param[in] Message Pointer to the EFI_HTTP_MESSAGE structure which
1658 contains the required information to generate
1659 the HTTP request message.
1660 @param[in] Url The URL of a remote host.
1661 @param[out] RequestMsg Pointer to the created HTTP request message.
1662 NULL if any error occured.
1663 @param[out] RequestMsgSize Size of the RequestMsg (in bytes).
1664
1665 @return EFI_SUCCESS If HTTP request string was created successfully
1666 @retval EFI_OUT_OF_RESOURCES Failed to allocate resources.
1667 @retval EFI_INVALID_PARAMETER The input arguments are invalid
1668
1669 **/
1670 EFI_STATUS
1671 EFIAPI
1672 HttpGenRequestMessage (
1673 IN CONST EFI_HTTP_MESSAGE *Message,
1674 IN CONST CHAR8 *Url,
1675 OUT CHAR8 **RequestMsg,
1676 OUT UINTN *RequestMsgSize
1677 )
1678 {
1679 EFI_STATUS Status;
1680 UINTN StrLength;
1681 CHAR8 *RequestPtr;
1682 UINTN HttpHdrSize;
1683 UINTN MsgSize;
1684 BOOLEAN Success;
1685 VOID *HttpHdr;
1686 EFI_HTTP_HEADER **AppendList;
1687 UINTN Index;
1688 EFI_HTTP_UTILITIES_PROTOCOL *HttpUtilitiesProtocol;
1689
1690
1691 ASSERT (Message != NULL);
1692
1693 *RequestMsg = NULL;
1694 Status = EFI_SUCCESS;
1695 HttpHdrSize = 0;
1696 MsgSize = 0;
1697 Success = FALSE;
1698 HttpHdr = NULL;
1699 AppendList = NULL;
1700 HttpUtilitiesProtocol = NULL;
1701
1702 //
1703 // 1. If we have a Request, we cannot have a NULL Url
1704 // 2. If we have a Request, HeaderCount can not be non-zero
1705 // 3. If we do not have a Request, HeaderCount should be zero
1706 // 4. If we do not have Request and Headers, we need at least a message-body
1707 //
1708 if ((Message->Data.Request != NULL && Url == NULL) ||
1709 (Message->Data.Request != NULL && Message->HeaderCount == 0) ||
1710 (Message->Data.Request == NULL && Message->HeaderCount != 0) ||
1711 (Message->Data.Request == NULL && Message->HeaderCount == 0 && Message->BodyLength == 0)) {
1712 return EFI_INVALID_PARAMETER;
1713 }
1714
1715 if (Message->HeaderCount != 0) {
1716 //
1717 // Locate the HTTP_UTILITIES protocol.
1718 //
1719 Status = gBS->LocateProtocol (
1720 &gEfiHttpUtilitiesProtocolGuid,
1721 NULL,
1722 (VOID **)&HttpUtilitiesProtocol
1723 );
1724
1725 if (EFI_ERROR (Status)) {
1726 DEBUG ((DEBUG_ERROR,"Failed to locate Http Utilities protocol. Status = %r.\n", Status));
1727 return Status;
1728 }
1729
1730 //
1731 // Build AppendList to send into HttpUtilitiesBuild
1732 //
1733 AppendList = AllocateZeroPool (sizeof (EFI_HTTP_HEADER *) * (Message->HeaderCount));
1734 if (AppendList == NULL) {
1735 return EFI_OUT_OF_RESOURCES;
1736 }
1737
1738 for(Index = 0; Index < Message->HeaderCount; Index++){
1739 AppendList[Index] = &Message->Headers[Index];
1740 }
1741
1742 //
1743 // Build raw HTTP Headers
1744 //
1745 Status = HttpUtilitiesProtocol->Build (
1746 HttpUtilitiesProtocol,
1747 0,
1748 NULL,
1749 0,
1750 NULL,
1751 Message->HeaderCount,
1752 AppendList,
1753 &HttpHdrSize,
1754 &HttpHdr
1755 );
1756
1757 if (AppendList != NULL) {
1758 FreePool (AppendList);
1759 }
1760
1761 if (EFI_ERROR (Status) || HttpHdr == NULL){
1762 return Status;
1763 }
1764 }
1765
1766 //
1767 // If we have headers to be sent, account for it.
1768 //
1769 if (Message->HeaderCount != 0) {
1770 MsgSize = HttpHdrSize;
1771 }
1772
1773 //
1774 // If we have a request line, account for the fields.
1775 //
1776 if (Message->Data.Request != NULL) {
1777 MsgSize += HTTP_METHOD_MAXIMUM_LEN + AsciiStrLen (HTTP_VERSION_CRLF_STR) + AsciiStrLen (Url);
1778 }
1779
1780
1781 //
1782 // If we have a message body to be sent, account for it.
1783 //
1784 MsgSize += Message->BodyLength;
1785
1786 //
1787 // memory for the string that needs to be sent to TCP
1788 //
1789 *RequestMsg = AllocateZeroPool (MsgSize);
1790 if (*RequestMsg == NULL) {
1791 Status = EFI_OUT_OF_RESOURCES;
1792 goto Exit;
1793 }
1794
1795 RequestPtr = *RequestMsg;
1796 //
1797 // Construct header request
1798 //
1799 if (Message->Data.Request != NULL) {
1800 switch (Message->Data.Request->Method) {
1801 case HttpMethodGet:
1802 StrLength = sizeof (HTTP_METHOD_GET) - 1;
1803 CopyMem (RequestPtr, HTTP_METHOD_GET, StrLength);
1804 RequestPtr += StrLength;
1805 break;
1806 case HttpMethodPut:
1807 StrLength = sizeof (HTTP_METHOD_PUT) - 1;
1808 CopyMem (RequestPtr, HTTP_METHOD_PUT, StrLength);
1809 RequestPtr += StrLength;
1810 break;
1811 case HttpMethodPatch:
1812 StrLength = sizeof (HTTP_METHOD_PATCH) - 1;
1813 CopyMem (RequestPtr, HTTP_METHOD_PATCH, StrLength);
1814 RequestPtr += StrLength;
1815 break;
1816 case HttpMethodPost:
1817 StrLength = sizeof (HTTP_METHOD_POST) - 1;
1818 CopyMem (RequestPtr, HTTP_METHOD_POST, StrLength);
1819 RequestPtr += StrLength;
1820 break;
1821 case HttpMethodHead:
1822 StrLength = sizeof (HTTP_METHOD_HEAD) - 1;
1823 CopyMem (RequestPtr, HTTP_METHOD_HEAD, StrLength);
1824 RequestPtr += StrLength;
1825 break;
1826 case HttpMethodDelete:
1827 StrLength = sizeof (HTTP_METHOD_DELETE) - 1;
1828 CopyMem (RequestPtr, HTTP_METHOD_DELETE, StrLength);
1829 RequestPtr += StrLength;
1830 break;
1831 default:
1832 ASSERT (FALSE);
1833 Status = EFI_INVALID_PARAMETER;
1834 goto Exit;
1835 }
1836
1837 StrLength = AsciiStrLen(EMPTY_SPACE);
1838 CopyMem (RequestPtr, EMPTY_SPACE, StrLength);
1839 RequestPtr += StrLength;
1840
1841 StrLength = AsciiStrLen (Url);
1842 CopyMem (RequestPtr, Url, StrLength);
1843 RequestPtr += StrLength;
1844
1845 StrLength = sizeof (HTTP_VERSION_CRLF_STR) - 1;
1846 CopyMem (RequestPtr, HTTP_VERSION_CRLF_STR, StrLength);
1847 RequestPtr += StrLength;
1848
1849 if (HttpHdr != NULL) {
1850 //
1851 // Construct header
1852 //
1853 CopyMem (RequestPtr, HttpHdr, HttpHdrSize);
1854 RequestPtr += HttpHdrSize;
1855 }
1856 }
1857
1858 //
1859 // Construct body
1860 //
1861 if (Message->Body != NULL) {
1862 CopyMem (RequestPtr, Message->Body, Message->BodyLength);
1863 RequestPtr += Message->BodyLength;
1864 }
1865
1866 //
1867 // Done
1868 //
1869 (*RequestMsgSize) = (UINTN)(RequestPtr) - (UINTN)(*RequestMsg);
1870 Success = TRUE;
1871
1872 Exit:
1873
1874 if (!Success) {
1875 if (*RequestMsg != NULL) {
1876 FreePool (*RequestMsg);
1877 }
1878 *RequestMsg = NULL;
1879 return Status;
1880 }
1881
1882 if (HttpHdr != NULL) {
1883 FreePool (HttpHdr);
1884 }
1885
1886 return EFI_SUCCESS;
1887 }
1888
1889 /**
1890 Translate the status code in HTTP message to EFI_HTTP_STATUS_CODE defined
1891 in UEFI 2.5 specification.
1892
1893 @param[in] StatusCode The status code value in HTTP message.
1894
1895 @return Value defined in EFI_HTTP_STATUS_CODE .
1896
1897 **/
1898 EFI_HTTP_STATUS_CODE
1899 EFIAPI
1900 HttpMappingToStatusCode (
1901 IN UINTN StatusCode
1902 )
1903 {
1904 switch (StatusCode) {
1905 case 100:
1906 return HTTP_STATUS_100_CONTINUE;
1907 case 101:
1908 return HTTP_STATUS_101_SWITCHING_PROTOCOLS;
1909 case 200:
1910 return HTTP_STATUS_200_OK;
1911 case 201:
1912 return HTTP_STATUS_201_CREATED;
1913 case 202:
1914 return HTTP_STATUS_202_ACCEPTED;
1915 case 203:
1916 return HTTP_STATUS_203_NON_AUTHORITATIVE_INFORMATION;
1917 case 204:
1918 return HTTP_STATUS_204_NO_CONTENT;
1919 case 205:
1920 return HTTP_STATUS_205_RESET_CONTENT;
1921 case 206:
1922 return HTTP_STATUS_206_PARTIAL_CONTENT;
1923 case 300:
1924 return HTTP_STATUS_300_MULTIPLE_CHIOCES;
1925 case 301:
1926 return HTTP_STATUS_301_MOVED_PERMANENTLY;
1927 case 302:
1928 return HTTP_STATUS_302_FOUND;
1929 case 303:
1930 return HTTP_STATUS_303_SEE_OTHER;
1931 case 304:
1932 return HTTP_STATUS_304_NOT_MODIFIED;
1933 case 305:
1934 return HTTP_STATUS_305_USE_PROXY;
1935 case 307:
1936 return HTTP_STATUS_307_TEMPORARY_REDIRECT;
1937 case 400:
1938 return HTTP_STATUS_400_BAD_REQUEST;
1939 case 401:
1940 return HTTP_STATUS_401_UNAUTHORIZED;
1941 case 402:
1942 return HTTP_STATUS_402_PAYMENT_REQUIRED;
1943 case 403:
1944 return HTTP_STATUS_403_FORBIDDEN;
1945 case 404:
1946 return HTTP_STATUS_404_NOT_FOUND;
1947 case 405:
1948 return HTTP_STATUS_405_METHOD_NOT_ALLOWED;
1949 case 406:
1950 return HTTP_STATUS_406_NOT_ACCEPTABLE;
1951 case 407:
1952 return HTTP_STATUS_407_PROXY_AUTHENTICATION_REQUIRED;
1953 case 408:
1954 return HTTP_STATUS_408_REQUEST_TIME_OUT;
1955 case 409:
1956 return HTTP_STATUS_409_CONFLICT;
1957 case 410:
1958 return HTTP_STATUS_410_GONE;
1959 case 411:
1960 return HTTP_STATUS_411_LENGTH_REQUIRED;
1961 case 412:
1962 return HTTP_STATUS_412_PRECONDITION_FAILED;
1963 case 413:
1964 return HTTP_STATUS_413_REQUEST_ENTITY_TOO_LARGE;
1965 case 414:
1966 return HTTP_STATUS_414_REQUEST_URI_TOO_LARGE;
1967 case 415:
1968 return HTTP_STATUS_415_UNSUPPORTED_MEDIA_TYPE;
1969 case 416:
1970 return HTTP_STATUS_416_REQUESTED_RANGE_NOT_SATISFIED;
1971 case 417:
1972 return HTTP_STATUS_417_EXPECTATION_FAILED;
1973 case 500:
1974 return HTTP_STATUS_500_INTERNAL_SERVER_ERROR;
1975 case 501:
1976 return HTTP_STATUS_501_NOT_IMPLEMENTED;
1977 case 502:
1978 return HTTP_STATUS_502_BAD_GATEWAY;
1979 case 503:
1980 return HTTP_STATUS_503_SERVICE_UNAVAILABLE;
1981 case 504:
1982 return HTTP_STATUS_504_GATEWAY_TIME_OUT;
1983 case 505:
1984 return HTTP_STATUS_505_HTTP_VERSION_NOT_SUPPORTED;
1985
1986 default:
1987 return HTTP_STATUS_UNSUPPORTED_STATUS;
1988 }
1989 }
1990
1991 /**
1992 Check whether header field called FieldName is in DeleteList.
1993
1994 @param[in] DeleteList Pointer to array of key/value header pairs.
1995 @param[in] DeleteCount The number of header pairs.
1996 @param[in] FieldName Pointer to header field's name.
1997
1998 @return TRUE if FieldName is not in DeleteList, that means this header field is valid.
1999 @return FALSE if FieldName is in DeleteList, that means this header field is invalid.
2000
2001 **/
2002 BOOLEAN
2003 EFIAPI
2004 HttpIsValidHttpHeader (
2005 IN CHAR8 *DeleteList[],
2006 IN UINTN DeleteCount,
2007 IN CHAR8 *FieldName
2008 )
2009 {
2010 UINTN Index;
2011
2012 for (Index = 0; Index < DeleteCount; Index++) {
2013 if (AsciiStrCmp (FieldName, DeleteList[Index]) == 0) {
2014 return FALSE;
2015 }
2016 }
2017
2018 return TRUE;
2019 }
2020