Skip to content

Commit 1a4d737

Browse files
committed
initial
0 parents  commit 1a4d737

19 files changed

Lines changed: 1294 additions & 0 deletions

.clang-format

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
---
2+
Language: Cpp
3+
# BasedOnStyle: LLVM
4+
AccessModifierOffset: -2
5+
AlignAfterOpenBracket: Align
6+
AlignArrayOfStructures: None
7+
AlignConsecutiveMacros:
8+
Enabled: true
9+
AcrossEmptyLines: true
10+
AcrossComments: true
11+
AlignConsecutiveAssignments: None
12+
AlignConsecutiveBitFields:
13+
Enabled: true
14+
AcrossEmptyLines: true
15+
AcrossComments: true
16+
AlignConsecutiveDeclarations: None
17+
AlignEscapedNewlines: Right
18+
AlignOperands: Align
19+
SortIncludes: true
20+
InsertBraces: true # Control statements must have curly brackets
21+
AlignTrailingComments: true
22+
AllowAllArgumentsOnNextLine: true
23+
AllowAllParametersOfDeclarationOnNextLine: true
24+
AllowShortEnumsOnASingleLine: true
25+
AllowShortBlocksOnASingleLine: Empty
26+
AllowShortCaseLabelsOnASingleLine: true
27+
AllowShortFunctionsOnASingleLine: All
28+
AllowShortLambdasOnASingleLine: All
29+
AllowShortIfStatementsOnASingleLine: Never
30+
AllowShortLoopsOnASingleLine: false
31+
AlwaysBreakAfterDefinitionReturnType: None
32+
AlwaysBreakAfterReturnType: AllDefinitions
33+
AlwaysBreakBeforeMultilineStrings: false
34+
AlwaysBreakTemplateDeclarations: Yes
35+
AttributeMacros:
36+
- __capability
37+
BinPackArguments: true
38+
BinPackParameters: true
39+
BraceWrapping:
40+
AfterCaseLabel: false
41+
AfterClass: false
42+
AfterControlStatement: Never
43+
AfterEnum: false
44+
AfterFunction: false
45+
AfterNamespace: false
46+
AfterObjCDeclaration: false
47+
AfterStruct: false
48+
AfterUnion: false
49+
AfterExternBlock: false
50+
BeforeCatch: false
51+
BeforeElse: false
52+
BeforeLambdaBody: false
53+
BeforeWhile: false
54+
IndentBraces: false
55+
SplitEmptyFunction: true
56+
SplitEmptyRecord: true
57+
SplitEmptyNamespace: true
58+
BreakBeforeBinaryOperators: NonAssignment
59+
BreakBeforeConceptDeclarations: true
60+
BreakBeforeBraces: Attach
61+
BreakBeforeInheritanceComma: false
62+
BreakInheritanceList: BeforeColon
63+
BreakBeforeTernaryOperators: true
64+
BreakConstructorInitializersBeforeComma: false
65+
BreakConstructorInitializers: BeforeColon
66+
BreakAfterJavaFieldAnnotations: false
67+
BreakStringLiterals: true
68+
ColumnLimit: 120
69+
CommentPragmas: "^ IWYU pragma:"
70+
QualifierAlignment: Leave
71+
CompactNamespaces: false
72+
ConstructorInitializerIndentWidth: 4
73+
ContinuationIndentWidth: 4
74+
Cpp11BracedListStyle: true
75+
DeriveLineEnding: true
76+
DerivePointerAlignment: false
77+
DisableFormat: false
78+
EmptyLineAfterAccessModifier: Never
79+
EmptyLineBeforeAccessModifier: LogicalBlock
80+
ExperimentalAutoDetectBinPacking: false
81+
PackConstructorInitializers: BinPack
82+
BasedOnStyle: ""
83+
ConstructorInitializerAllOnOneLineOrOnePerLine: false
84+
AllowAllConstructorInitializersOnNextLine: true
85+
FixNamespaceComments: true
86+
ForEachMacros:
87+
- foreach
88+
- Q_FOREACH
89+
- BOOST_FOREACH
90+
IfMacros:
91+
- KJ_IF_MAYBE
92+
IncludeBlocks: Preserve
93+
IncludeCategories:
94+
- Regex: "^<(.*)>"
95+
Priority: 0
96+
- Regex: '^"(.*)"'
97+
Priority: 1
98+
- Regex: "(.*)"
99+
Priority: 2
100+
IncludeIsMainRegex: "(Test)?$"
101+
IncludeIsMainSourceRegex: ""
102+
IndentAccessModifiers: false
103+
IndentCaseLabels: true
104+
IndentCaseBlocks: false
105+
IndentGotoLabels: true
106+
IndentPPDirectives: None
107+
IndentExternBlock: AfterExternBlock
108+
IndentRequires: true
109+
IndentWidth: 4
110+
IndentWrappedFunctionNames: false
111+
InsertTrailingCommas: None
112+
JavaScriptQuotes: Leave
113+
JavaScriptWrapImports: true
114+
KeepEmptyLinesAtTheStartOfBlocks: true
115+
LambdaBodyIndentation: Signature
116+
MacroBlockBegin: ""
117+
MacroBlockEnd: ""
118+
MaxEmptyLinesToKeep: 1
119+
NamespaceIndentation: None
120+
ObjCBinPackProtocolList: Auto
121+
ObjCBlockIndentWidth: 2
122+
ObjCBreakBeforeNestedBlockParam: true
123+
ObjCSpaceAfterProperty: false
124+
ObjCSpaceBeforeProtocolList: true
125+
PenaltyBreakAssignment: 2
126+
PenaltyBreakBeforeFirstCallParameter: 19
127+
PenaltyBreakComment: 300
128+
PenaltyBreakFirstLessLess: 120
129+
PenaltyBreakOpenParenthesis: 0
130+
PenaltyBreakString: 1000
131+
PenaltyBreakTemplateDeclaration: 10
132+
PenaltyExcessCharacter: 1000000
133+
PenaltyReturnTypeOnItsOwnLine: 60
134+
PenaltyIndentedWhitespace: 0
135+
PointerAlignment: Left
136+
PPIndentWidth: -1
137+
ReferenceAlignment: Pointer
138+
ReflowComments: false
139+
RemoveBracesLLVM: false
140+
SeparateDefinitionBlocks: Always
141+
ShortNamespaceLines: 1
142+
SortJavaStaticImport: Before
143+
SortUsingDeclarations: true
144+
SpaceAfterCStyleCast: false
145+
SpaceAfterLogicalNot: false
146+
SpaceAfterTemplateKeyword: true
147+
SpaceBeforeAssignmentOperators: true
148+
SpaceBeforeCaseColon: false
149+
SpaceBeforeParens: ControlStatements
150+
SpaceBeforeParensOptions:
151+
AfterControlStatements: true
152+
AfterForeachMacros: true
153+
AfterFunctionDefinitionName: false
154+
AfterFunctionDeclarationName: false
155+
AfterIfMacros: true
156+
AfterOverloadedOperator: false
157+
BeforeNonEmptyParentheses: false
158+
SpaceAroundPointerQualifiers: Default
159+
SpaceBeforeRangeBasedForLoopColon: true
160+
SpaceInEmptyBlock: false
161+
SpaceInEmptyParentheses: false
162+
SpacesBeforeTrailingComments: 1
163+
SpacesInAngles: Never
164+
SpacesInConditionalStatement: false
165+
SpacesInContainerLiterals: true
166+
SpacesInCStyleCastParentheses: false
167+
SpacesInLineCommentPrefix:
168+
Minimum: 1
169+
Maximum: -1
170+
SpacesInParentheses: false
171+
SpacesInSquareBrackets: false
172+
SpaceBeforeSquareBrackets: false
173+
BitFieldColonSpacing: Both
174+
Standard: Latest
175+
StatementAttributeLikeMacros:
176+
- Q_EMIT
177+
StatementMacros:
178+
- Q_UNUSED
179+
- QT_REQUIRE_VERSION
180+
TabWidth: 8
181+
UseCRLF: false
182+
UseTab: Never
183+
WhitespaceSensitiveMacros:
184+
- STRINGIZE
185+
- PP_STRINGIZE
186+
- BOOST_PP_STRINGIZE
187+
- NS_SWIFT_NAME
188+
- CF_SWIFT_NAME
189+
SpaceBeforeCpp11BracedList: false
190+
SpaceBeforeCtorInitializerColon: true
191+
SpaceBeforeInheritanceColon: true
192+
---
193+

