-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathcore_http_client.c
2697 lines (2308 loc) · 102 KB
/
core_http_client.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* coreHTTP v3.1.1
* Copyright (C) 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file core_http_client.c
* @brief Implements the user-facing functions in core_http_client.h.
*/
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include "core_http_client.h"
#include "core_http_client_private.h"
/*-----------------------------------------------------------*/
/**
* @brief When #HTTPResponse_t.getTime is set to NULL in #HTTPClient_Send then
* this function will replace that field.
*
* @return This function always returns zero.
*/
static uint32_t getZeroTimestampMs( void );
/**
* @brief Adds the Content-Length header field and value to the
* @p pRequestHeaders.
*
* @param[in] pRequestHeaders Request header buffer information.
* @param[in] contentLength The Content-Length header value to write.
*
* @return #HTTPSuccess if successful. If there was insufficient memory in the
* application buffer, then #HTTPInsufficientMemory is returned.
*/
static HTTPStatus_t addContentLengthHeader( HTTPRequestHeaders_t * pRequestHeaders,
size_t contentLength );
/**
* @brief Send the HTTP body over the transport send interface.
*
* @param[in] pTransport Transport interface.
* @param[in] getTimestampMs Function to retrieve a timestamp in milliseconds.
* @param[in] pRequestBodyBuf Request body buffer.
* @param[in] reqBodyBufLen Length of the request body buffer.
*
* @return #HTTPSuccess if successful. If there was a network error or less
* bytes than what was specified were sent, then #HTTPNetworkError is
* returned.
*/
static HTTPStatus_t sendHttpBody( const TransportInterface_t * pTransport,
HTTPClient_GetCurrentTimeFunc_t getTimestampMs,
const uint8_t * pRequestBodyBuf,
size_t reqBodyBufLen );
/**
* @brief A strncpy replacement with HTTP header validation.
*
* This function checks for `\r` and `\n` in the @p pSrc while copying.
* This function checks for `:` in the @p pSrc, if @p isField is set to 1.
*
* @param[in] pDest The destination buffer to copy to.
* @param[in] pSrc The source buffer to copy from.
* @param[in] len The length of @p pSrc to copy to pDest.
* @param[in] isField Set to 0 to indicate that @p pSrc is a field. Set to 1 to
* indicate that @p pSrc is a value.
*
* @return @p pDest if the copy was successful, NULL otherwise.
*/
static char * httpHeaderStrncpy( char * pDest,
const char * pSrc,
size_t len,
uint8_t isField );
/**
* @brief Write header based on parameters. This method also adds a trailing
* "\r\n". If a trailing "\r\n" already exists in the HTTP header, this method
* backtracks in order to write over it and updates the length accordingly.
*
* @param[in] pRequestHeaders Request header buffer information.
* @param[in] pField The ISO 8859-1 encoded header field name to write.
* @param[in] fieldLen The byte length of the header field name.
* @param[in] pValue The ISO 8859-1 encoded header value to write.
* @param[in] valueLen The byte length of the header field value.
*
* @return #HTTPSuccess if successful. If there was insufficient memory in the
* application buffer, then #HTTPInsufficientMemory is returned.
*/
static HTTPStatus_t addHeader( HTTPRequestHeaders_t * pRequestHeaders,
const char * pField,
size_t fieldLen,
const char * pValue,
size_t valueLen );
/**
* @brief Add the byte range request header to the request headers store in
* #HTTPRequestHeaders_t.pBuffer once all the parameters are validated.
*
* @param[in] pRequestHeaders Request header buffer information.
* @param[in] rangeStartOrlastNbytes Represents either the starting byte
* for a range OR the last N number of bytes in the requested file.
* @param[in] rangeEnd The ending range for the requested file. For end of file
* byte in Range Specifications 2. and 3., #HTTP_RANGE_REQUEST_END_OF_FILE
* should be passed.
*
* @return #HTTPSuccess if successful. If there was insufficient memory in the
* application buffer, then #HTTPInsufficientMemory is returned.
*/
static HTTPStatus_t addRangeHeader( HTTPRequestHeaders_t * pRequestHeaders,
int32_t rangeStartOrlastNbytes,
int32_t rangeEnd );
/**
* @brief Get the status of the HTTP response given the parsing state and how
* much data is in the response buffer.
*
* @param[in] parsingState State of the parsing on the HTTP response.
* @param[in] totalReceived The amount of network data received in the response
* buffer.
* @param[in] responseBufferLen The length of the response buffer.
*
* @return Returns #HTTPSuccess if the parsing state is complete. If
* the parsing state denotes it never started, then return #HTTPNoResponse. If
* the parsing state is incomplete, then if the response buffer is not full
* #HTTPPartialResponse is returned. If the parsing state is incomplete, then
* if the response buffer is full #HTTPInsufficientMemory is returned.
*/
static HTTPStatus_t getFinalResponseStatus( HTTPParsingState_t parsingState,
size_t totalReceived,
size_t responseBufferLen );
/**
* @brief Send the HTTP request over the network.
*
* @param[in] pTransport Transport interface.
* @param[in] getTimestampMs Function to retrieve a timestamp in milliseconds.
* @param[in] pRequestHeaders Request headers to send over the network.
* @param[in] pRequestBodyBuf Request body buffer to send over the network.
* @param[in] reqBodyBufLen Length of the request body buffer.
* @param[in] sendFlags Application provided flags to #HTTPClient_Send.
*
* @return Returns #HTTPSuccess if successful. Please see #HTTPClient_SendHttpHeaders and
* #sendHttpBody for other statuses returned.
*/
static HTTPStatus_t sendHttpRequest( const TransportInterface_t * pTransport,
HTTPClient_GetCurrentTimeFunc_t getTimestampMs,
HTTPRequestHeaders_t * pRequestHeaders,
const uint8_t * pRequestBodyBuf,
size_t reqBodyBufLen,
uint32_t sendFlags );
/**
* @brief Converts an integer value to its ASCII representation in the passed
* buffer.
*
* @param[in] value The value to convert to ASCII.
* @param[out] pBuffer The buffer to store the ASCII representation of the
* integer.
* @param[in] bufferLength The length of pBuffer.
*
* @return Returns the number of bytes written to @p pBuffer.
*/
static uint8_t convertInt32ToAscii( int32_t value,
char * pBuffer,
size_t bufferLength );
/**
* @brief This method writes the request line (first line) of the HTTP Header
* into #HTTPRequestHeaders_t.pBuffer and updates length accordingly.
*
* @param pRequestHeaders Request header buffer information.
* @param pMethod The HTTP request method e.g. "GET", "POST", "PUT", or "HEAD".
* @param methodLen The byte length of the request method.
* @param pPath The Request-URI to the objects of interest, e.g. "/path/to/item.txt".
* @param pathLen The byte length of the request path.
*
* @return #HTTPSuccess if successful. If there was insufficient memory in the
* application buffer, then #HTTPInsufficientMemory is returned.
*/
static HTTPStatus_t writeRequestLine( HTTPRequestHeaders_t * pRequestHeaders,
const char * pMethod,
size_t methodLen,
const char * pPath,
size_t pathLen );
/**
* @brief Find the specified header field in the response buffer.
*
* @param[in] pBuffer The response buffer to parse.
* @param[in] bufferLen The length of the response buffer to parse.
* @param[in] pField The header field to search for.
* @param[in] fieldLen The length of pField.
* @param[out] pValueLoc The location of the the header value found in pBuffer.
* @param[out] pValueLen The length of pValue.
*
* @return One of the following:
* - #HTTPSuccess when header is found in the response.
* - #HTTPHeaderNotFound if requested header is not found in response.
* - #HTTPInvalidResponse if passed response is invalid for parsing.
* - #HTTPParserInternalError for any parsing errors.
*/
static HTTPStatus_t findHeaderInResponse( const uint8_t * pBuffer,
size_t bufferLen,
const char * pField,
size_t fieldLen,
const char ** pValueLoc,
size_t * pValueLen );
/**
* @brief The "on_header_field" callback for the HTTP parser used by the
* #findHeaderInResponse function. The callback checks whether the parser
* header field matched the header being searched for, and sets a flag to
* represent reception of the header accordingly.
*
* @param[in] pHttpParser Parsing object containing state and callback context.
* @param[in] pFieldLoc The location of the parsed header field in the response
* buffer.
* @param[in] fieldLen The length of the header field.
*
* @return Returns #LLHTTP_CONTINUE_PARSING to indicate continuation with
* parsing.
*/
static int findHeaderFieldParserCallback( llhttp_t * pHttpParser,
const char * pFieldLoc,
size_t fieldLen );
/**
* @brief The "on_header_value" callback for the HTTP parser used by the
* #findHeaderInResponse function. The callback sets the user-provided output
* parameters for header value if the requested header's field was found in the
* @ref findHeaderFieldParserCallback function.
*
* @param[in] pHttpParser Parsing object containing state and callback context.
* @param[in] pValueLoc The location of the parsed header value in the response
* buffer.
* @param[in] valueLen The length of the header value.
*
* @return Returns #LLHTTP_STOP_PARSING, if the header field/value pair are
* found, otherwise #LLHTTP_CONTINUE_PARSING is returned.
*/
static int findHeaderValueParserCallback( llhttp_t * pHttpParser,
const char * pValueLoc,
size_t valueLen );
/**
* @brief The "on_header_complete" callback for the HTTP parser used by the
* #findHeaderInResponse function.
*
* This callback will only be invoked if the requested header is not found in
* the response. This callback is used to signal the parser to halt execution
* if the requested header is not found.
*
* @param[in] pHttpParser Parsing object containing state and callback context.
*
* @return Returns #LLHTTP_STOP_PARSING_NO_HEADER for the parser to halt further
* execution, as all headers have been parsed in the response.
*/
static int findHeaderOnHeaderCompleteCallback( llhttp_t * pHttpParser );
/**
* @brief Initialize the parsing context for parsing a response fresh from the
* server.
*
* @param[in] pParsingContext The parsing context to initialize.
* @param[in] pRequestHeaders Request headers for the corresponding HTTP request.
*/
static void initializeParsingContextForFirstResponse( HTTPParsingContext_t * pParsingContext,
const HTTPRequestHeaders_t * pRequestHeaders );
/**
* @brief Parses the response buffer in @p pResponse.
*
* This function may be invoked multiple times for different parts of the the
* HTTP response. The state of what was last parsed in the response is kept in
* @p pParsingContext.
*
* @param[in,out] pParsingContext The response parsing state.
* @param[in,out] pResponse The response information to be updated.
* @param[in] parseLen The next length to parse in pResponse->pBuffer.
*
* @return One of the following:
* - #HTTPSuccess
* - #HTTPInvalidParameter
* - Please see #processLlhttpError for parsing errors returned.
*/
static HTTPStatus_t parseHttpResponse( HTTPParsingContext_t * pParsingContext,
HTTPResponse_t * pResponse,
size_t parseLen );
/**
* @brief Callback invoked during llhttp_execute() to indicate the start of
* the HTTP response message.
*
* This callback is invoked when an "H" in the "HTTP/1.1" that starts a response
* is found.
*
* @param[in] pHttpParser Parsing object containing state and callback context.
*
* @return #LLHTTP_CONTINUE_PARSING to continue parsing.
*/
static int httpParserOnMessageBeginCallback( llhttp_t * pHttpParser );
/**
* @brief Callback invoked during llhttp_execute() when the HTTP response
* status-code and its associated reason-phrase are found.
*
* @param[in] pHttpParser Parsing object containing state and callback context.
* @param[in] pLoc Location of the HTTP response reason-phrase string in the
* response message buffer.
* @param[in] length Length of the HTTP response status code string.
*
* @return #LLHTTP_CONTINUE_PARSING to continue parsing.
*/
static int httpParserOnStatusCallback( llhttp_t * pHttpParser,
const char * pLoc,
size_t length );
/**
* @brief Callback invoked during llhttp_execute() when the HTTP response
* status parsing is complete.
*
* @param[in] pHttpParser Parsing object containing state and callback context.
*
* @return #LLHTTP_CONTINUE_PARSING to continue parsing.
*/
static int httpParserOnStatusCompleteCallback( llhttp_t * pHttpParser );
/**
* @brief Callback invoked during llhttp_execute() when an HTTP response
* header field is found.
*
* If only part of the header field was found, then parsing of the next part of
* the response message will invoke this callback in succession.
*
* @param[in] pHttpParser Parsing object containing state and callback context.
* @param[in] pLoc Location of the header field string in the response
* message buffer.
* @param[in] length Length of the header field.
*
* @return #LLHTTP_CONTINUE_PARSING to continue parsing.
*/
static int httpParserOnHeaderFieldCallback( llhttp_t * pHttpParser,
const char * pLoc,
size_t length );
/**
* @brief Callback invoked during llhttp_execute() when an HTTP response
* header value is found.
*
* This header value corresponds to the header field that was found in the
* immediately preceding httpParserOnHeaderFieldCallback().
*
* If only part of the header value was found, then parsing of the next part of
* the response message will invoke this callback in succession.
*
* @param[in] pHttpParser Parsing object containing state and callback context.
* @param[in] pLoc Location of the header value in the response message buffer.
* @param[in] length Length of the header value.
*
* @return #LLHTTP_CONTINUE_PARSING to continue parsing.
*/
static int httpParserOnHeaderValueCallback( llhttp_t * pHttpParser,
const char * pLoc,
size_t length );
/**
* @brief Callback invoked during llhttp_execute() when the end of the
* headers are found.
*
* The end of the headers is signaled in a HTTP response message by another
* "\r\n" after the final header line.
*
* @param[in] pHttpParser Parsing object containing state and callback context.
*
* @return #LLHTTP_CONTINUE_PARSING to continue parsing.
* #LLHTTP_STOP_PARSING_NO_BODY is returned if the response is for a HEAD request.
*/
static int httpParserOnHeadersCompleteCallback( llhttp_t * pHttpParser );
/**
* @brief Callback invoked during llhttp_execute() when the HTTP response
* body is found.
*
* If only part of the response body was found, then parsing of the next part of
* the response message will invoke this callback in succession.
*
* This callback will be also invoked in succession if the response body is of
* type "Transfer-Encoding: chunked". This callback will be invoked after each
* chunk header.
*
* The follow is an example of a Transfer-Encoding chunked response:
*
* @code
* HTTP/1.1 200 OK\r\n
* Content-Type: text/plain\r\n
* Transfer-Encoding: chunked\r\n
* \r\n
* d\r\n
* Hello World! \r\n
* 7\r\n
* I am a \r\n
* a\r\n
* developer.\r\n
* 0\r\n
* \r\n
* @endcode
*
* The first invocation of this callback will contain @p pLoc = "Hello World!"
* and @p length = 13.
* The second invocation of this callback will contain @p pLoc = "I am a " and
* @p length = 7.
* The third invocation of this callback will contain @p pLoc = "developer." and
* @p length = 10.
*
* @param[in] pHttpParser Parsing object containing state and callback context.
* @param[in] pLoc - Pointer to the body string in the response message buffer.
* @param[in] length - The length of the body found.
*
* @return Zero to continue parsing. All other return values will stop parsing
* and llhttp_execute() will return with the same value.
*/
static int httpParserOnBodyCallback( llhttp_t * pHttpParser,
const char * pLoc,
size_t length );
/**
* @brief Callback invoked during llhttp_execute() to indicate the the
* completion of an HTTP response message.
*
* When there is no response body, the end of the response message is when the
* headers end. This is indicated by another "\r\n" after the final header line.
*
* When there is response body, the end of the response message is when the
* full "Content-Length" value is parsed following the end of the headers. If
* there is no Content-Length header, then llhttp_execute() expects a
* zero length-ed parsing data to indicate the end of the response.
*
* For a "Transfer-Encoding: chunked" type of response message, the complete
* response message is signaled by a terminating chunk header with length zero.
*
* See https://github.com/nodejs/llhttp for more information.
*
* @param[in] pHttpParser Parsing object containing state and callback context.
*
* @return Zero to continue parsing. All other return values will stop parsing
* and llhttp_execute() will return with the same value.
*/
static int httpParserOnMessageCompleteCallback( llhttp_t * pHttpParser );
/**
* @brief When a complete header is found the HTTP response header count
* increases and the application is notified.
*
* This function is invoked only in callbacks that could follow
* #httpParserOnHeaderValueCallback. These callbacks are
* #httpParserOnHeaderFieldCallback and #httpParserOnHeadersCompleteCallback.
* A header field and value is not is not known to be complete until
* #httpParserOnHeaderValueCallback is not called in succession.
*
* @param[in] pParsingContext Parsing state containing information to notify
* the application of a complete header.
*/
static void processCompleteHeader( HTTPParsingContext_t * pParsingContext );
/**
* @brief When parsing is complete an error could be indicated in
* pHttpParser->error. This function translates that error into a library
* specific error code.
*
* @param[in] pHttpParser Third-party HTTP parsing context.
*
* @return One of the following:
* - #HTTPSuccess
* - #HTTPSecurityAlertExtraneousResponseData
* - #HTTPSecurityAlertInvalidChunkHeader
* - #HTTPSecurityAlertInvalidProtocolVersion
* - #HTTPSecurityAlertInvalidStatusCode
* - #HTTPSecurityAlertInvalidCharacter
* - #HTTPSecurityAlertInvalidContentLength
* - #HTTPParserInternalError
*/
static HTTPStatus_t processLlhttpError( const llhttp_t * pHttpParser );
/**
* @brief Compares at most the first n bytes of str1 and str2 without case sensitivity
* and n must be less than the actual size of either string.
*
* @param[in] str1 First string to be compared.
* @param[in] str2 Second string to be compared.
* @param[in] n The maximum number of characters to be compared.
*
* @return One of the following:
* 0 if str1 is equal to str2
* 1 if str1 is not equal to str2.
*/
static int8_t caseInsensitiveStringCmp( const char * str1,
const char * str2,
size_t n );
/*-----------------------------------------------------------*/
static uint32_t getZeroTimestampMs( void )
{
return 0U;
}
/*-----------------------------------------------------------*/
static int8_t caseInsensitiveStringCmp( const char * str1,
const char * str2,
size_t n )
{
size_t i = 0U;
/* Inclusion of temporary variables for MISRA rule 13.2 compliance */
char firstChar;
char secondChar;
/* Get the offset from a lowercase to capital character in a MISRA compliant way */
int8_t offset = 'a' - 'A';
for( i = 0U; i < n; i++ )
{
firstChar = str1[ i ];
secondChar = str2[ i ];
/* Subtract offset to go from lowercase to uppercase ASCII character */
if( ( firstChar >= 'a' ) && ( firstChar <= 'z' ) )
{
firstChar = ( char ) ( firstChar - offset );
}
if( ( secondChar >= 'a' ) && ( secondChar <= 'z' ) )
{
secondChar = ( char ) ( secondChar - offset );
}
if( ( firstChar ) != ( secondChar ) )
{
break;
}
}
return ( i == n ) ? 0 : 1;
}
/*-----------------------------------------------------------*/
static void processCompleteHeader( HTTPParsingContext_t * pParsingContext )
{
HTTPResponse_t * pResponse = NULL;
assert( pParsingContext != NULL );
assert( pParsingContext->pResponse != NULL );
pResponse = pParsingContext->pResponse;
/* A header is complete when both the last header field and value have been
* filled in. */
if( ( pParsingContext->pLastHeaderField != NULL ) &&
( pParsingContext->pLastHeaderValue != NULL ) )
{
assert( pResponse->headerCount < SIZE_MAX );
/* Increase the header count. */
pResponse->headerCount++;
LogDebug( ( "Response parsing: Found complete header: "
"HeaderField=%.*s, HeaderValue=%.*s",
( int ) ( pParsingContext->lastHeaderFieldLen ),
pParsingContext->pLastHeaderField,
( int ) ( pParsingContext->lastHeaderValueLen ),
pParsingContext->pLastHeaderValue ) );
/* If the application registered a callback, then it must be notified. */
if( pResponse->pHeaderParsingCallback != NULL )
{
pResponse->pHeaderParsingCallback->onHeaderCallback(
pResponse->pHeaderParsingCallback->pContext,
pParsingContext->pLastHeaderField,
pParsingContext->lastHeaderFieldLen,
pParsingContext->pLastHeaderValue,
pParsingContext->lastHeaderValueLen,
pResponse->statusCode );
}
/* Prepare the next header field and value for the first invocation of
* httpParserOnHeaderFieldCallback() and
* httpParserOnHeaderValueCallback(). */
pParsingContext->pLastHeaderField = NULL;
pParsingContext->lastHeaderFieldLen = 0U;
pParsingContext->pLastHeaderValue = NULL;
pParsingContext->lastHeaderValueLen = 0U;
}
}
/*-----------------------------------------------------------*/
static int httpParserOnMessageBeginCallback( llhttp_t * pHttpParser )
{
HTTPParsingContext_t * pParsingContext = NULL;
assert( pHttpParser != NULL );
assert( pHttpParser->data != NULL );
pParsingContext = ( HTTPParsingContext_t * ) ( pHttpParser->data );
/* Parsing has initiated. */
pParsingContext->state = HTTP_PARSING_INCOMPLETE;
LogDebug( ( "Response parsing: Found the start of the response message." ) );
return LLHTTP_CONTINUE_PARSING;
}
/*-----------------------------------------------------------*/
static int httpParserOnStatusCallback( llhttp_t * pHttpParser,
const char * pLoc,
size_t length )
{
HTTPParsingContext_t * pParsingContext = NULL;
HTTPResponse_t * pResponse = NULL;
assert( pHttpParser != NULL );
assert( pHttpParser->data != NULL );
assert( pLoc != NULL );
pParsingContext = ( HTTPParsingContext_t * ) ( pHttpParser->data );
pResponse = pParsingContext->pResponse;
assert( pResponse != NULL );
/* Set the location of what to parse next. */
pParsingContext->pBufferCur = &pLoc[ length ];
/* Initialize the first header field and value to be passed to the user
* callback. */
pParsingContext->pLastHeaderField = NULL;
pParsingContext->lastHeaderFieldLen = 0U;
pParsingContext->pLastHeaderValue = NULL;
pParsingContext->lastHeaderValueLen = 0U;
/* httpParserOnStatusCallback() is reached because llhttp_execute() has
* successfully read the HTTP response status code. */
pResponse->statusCode = ( uint16_t ) ( pHttpParser->status_code );
LogDebug( ( "Response parsing: Found the Reason-Phrase: "
"StatusCode=%u, ReasonPhrase=%.*s",
( unsigned int ) pResponse->statusCode,
( int ) length,
pLoc ) );
return LLHTTP_CONTINUE_PARSING;
}
/*-----------------------------------------------------------*/
static int httpParserOnStatusCompleteCallback( llhttp_t * pHttpParser )
{
HTTPParsingContext_t * pParsingContext = NULL;
HTTPResponse_t * pResponse = NULL;
assert( pHttpParser != NULL );
assert( pHttpParser->data != NULL );
pParsingContext = ( HTTPParsingContext_t * ) ( pHttpParser->data );
pResponse = pParsingContext->pResponse;
assert( pResponse != NULL );
/* Initialize the first header field and value to be passed to the user
* callback. */
pParsingContext->pLastHeaderField = NULL;
pParsingContext->lastHeaderFieldLen = 0U;
pParsingContext->pLastHeaderValue = NULL;
pParsingContext->lastHeaderValueLen = 0U;
/* httpParserOnStatusCompleteCallback() is reached because llhttp_execute()
* has successfully read the HTTP response status code. */
pResponse->statusCode = ( uint16_t ) ( pHttpParser->status_code );
LogDebug( ( "Response parsing: StatusCode=%u",
( unsigned int ) pResponse->statusCode ) );
return LLHTTP_CONTINUE_PARSING;
}
/*-----------------------------------------------------------*/
static int httpParserOnHeaderFieldCallback( llhttp_t * pHttpParser,
const char * pLoc,
size_t length )
{
HTTPParsingContext_t * pParsingContext = NULL;
HTTPResponse_t * pResponse = NULL;
assert( pHttpParser != NULL );
assert( pHttpParser->data != NULL );
assert( pLoc != NULL );
pParsingContext = ( HTTPParsingContext_t * ) ( pHttpParser->data );
pResponse = pParsingContext->pResponse;
assert( pResponse != NULL );
/* If this is the first time httpParserOnHeaderFieldCallback() has been
* invoked on a response, then the start of the response headers is NULL. */
if( pResponse->pHeaders == NULL )
{
pResponse->pHeaders = ( const uint8_t * ) pLoc;
}
/* Set the location of what to parse next. */
pParsingContext->pBufferCur = &pLoc[ length ];
/* The httpParserOnHeaderFieldCallback() always follows the
* httpParserOnHeaderValueCallback() if there is another header field. When
* httpParserOnHeaderValueCallback() is not called in succession, then a
* complete header has been found. */
processCompleteHeader( pParsingContext );
/* If httpParserOnHeaderFieldCallback() is invoked in succession, then the
* last time llhttp_execute() was called only part of the header field
* was parsed. The indication of successive invocations is a non-NULL
* pParsingContext->pLastHeaderField. */
if( pParsingContext->pLastHeaderField == NULL )
{
pParsingContext->pLastHeaderField = pLoc;
pParsingContext->lastHeaderFieldLen = length;
}
else
{
assert( pParsingContext->lastHeaderFieldLen <= SIZE_MAX - length );
pParsingContext->lastHeaderFieldLen += length;
}
LogDebug( ( "Response parsing: Found a header field: "
"HeaderField=%.*s",
( int ) length,
pLoc ) );
return LLHTTP_CONTINUE_PARSING;
}
/*-----------------------------------------------------------*/
static int httpParserOnHeaderValueCallback( llhttp_t * pHttpParser,
const char * pLoc,
size_t length )
{
HTTPParsingContext_t * pParsingContext = NULL;
assert( pHttpParser != NULL );
assert( pHttpParser->data != NULL );
assert( pLoc != NULL );
pParsingContext = ( HTTPParsingContext_t * ) ( pHttpParser->data );
/* Set the location of what to parse next. */
pParsingContext->pBufferCur = &pLoc[ length ];
/* If httpParserOnHeaderValueCallback() is invoked in succession, then the
* last time llhttp_execute() was called only part of the header field
* was parsed. The indication of successive invocations is a non-NULL
* pParsingContext->pLastHeaderField. */
if( pParsingContext->pLastHeaderValue == NULL )
{
pParsingContext->pLastHeaderValue = pLoc;
pParsingContext->lastHeaderValueLen = length;
}
else
{
pParsingContext->lastHeaderValueLen += length;
}
/* Given that httpParserOnHeaderFieldCallback() is ALWAYS invoked before
* httpParserOnHeaderValueCallback() is invoked, then the last header field
* should never be NULL. This would indicate a bug in the llhttp library. */
assert( pParsingContext->pLastHeaderField != NULL );
LogDebug( ( "Response parsing: Found a header value: "
"HeaderValue=%.*s",
( int ) length,
pLoc ) );
return LLHTTP_CONTINUE_PARSING;
}
/*-----------------------------------------------------------*/
static int httpParserOnHeadersCompleteCallback( llhttp_t * pHttpParser )
{
int shouldContinueParse = LLHTTP_CONTINUE_PARSING;
HTTPParsingContext_t * pParsingContext = NULL;
HTTPResponse_t * pResponse = NULL;
assert( pHttpParser != NULL );
assert( pHttpParser->data != NULL );
pParsingContext = ( HTTPParsingContext_t * ) ( pHttpParser->data );
pResponse = pParsingContext->pResponse;
assert( pResponse != NULL );
assert( pParsingContext->pBufferCur != NULL );
/* Flag indicating that the headers have been completely signed - useful for libraries built on top of corehttp. */
pResponse->areHeadersComplete = 1;
/* The current location to parse was updated in previous callbacks and MUST
* always be within the response buffer. */
assert( pParsingContext->pBufferCur >= ( const char * ) ( pResponse->pBuffer ) );
assert( pParsingContext->pBufferCur < ( const char * ) ( pResponse->pBuffer + pResponse->bufferLen ) );
/* `\r\n\r\n`, `\r\n\n`, `\n\r\n`, and `\n\n` are all valid indicators of
* the end of the response headers. To reduce complexity these characters
* are not included in the response headers length returned to the user. */
/* If headers existed, then pResponse->pHeaders was set during the first
* call to httpParserOnHeaderFieldCallback(). */
if( pResponse->pHeaders != NULL )
{
/* The start of the headers ALWAYS come before the the end of the headers. */
assert( ( const char * ) ( pResponse->pHeaders ) < pParsingContext->pBufferCur );
/* MISRA Ref 10.8.1 [Essential type casting] */
/* More details at: https://github.com/FreeRTOS/coreHTTP/blob/main/MISRA.md#rule-108 */
/* coverity[misra_c_2012_rule_10_8_violation] */
pResponse->headersLen = ( size_t ) ( pParsingContext->pBufferCur - ( const char * ) ( pResponse->pHeaders ) );
}
else
{
pResponse->headersLen = 0U;
}
/* MISRA Ref 14.3.1 [Configuration dependent invariant] */
/* More details at: https://github.com/FreeRTOS/coreHTTP/blob/main/MISRA.md#rule-143 */
/* coverity[misra_c_2012_rule_14_3_violation] */
if( pHttpParser->content_length != UINT64_MAX )
{
pResponse->contentLength = ( size_t ) ( pHttpParser->content_length );
}
else
{
pResponse->contentLength = 0U;
}
/* If the Connection: close header was found this flag will be set. */
if( ( pHttpParser->flags & ( unsigned int ) ( F_CONNECTION_CLOSE ) ) != 0U )
{
pResponse->respFlags |= HTTP_RESPONSE_CONNECTION_CLOSE_FLAG;
}
/* If the Connection: keep-alive header was found this flag will be set. */
if( ( pHttpParser->flags & ( unsigned int ) ( F_CONNECTION_KEEP_ALIVE ) ) != 0U )
{
pResponse->respFlags |= HTTP_RESPONSE_CONNECTION_KEEP_ALIVE_FLAG;
}
/* llhttp_execute() requires that callback implementations must
* indicate that parsing stops on headers complete, if response is to a HEAD
* request. A HEAD response will contain Content-Length, but no body. If
* the parser is not stopped here, then it will try to keep parsing past the
* end of the headers up to the Content-Length found. */
if( pParsingContext->isHeadResponse == 1U )
{
shouldContinueParse = LLHTTP_STOP_PARSING_NO_BODY;
}
/* If headers are present in the response, then
* httpParserOnHeadersCompleteCallback() always follows
* the httpParserOnHeaderValueCallback(). When
* httpParserOnHeaderValueCallback() is not called in succession, then a
* complete header has been found. */
processCompleteHeader( pParsingContext );
LogDebug( ( "Response parsing: Found the end of the headers." ) );
/* If there is HTTP_RESPONSE_DO_NOT_PARSE_BODY_FLAG opt-in we should stop
* parsing here. */
if( ( pResponse->respOptionFlags & HTTP_RESPONSE_DO_NOT_PARSE_BODY_FLAG ) != 0U )
{
shouldContinueParse = ( int ) LLHTTP_PAUSE_PARSING;
}
return shouldContinueParse;
}
/*-----------------------------------------------------------*/
static int httpParserOnBodyCallback( llhttp_t * pHttpParser,
const char * pLoc,
size_t length )
{
int shouldContinueParse = LLHTTP_CONTINUE_PARSING;
HTTPParsingContext_t * pParsingContext = NULL;
HTTPResponse_t * pResponse = NULL;
char * pNextWriteLoc = NULL;
assert( pHttpParser != NULL );
assert( pHttpParser->data != NULL );
assert( pLoc != NULL );
pParsingContext = ( HTTPParsingContext_t * ) ( pHttpParser->data );
pResponse = pParsingContext->pResponse;
assert( pResponse != NULL );
assert( pResponse->pBuffer != NULL );
assert( pLoc >= ( const char * ) ( pResponse->pBuffer ) );
assert( pLoc < ( const char * ) ( pResponse->pBuffer + pResponse->bufferLen ) );
/* If this is the first time httpParserOnBodyCallback() has been invoked,
* then the start of the response body is NULL. */
if( pResponse->pBody == NULL )
{
/* Ideally the start of the body should follow right after the header
* end indicating characters, but to reduce complexity and ensure users
* are given the correct start of the body, we set the start of the body
* to what the parser tells us is the start. This could come after the
* initial transfer encoding chunked header. */
pResponse->pBody = ( const uint8_t * ) ( pLoc );
pResponse->bodyLen = 0U;
}
/* The next location to write. */
/* MISRA Ref 11.8.1 [Removal of const from pointer] */
/* More details at: https://github.com/FreeRTOS/coreHTTP/blob/main/MISRA.md#rule-118 */
/* coverity[misra_c_2012_rule_11_8_violation] */
pNextWriteLoc = ( char * ) ( &( pResponse->pBody[ pResponse->bodyLen ] ) );
/* If the response is of type Transfer-Encoding: chunked, then actual body
* will follow the the chunked header. This body data is in a later location
* and must be moved up in the buffer. When pLoc is greater than the current
* end of the body, that signals the parser found a chunk header. */
/* MISRA Ref 18.3.1 [Pointer comparison] */
/* More details at: https://github.com/FreeRTOS/coreHTTP/blob/main/MISRA.md#rule-183 */
/* coverity[pointer_parameter] */
/* coverity[misra_c_2012_rule_18_3_violation] */
if( pLoc > pNextWriteLoc )
{
/* memmove is used instead of memcpy because memcpy has undefined behavior
* when source and destination locations in memory overlap. */
( void ) memmove( pNextWriteLoc, pLoc, length );
}
/* Increase the length of the body found. */
pResponse->bodyLen += length;
/* Set the next location of parsing. */
pParsingContext->pBufferCur = &pLoc[ length ];
LogDebug( ( "Response parsing: Found the response body: "
"BodyLength=%lu",
( unsigned long ) length ) );
return shouldContinueParse;
}
/*-----------------------------------------------------------*/
static int httpParserOnMessageCompleteCallback( llhttp_t * pHttpParser )
{
HTTPParsingContext_t * pParsingContext = NULL;
assert( pHttpParser != NULL );
assert( pHttpParser->data != NULL );
pParsingContext = ( HTTPParsingContext_t * ) ( pHttpParser->data );
/* The response message is complete. */
pParsingContext->state = HTTP_PARSING_COMPLETE;
LogDebug( ( "Response parsing: Response message complete." ) );
return LLHTTP_CONTINUE_PARSING;
}
/*-----------------------------------------------------------*/
static void initializeParsingContextForFirstResponse( HTTPParsingContext_t * pParsingContext,