.gitignore

Whitespace-only changes.

CMakeLists.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
project (lcorehttp)
2+
3+
file(GLOB lcorehttp_sources ./src/**.c)
4+
set(lcorehttp ${lcorehttp_sources})
5+
6+
add_library(lcorehttp ${lcorehttp})
7+
target_link_libraries(lcorehttp)

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2023 alis-is
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Lua CoreHTTP
2+
3+
Lua CoreHTTP is a lightweight binding to CoreHTTP, designed to extend the HTTP functionality in Lua projects. It leverages lua-simple-socket for underlying transport layer operations, ensuring a simplistic yet powerful interface for HTTP communications. With mbed TLS integration, Lua CoreHTTP also provides secure transmission capabilities.
4+
5+
## Features
6+
7+
- Lightweight binding to CoreHTTP.
8+
- HTTP client and server functionalities.
9+
- TLS/SSL support through mbed TLS integration.
10+
- Dependable transport layer operations through lua-simple-socket.
11+
12+
## Dependencies
13+
14+
- [lua-simple-socket](https://github.com/alis-is/lua-simple-socket)
15+
- [mbed TLS](https://tls.mbed.org/)
16+

include/core_http_config.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// #define HTTP_DO_NOT_USE_CUSTOM_CONFIG
2+
#ifndef COREHTTP_CONFIG_H
3+
#define COREHTTP_CONFIG_H
4+
5+
#include <stdio.h>
6+
#include "logging.h"
7+
8+
#define HTTP_USER_AGENT_VALUE "lua-corehttp"
9+
// #define HTTP_RECV_RETRY_TIMEOUT_MS 1U
10+
// #define DEBUG_COREHTTP 1
11+
12+
#if defined(DEBUG_COREHTTP)
13+
#define LogError(args) internal_log args
14+
#define LogWarn(args) internal_log args
15+
#define LogInfo(args) internal_log args
16+
#define LogDebug(args) internal_log args
17+
#endif
18+
19+
#endif

include/logging.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#ifndef LOGGING_H
2+
#define LOGGING_H
3+
4+
#include <stdarg.h>
5+
#include <stdio.h>
6+
7+
#define LOG_METADATA_FORMAT "%s:%d"
8+
#define LIBRARY_LOG_NAME "YourLibrary"
9+
#define LOG_METADATA_ARGS __FILE__, __LINE__
10+
11+
void internal_log(const char* format, ...);
12+
13+
#endif // LOGGING_H

src/extended_core_http_client.c

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
#include <assert.h>
2+
#include <stdlib.h>
3+
#include "core_http_client.h"
4+
#include "core_http_client_private.h"
5+
#include "extended_core_http_client.h"
6+
#include "lcorehttp_client.h"
7+
8+
static uint32_t
9+
getZeroTimestampMs(void) {
10+
return 0U;
11+
}
12+
13+
HTTPStatus_t
14+
HTTPClient_Validate(const TransportInterface_t* pTransport, HTTPRequestHeaders_t* pRequestHeaders,
15+
const uint8_t* pRequestBodyBuf, size_t reqBodyBufLen, HTTPResponse_t* pResponse) {
16+
HTTPStatus_t returnStatus = HTTPInvalidParameter;
17+
18+
if (pTransport == NULL) {
19+
LogError(("Parameter check failed: pTransport interface is NULL."));
20+
} else if (pTransport->send == NULL) {
21+
LogError(("Parameter check failed: pTransport->send is NULL."));
22+
} else if (pTransport->recv == NULL) {
23+
LogError(("Parameter check failed: pTransport->recv is NULL."));
24+
} else if (pRequestHeaders == NULL) {
25+
LogError(("Parameter check failed: pRequestHeaders is NULL."));
26+
} else if (pRequestHeaders->pBuffer == NULL) {
27+
LogError(("Parameter check failed: pRequestHeaders->pBuffer is NULL."));
28+
} else if (pRequestHeaders->headersLen < HTTP_MINIMUM_REQUEST_LINE_LENGTH) {
29+
LogError(("Parameter check failed: pRequestHeaders->headersLen "
30+
"does not meet minimum the required length. "
31+
"MinimumRequiredLength=%u, HeadersLength=%lu",
32+
HTTP_MINIMUM_REQUEST_LINE_LENGTH, (unsigned long)(pRequestHeaders->headersLen)));
33+
} else if (pRequestHeaders->headersLen > pRequestHeaders->bufferLen) {
34+
LogError(("Parameter check failed: pRequestHeaders->headersLen > "
35+
"pRequestHeaders->bufferLen."));
36+
} else if (pResponse == NULL) {
37+
LogError(("Parameter check failed: pResponse is NULL. "));
38+
} else if (pResponse->pBuffer == NULL) {
39+
LogError(("Parameter check failed: pResponse->pBuffer is NULL."));
40+
} else if (pResponse->bufferLen == 0U) {
41+
LogError(("Parameter check failed: pResponse->bufferLen is zero."));
42+
} else if ((pRequestBodyBuf == NULL) && (reqBodyBufLen > 0U)) {
43+
/* If there is no body to send we must ensure that the reqBodyBufLen is
44+
* zero so that no Content-Length header is automatically written. */
45+
LogError(("Parameter check failed: pRequestBodyBuf is NULL, but "
46+
"reqBodyBufLen is greater than zero."));
47+
} else if (reqBodyBufLen > (size_t)(INT32_MAX)) {
48+
/* This check is needed because convertInt32ToAscii() is used on the
49+
* reqBodyBufLen to create a Content-Length header value string. */
50+
LogError(("Parameter check failed: reqBodyBufLen > INT32_MAX."
51+
"reqBodyBufLen=%lu",
52+
(unsigned long)reqBodyBufLen));
53+
} else {
54+
if (pResponse->getTime == NULL) {
55+
/* Set a zero timestamp function when the application did not configure
56+
* one. */
57+
pResponse->getTime = getZeroTimestampMs;
58+
}
59+
60+
returnStatus = HTTPSuccess;
61+
}
62+
63+
return returnStatus;
64+
}
65+
66+
HTTPStatus_t
67+
HTTPClient_Read(const TransportInterface_t* pTransport, HTTPResponse_t* pResponse, uint8_t* pBuffer,
68+
size_t bufferCapacity, size_t* pBytesRead) {
69+
HTTPStatus_t returnStatus = HTTPSuccess;
70+
uint8_t shouldRecv = 1U, timeoutReached = 0U;
71+
size_t totalReceived = 0U;
72+
int32_t currentReceived = 0;
73+
uint32_t lastRecvTimeMs = 0U, timeSinceLastRecvMs = 0U;
74+
uint32_t retryTimeoutMs = HTTP_RECV_RETRY_TIMEOUT_MS;
75+
76+
lastRecvTimeMs = pResponse->getTime();
77+
78+
while (shouldRecv == 1U) {
79+
/* Receive the HTTP response data into the pResponse->pBuffer. */
80+
currentReceived =
81+
pTransport->recv(pTransport->pNetworkContext, pBuffer + totalReceived, bufferCapacity - totalReceived);
82+
if (currentReceived < 0) {
83+
LogError(("Failed to receive HTTP data: Transport recv() "
84+
"returned error: TransportStatus=%ld",
85+
(long int)currentReceived));
86+
returnStatus = HTTPNetworkError;
87+
} else if (currentReceived > 0) {
88+
/* Reset the time of the last data received when data is received. */
89+
lastRecvTimeMs = pResponse->getTime();
90+
/* MISRA compliance requires the cast to an unsigned type, since we have checked that
91+
* the value of current received is greater than 0 we don't need to worry about int overflow. */
92+
totalReceived += (size_t)currentReceived;
93+
} else {
94+
timeSinceLastRecvMs = pResponse->getTime() - lastRecvTimeMs;
95+
/* Check if the allowed elapsed time between non-zero data has been
96+
* reached. */
97+
if (timeSinceLastRecvMs >= retryTimeoutMs) {
98+
timeoutReached = 1U;
99+
}
100+
}
101+
shouldRecv =
102+
((returnStatus == HTTPSuccess) && (timeoutReached == 0U) && (totalReceived < bufferCapacity)) ? 1U : 0U;
103+
}
104+
*pBytesRead = totalReceived;
105+
106+
return returnStatus;
107+
}
108+
109+
HTTPStatus_t
110+
HTTPClient_Write(const TransportInterface_t* pTransport, HTTPClient_GetCurrentTimeFunc_t getTimestampMs,
111+
const uint8_t* pData, size_t dataLen) {
112+
return HTTPClient_InternalSendHttpData(pTransport, getTimestampMs, pData, dataLen);
113+
}

0 commit comments

Comments
 (0)