20#include <freerdp/config.h>
26#include <winpr/print.h>
27#include <winpr/stream.h>
28#include <winpr/string.h>
30#include <winpr/sysinfo.h>
32#include <freerdp/log.h>
33#include <freerdp/crypto/crypto.h>
36#include <winpr/crypto.h>
38#ifdef FREERDP_HAVE_VALGRIND_MEMCHECK_H
39#include <valgrind/memcheck.h>
46#define TAG FREERDP_TAG("core.gateway.http")
48#define RESPONSE_SIZE_LIMIT (64ULL * 1024ULL * 1024ULL)
50#define WEBSOCKET_MAGIC_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
58 BOOL websocketUpgrade;
59 char* SecWebsocketKey;
60 wListDictionary* cookies;
72 TRANSFER_ENCODING TransferEncoding;
86 TRANSFER_ENCODING TransferEncoding;
87 char* SecWebsocketVersion;
88 char* SecWebsocketAccept;
93 wHashTable* Authenticates;
94 wHashTable* SetCookie;
98static wHashTable* HashTable_New_String(
void);
100static const char* string_strnstr(
const char* str1,
const char* str2,
size_t slen)
106 if ((c = *str2++) !=
'\0')
108 len = strnlen(str2, slen + 1);
114 if (slen-- < 1 || (sc = *str1++) ==
'\0')
120 }
while (strncmp(str1, str2, len) != 0);
128static BOOL strings_equals_nocase(
const void* obj1,
const void* obj2)
133 return _stricmp(obj1, obj2) == 0;
136HttpContext* http_context_new(
void)
138 HttpContext* context = (HttpContext*)calloc(1,
sizeof(HttpContext));
142 context->headers = HashTable_New_String();
143 if (!context->headers)
146 context->cookies = ListDictionary_New(FALSE);
147 if (!context->cookies)
151 wObject* key = ListDictionary_KeyObject(context->cookies);
152 wObject* value = ListDictionary_ValueObject(context->cookies);
166 WINPR_PRAGMA_DIAG_PUSH
167 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
168 http_context_free(context);
169 WINPR_PRAGMA_DIAG_POP
173BOOL http_context_set_method(HttpContext* context,
const char* Method)
175 if (!context || !Method)
178 free(context->Method);
179 context->Method = _strdup(Method);
181 return (context->Method !=
nullptr);
184BOOL http_request_set_content_type(HttpRequest* request,
const char* ContentType)
186 if (!request || !ContentType)
189 return http_request_set_header(request,
"Content-Type",
"%s", ContentType);
192const char* http_context_get_uri(HttpContext* context)
200BOOL http_context_set_uri(HttpContext* context,
const char* URI)
202 if (!context || !URI)
206 context->URI = _strdup(URI);
208 return (context->URI !=
nullptr);
211BOOL http_context_set_user_agent(HttpContext* context,
const char* UserAgent)
213 if (!context || !UserAgent)
216 return http_context_set_header(context,
"User-Agent",
"%s", UserAgent);
219BOOL http_context_set_x_ms_user_agent(HttpContext* context,
const char* X_MS_UserAgent)
221 if (!context || !X_MS_UserAgent)
224 return http_context_set_header(context,
"X-MS-User-Agent",
"%s", X_MS_UserAgent);
227BOOL http_context_set_host(HttpContext* context,
const char* Host)
229 if (!context || !Host)
232 return http_context_set_header(context,
"Host",
"%s", Host);
235BOOL http_context_set_accept(HttpContext* context,
const char* Accept)
237 if (!context || !Accept)
240 return http_context_set_header(context,
"Accept",
"%s", Accept);
243BOOL http_context_set_cache_control(HttpContext* context,
const char* CacheControl)
245 if (!context || !CacheControl)
248 return http_context_set_header(context,
"Cache-Control",
"%s", CacheControl);
251BOOL http_context_set_connection(HttpContext* context,
const char* Connection)
253 if (!context || !Connection)
256 free(context->Connection);
257 context->Connection = _strdup(Connection);
259 return (context->Connection !=
nullptr);
262WINPR_ATTR_FORMAT_ARG(2, 0)
263static BOOL list_append(HttpContext* context, WINPR_FORMAT_ARG const
char* str, va_list ap)
266 va_list vat = WINPR_C_ARRAY_INIT;
267 char* Pragma =
nullptr;
268 size_t PragmaSize = 0;
271 const int size = winpr_vasprintf(&Pragma, &PragmaSize, str, ap);
278 char* sstr =
nullptr;
282 winpr_asprintf(&sstr, &slen,
"%s, %s", context->Pragma, Pragma);
289 free(context->Pragma);
290 context->Pragma = sstr;
300WINPR_ATTR_FORMAT_ARG(2, 3)
301BOOL http_context_set_pragma(HttpContext* context, WINPR_FORMAT_ARG const
char* Pragma, ...)
303 if (!context || !Pragma)
306 free(context->Pragma);
307 context->Pragma =
nullptr;
309 va_list ap = WINPR_C_ARRAY_INIT;
310 va_start(ap, Pragma);
311 return list_append(context, Pragma, ap);
314WINPR_ATTR_FORMAT_ARG(2, 3)
315BOOL http_context_append_pragma(HttpContext* context, const
char* Pragma, ...)
317 if (!context || !Pragma)
320 va_list ap = WINPR_C_ARRAY_INIT;
321 va_start(ap, Pragma);
322 return list_append(context, Pragma, ap);
325BOOL http_context_set_rdg_connection_id(HttpContext* context,
const GUID* RdgConnectionId)
327 if (!context || !RdgConnectionId)
330 char buffer[64] = WINPR_C_ARRAY_INIT;
331 return http_context_set_header(context,
"RDG-Connection-Id",
"%s",
332 guid2str(RdgConnectionId, buffer,
sizeof(buffer)));
335BOOL http_context_set_rdg_correlation_id(HttpContext* context,
const GUID* RdgCorrelationId)
337 if (!context || !RdgCorrelationId)
340 char buffer[64] = WINPR_C_ARRAY_INIT;
341 return http_context_set_header(context,
"RDG-Correlation-Id",
"%s",
342 guid2str(RdgCorrelationId, buffer,
sizeof(buffer)));
345BOOL http_context_enable_websocket_upgrade(HttpContext* context, BOOL enable)
347 WINPR_ASSERT(context);
351 GUID key = WINPR_C_ARRAY_INIT;
352 if (RPC_S_OK != UuidCreate(&key))
355 free(context->SecWebsocketKey);
356 context->SecWebsocketKey = crypto_base64_encode((BYTE*)&key,
sizeof(key));
357 if (!context->SecWebsocketKey)
361 context->websocketUpgrade = enable;
365BOOL http_context_is_websocket_upgrade_enabled(HttpContext* context)
367 return context->websocketUpgrade;
370BOOL http_context_set_rdg_auth_scheme(HttpContext* context,
const char* RdgAuthScheme)
372 if (!context || !RdgAuthScheme)
375 return http_context_set_header(context,
"RDG-Auth-Scheme",
"%s", RdgAuthScheme);
378BOOL http_context_set_cookie(HttpContext* context,
const char* CookieName,
const char* CookieValue)
380 if (!context || !CookieName || !CookieValue)
382 if (ListDictionary_Contains(context->cookies, CookieName))
384 if (!ListDictionary_SetItemValue(context->cookies, CookieName, CookieValue))
389 if (!ListDictionary_Add(context->cookies, CookieName, CookieValue))
395void http_context_free(HttpContext* context)
399 free(context->SecWebsocketKey);
401 free(context->Method);
402 free(context->Connection);
403 free(context->Pragma);
404 HashTable_Free(context->headers);
405 ListDictionary_Free(context->cookies);
410BOOL http_request_set_method(HttpRequest* request,
const char* Method)
412 if (!request || !Method)
415 free(request->Method);
416 request->Method = _strdup(Method);
418 return (request->Method !=
nullptr);
421BOOL http_request_set_uri(HttpRequest* request,
const char* URI)
423 if (!request || !URI)
427 request->URI = _strdup(URI);
429 return (request->URI !=
nullptr);
432BOOL http_request_set_auth_scheme(HttpRequest* request,
const char* AuthScheme)
434 if (!request || !AuthScheme)
437 free(request->AuthScheme);
438 request->AuthScheme = _strdup(AuthScheme);
440 return (request->AuthScheme !=
nullptr);
443BOOL http_request_set_auth_param(HttpRequest* request,
const char* AuthParam)
445 if (!request || !AuthParam)
448 free(request->AuthParam);
449 request->AuthParam = _strdup(AuthParam);
451 return (request->AuthParam !=
nullptr);
454BOOL http_request_set_transfer_encoding(HttpRequest* request, TRANSFER_ENCODING TransferEncoding)
456 if (!request || TransferEncoding == TransferEncodingUnknown)
459 request->TransferEncoding = TransferEncoding;
464WINPR_ATTR_FORMAT_ARG(2, 3)
465static BOOL http_encode_print(
wStream* s, WINPR_FORMAT_ARG const
char* fmt, ...)
468 va_list ap = WINPR_C_ARRAY_INIT;
476 length = vsnprintf(
nullptr, 0, fmt, ap) + 1;
479 if (!Stream_EnsureRemainingCapacity(s, (
size_t)length))
482 str = (
char*)Stream_Pointer(s);
484 used = vsnprintf(str, (
size_t)length, fmt, ap);
488 if ((used + 1) != length)
491 Stream_Seek(s, (
size_t)used);
495static BOOL http_encode_body_line(
wStream* s,
const char* param,
const char* value)
497 if (!s || !param || !value)
500 return http_encode_print(s,
"%s: %s\r\n", param, value);
503static BOOL http_encode_content_length_line(
wStream* s,
size_t ContentLength)
505 return http_encode_print(s,
"Content-Length: %" PRIuz
"\r\n", ContentLength);
508static BOOL http_encode_header_line(
wStream* s,
const char* Method,
const char* URI)
510 if (!s || !Method || !URI)
513 return http_encode_print(s,
"%s %s HTTP/1.1\r\n", Method, URI);
516static BOOL http_encode_authorization_line(
wStream* s,
const char* AuthScheme,
517 const char* AuthParam)
519 if (!s || !AuthScheme || !AuthParam)
522 return http_encode_print(s,
"Authorization: %s %s\r\n", AuthScheme, AuthParam);
525static BOOL http_encode_cookie_line(
wStream* s, wListDictionary* cookies)
527 ULONG_PTR* keys =
nullptr;
533 ListDictionary_Lock(cookies);
534 const size_t count = ListDictionary_GetKeys(cookies, &keys);
539 status = http_encode_print(s,
"Cookie: ");
543 for (
size_t x = 0; status && x < count; x++)
545 char* cur = (
char*)ListDictionary_GetItemValue(cookies, (
void*)keys[x]);
553 status = http_encode_print(s,
"; ");
557 status = http_encode_print(s,
"%s=%s", (
char*)keys[x], cur);
560 status = http_encode_print(s,
"\r\n");
563 ListDictionary_Unlock(cookies);
567static BOOL write_headers(
const void* pkey,
void* pvalue,
void* arg)
569 const char* key = pkey;
570 const char* value = pvalue;
577 return http_encode_body_line(s, key, value);
580wStream* http_request_write(HttpContext* context, HttpRequest* request)
582 if (!context || !request)
585 wStream* s = Stream_New(
nullptr, 1024);
590 if (!http_encode_header_line(s, request->Method, request->URI) ||
592 !http_encode_body_line(s,
"Pragma", context->Pragma))
595 if (!context->websocketUpgrade)
597 if (!http_encode_body_line(s,
"Connection", context->Connection))
602 if (!http_encode_body_line(s,
"Connection",
"Upgrade") ||
603 !http_encode_body_line(s,
"Upgrade",
"websocket") ||
604 !http_encode_body_line(s,
"Sec-Websocket-Version",
"13") ||
605 !http_encode_body_line(s,
"Sec-Websocket-Key", context->SecWebsocketKey))
609 if (request->TransferEncoding != TransferEncodingIdentity)
611 if (request->TransferEncoding == TransferEncodingChunked)
613 if (!http_encode_body_line(s,
"Transfer-Encoding",
"chunked"))
621 if (!http_encode_content_length_line(s, request->ContentLength))
625 if (!utils_str_is_empty(request->Authorization))
627 if (!http_encode_body_line(s,
"Authorization", request->Authorization))
630 else if (!utils_str_is_empty(request->AuthScheme) && !utils_str_is_empty(request->AuthParam))
632 if (!http_encode_authorization_line(s, request->AuthScheme, request->AuthParam))
636 if (!HashTable_Foreach(context->headers, write_headers, s))
639 if (!HashTable_Foreach(request->headers, write_headers, s))
642 if (!http_encode_cookie_line(s, context->cookies))
645 if (!http_encode_print(s,
"\r\n"))
648 Stream_SealLength(s);
651 Stream_Free(s, TRUE);
655HttpRequest* http_request_new(
void)
657 HttpRequest* request = (HttpRequest*)calloc(1,
sizeof(HttpRequest));
661 request->headers = HashTable_New_String();
662 if (!request->headers)
664 request->TransferEncoding = TransferEncodingIdentity;
667 http_request_free(request);
671void http_request_free(HttpRequest* request)
676 free(request->AuthParam);
677 free(request->AuthScheme);
678 free(request->Authorization);
679 free(request->Method);
681 HashTable_Free(request->headers);
685static BOOL http_response_parse_header_status_line(HttpResponse* response,
const char* status_line)
688 char* separator =
nullptr;
689 char* status_code =
nullptr;
695 separator = strchr(status_line,
' ');
700 status_code = separator + 1;
701 separator = strchr(status_code,
' ');
707 const char* reason_phrase = separator + 1;
711 long val = strtol(status_code,
nullptr, 0);
713 if ((errno != 0) || (val < 0) || (val > INT16_MAX))
716 response->StatusCode = (UINT16)val;
718 free(response->ReasonPhrase);
719 response->ReasonPhrase = _strdup(reason_phrase);
722 if (!response->ReasonPhrase)
730 WLog_ERR(TAG,
"http_response_parse_header_status_line failed [%s]", status_line);
735static BOOL http_response_parse_header_field(HttpResponse* response,
const char* name,
738 WINPR_ASSERT(response);
743 if (_stricmp(name,
"Content-Length") == 0)
745 unsigned long long val = 0;
747 val = _strtoui64(value,
nullptr, 0);
749 if ((errno != 0) || (val > INT32_MAX))
752 response->ContentLength = WINPR_ASSERTING_INT_CAST(
size_t, val);
756 if (_stricmp(name,
"Content-Type") == 0)
758 free(response->ContentType);
759 response->ContentType = _strdup(value);
761 return response->ContentType !=
nullptr;
764 if (_stricmp(name,
"Transfer-Encoding") == 0)
766 if (_stricmp(value,
"identity") == 0)
767 response->TransferEncoding = TransferEncodingIdentity;
768 else if (_stricmp(value,
"chunked") == 0)
769 response->TransferEncoding = TransferEncodingChunked;
771 response->TransferEncoding = TransferEncodingUnknown;
776 if (_stricmp(name,
"Sec-WebSocket-Version") == 0)
778 free(response->SecWebsocketVersion);
779 response->SecWebsocketVersion = _strdup(value);
781 return response->SecWebsocketVersion !=
nullptr;
784 if (_stricmp(name,
"Sec-WebSocket-Accept") == 0)
786 free(response->SecWebsocketAccept);
787 response->SecWebsocketAccept = _strdup(value);
789 return response->SecWebsocketAccept !=
nullptr;
792 if (_stricmp(name,
"WWW-Authenticate") == 0)
794 const char* authScheme = value;
795 const char* authValue =
"";
796 char* separator = strchr(value,
' ');
807 authValue = separator + 1;
810 return HashTable_Insert(response->Authenticates, authScheme, authValue);
813 if (_stricmp(name,
"Set-Cookie") == 0)
815 char* separator = strchr(value,
'=');
825 const char* CookieName = value;
826 char* CookieValue = separator + 1;
828 if (*CookieValue ==
'"')
830 char* p = CookieValue;
831 while (*p !=
'"' && *p !=
'\0')
841 char* p = CookieValue;
842 while (*p !=
';' && *p !=
'\0' && *p !=
' ')
848 return HashTable_Insert(response->SetCookie, CookieName, CookieValue);
855static BOOL http_response_parse_header(HttpResponse* response)
859 char* line =
nullptr;
860 char* name =
nullptr;
861 char* colon_pos =
nullptr;
862 char* end_of_header =
nullptr;
863 char end_of_header_char = 0;
868 if (!response->lines)
871 if (!http_response_parse_header_status_line(response, response->lines[0]))
874 for (
size_t count = 1; count < response->count; count++)
876 line = response->lines[count];
888 colon_pos = strchr(line,
':');
892 if ((colon_pos ==
nullptr) || (colon_pos == line))
896 for (end_of_header = colon_pos; end_of_header != line; end_of_header--)
898 c = end_of_header[-1];
900 if (c !=
' ' && c !=
'\t' && c !=
':')
904 if (end_of_header == line)
907 end_of_header_char = *end_of_header;
908 *end_of_header =
'\0';
912 char* value = colon_pos + 1;
913 for (; *value; value++)
915 if ((*value !=
' ') && (*value !=
'\t'))
919 const int res = http_response_parse_header_field(response, name, value);
920 *end_of_header = end_of_header_char;
929 WLog_ERR(TAG,
"parsing failed");
934static void http_response_print(wLog* log, DWORD level,
const HttpResponse* response,
935 const char* file,
size_t line,
const char* fkt)
937 char buffer[64] = WINPR_C_ARRAY_INIT;
940 WINPR_ASSERT(response);
942 if (!WLog_IsLevelActive(log, level))
945 const long status = http_response_get_status_code(response);
946 WLog_PrintTextMessage(log, level, line, file, fkt,
"HTTP status: %s",
947 freerdp_http_status_string_format(status, buffer, ARRAYSIZE(buffer)));
949 if (WLog_IsLevelActive(log, WLOG_DEBUG))
951 for (
size_t i = 0; i < response->count; i++)
952 WLog_PrintTextMessage(log, WLOG_DEBUG, line, file, fkt,
"[%" PRIuz
"] %s", i,
956 if (response->ReasonPhrase)
957 WLog_PrintTextMessage(log, level, line, file, fkt,
"[reason] %s", response->ReasonPhrase);
959 if (WLog_IsLevelActive(log, WLOG_TRACE))
961 WLog_PrintTextMessage(log, WLOG_TRACE, line, file, fkt,
"[body][%" PRIuz
"] %s",
962 response->BodyLength, response->BodyContent);
966static BOOL http_use_content_length(
const char* cur)
973 if (_strnicmp(cur,
"application/rpc", 15) == 0)
975 else if (_strnicmp(cur,
"text/plain", 10) == 0)
977 else if (_strnicmp(cur,
"text/html", 9) == 0)
979 else if (_strnicmp(cur,
"application/json", 16) == 0)
1003static int print_bio_error(
const char* str,
size_t len,
void* bp)
1008 WLog_Print(log, WLOG_ERROR,
"%s", str);
1009 if (len > INT32_MAX)
1014int http_chuncked_read(BIO* bio, BYTE* pBuffer,
size_t size,
1018 int effectiveDataLen = 0;
1020 WINPR_ASSERT(pBuffer);
1021 WINPR_ASSERT(encodingContext !=
nullptr);
1022 WINPR_ASSERT(size <= INT32_MAX);
1025 switch (encodingContext->state)
1027 case ChunkStateData:
1030 (size > encodingContext->nextOffset ? encodingContext->nextOffset : size);
1035 status = BIO_read(bio, pBuffer, (
int)rd);
1037 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1039 encodingContext->nextOffset -= WINPR_ASSERTING_INT_CAST(uint32_t, status);
1040 if (encodingContext->nextOffset == 0)
1042 encodingContext->state = ChunkStateFooter;
1043 encodingContext->headerFooterPos = 0;
1045 effectiveDataLen += status;
1047 if ((
size_t)status == size)
1048 return effectiveDataLen;
1051 size -= (size_t)status;
1054 case ChunkStateFooter:
1056 char _dummy[2] = WINPR_C_ARRAY_INIT;
1057 WINPR_ASSERT(encodingContext->nextOffset == 0);
1058 WINPR_ASSERT(encodingContext->headerFooterPos < 2);
1060 status = BIO_read(bio, _dummy, (
int)(2 - encodingContext->headerFooterPos));
1063 encodingContext->headerFooterPos += (size_t)status;
1064 if (encodingContext->headerFooterPos == 2)
1066 encodingContext->state = ChunkStateLenghHeader;
1067 encodingContext->headerFooterPos = 0;
1071 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1074 case ChunkStateLenghHeader:
1076 BOOL _haveNewLine = FALSE;
1077 char* dst = &encodingContext->lenBuffer[encodingContext->headerFooterPos];
1078 WINPR_ASSERT(encodingContext->nextOffset == 0);
1079 while (encodingContext->headerFooterPos < 10 && !_haveNewLine)
1082 status = BIO_read(bio, dst, 1);
1086 _haveNewLine = TRUE;
1087 encodingContext->headerFooterPos += (size_t)status;
1091 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1097 size_t tmp = strtoul(encodingContext->lenBuffer,
nullptr, 16);
1098 if ((errno != 0) || (tmp > SIZE_MAX))
1101 encodingContext->nextOffset = 0;
1102 encodingContext->state = ChunkStateEnd;
1105 encodingContext->nextOffset = tmp;
1106 encodingContext->state = ChunkStateData;
1108 if (encodingContext->nextOffset == 0)
1110 WLog_DBG(TAG,
"chunked encoding end of stream received");
1111 encodingContext->headerFooterPos = 0;
1112 encodingContext->state = ChunkStateEnd;
1113 return (effectiveDataLen > 0 ? effectiveDataLen : 0);
1124#define sleep_or_timeout(tls, startMS, timeoutMS) \
1125 sleep_or_timeout_((tls), (startMS), (timeoutMS), __FILE__, __func__, __LINE__)
1126static BOOL sleep_or_timeout_(rdpTls* tls, UINT64 startMS, UINT32 timeoutMS,
const char* file,
1127 const char* fkt,
size_t line)
1132 const UINT64 nowMS = GetTickCount64();
1133 if (nowMS - startMS > timeoutMS)
1135 DWORD level = WLOG_ERROR;
1136 wLog* log = WLog_Get(TAG);
1137 if (WLog_IsLevelActive(log, level))
1138 WLog_PrintTextMessage(log, level, line, file, fkt,
"timeout [%" PRIu32
"ms] exceeded",
1142 if (!BIO_should_retry(tls->bio))
1144 DWORD level = WLOG_ERROR;
1145 wLog* log = WLog_Get(TAG);
1146 if (WLog_IsLevelActive(log, level))
1148 WLog_PrintTextMessage(log, level, line, file, fkt,
"Retries exceeded");
1149 ERR_print_errors_cb(print_bio_error, log);
1153 if (freerdp_shall_disconnect_context(tls->context))
1159static SSIZE_T http_response_recv_line(rdpTls* tls, HttpResponse* response)
1162 WINPR_ASSERT(response);
1164 SSIZE_T payloadOffset = -1;
1165 const UINT32 timeoutMS =
1167 const UINT64 startMS = GetTickCount64();
1168 while (payloadOffset <= 0)
1170 size_t bodyLength = 0;
1171 size_t position = 0;
1174 char* end =
nullptr;
1178 status = BIO_read(tls->bio, Stream_Pointer(response->data), 1);
1181 if (sleep_or_timeout(tls, startMS, timeoutMS))
1186#ifdef FREERDP_HAVE_VALGRIND_MEMCHECK_H
1187 VALGRIND_MAKE_MEM_DEFINED(Stream_Pointer(response->data), status);
1189 Stream_Seek(response->data, (
size_t)status);
1191 if (!Stream_EnsureRemainingCapacity(response->data, 1024))
1194 position = Stream_GetPosition(response->data);
1198 else if (position > RESPONSE_SIZE_LIMIT)
1200 WLog_ERR(TAG,
"Request header too large! (%" PRIuz
" bytes) Aborting!", bodyLength);
1206 s = (position > 8) ? 8 : position;
1207 end = (
char*)Stream_Pointer(response->data) - s;
1209 if (string_strnstr(end,
"\r\n\r\n", s) !=
nullptr)
1210 payloadOffset = WINPR_ASSERTING_INT_CAST(SSIZE_T, Stream_GetPosition(response->data));
1214 return payloadOffset;
1217static BOOL http_response_recv_body(rdpTls* tls, HttpResponse* response, BOOL readContentLength,
1218 size_t payloadOffset,
size_t bodyLength)
1223 WINPR_ASSERT(response);
1225 const UINT64 startMS = GetTickCount64();
1226 const UINT32 timeoutMS =
1229 if ((response->TransferEncoding == TransferEncodingChunked) && readContentLength)
1232 ctx.state = ChunkStateLenghHeader;
1234 ctx.headerFooterPos = 0;
1238 if (!Stream_EnsureRemainingCapacity(response->data, 2048))
1241 int status = http_chuncked_read(tls->bio, Stream_Pointer(response->data),
1242 Stream_GetRemainingCapacity(response->data), &ctx);
1245 if (sleep_or_timeout(tls, startMS, timeoutMS))
1250 Stream_Seek(response->data, (
size_t)status);
1253 }
while (ctx.state != ChunkStateEnd);
1254 response->BodyLength = WINPR_ASSERTING_INT_CAST(uint32_t, full_len);
1255 if (response->BodyLength > 0)
1256 response->BodyContent = &(Stream_BufferAs(response->data,
char))[payloadOffset];
1260 while (response->BodyLength < bodyLength)
1264 if (!Stream_EnsureRemainingCapacity(response->data, bodyLength - response->BodyLength))
1268 size_t diff = bodyLength - response->BodyLength;
1269 if (diff > INT32_MAX)
1271 status = BIO_read(tls->bio, Stream_Pointer(response->data), (
int)diff);
1275 if (sleep_or_timeout(tls, startMS, timeoutMS))
1280 Stream_Seek(response->data, (
size_t)status);
1281 response->BodyLength += (
unsigned long)status;
1283 if (response->BodyLength > RESPONSE_SIZE_LIMIT)
1285 WLog_ERR(TAG,
"Request body too large! (%" PRIuz
" bytes) Aborting!",
1286 response->BodyLength);
1291 if (response->BodyLength > 0)
1292 response->BodyContent = &(Stream_BufferAs(response->data,
char))[payloadOffset];
1294 if (bodyLength != response->BodyLength)
1296 WLog_WARN(TAG,
"%s unexpected body length: actual: %" PRIuz
", expected: %" PRIuz,
1297 response->ContentType, response->BodyLength, bodyLength);
1300 response->BodyLength = MIN(bodyLength, response->BodyLength);
1304 if (!Stream_EnsureRemainingCapacity(response->data,
sizeof(UINT16)))
1306 Stream_Write_UINT16(response->data, 0);
1314static void clear_lines(HttpResponse* response)
1316 WINPR_ASSERT(response);
1318 for (
size_t x = 0; x < response->count; x++)
1320 WINPR_ASSERT(response->lines);
1321 char* line = response->lines[x];
1325 free((
void*)response->lines);
1326 response->lines =
nullptr;
1327 response->count = 0;
1330HttpResponse* http_response_recv(rdpTls* tls, BOOL readContentLength)
1332 size_t bodyLength = 0;
1333 HttpResponse* response = http_response_new();
1338 response->ContentLength = 0;
1340 const SSIZE_T payloadOffset = http_response_recv_line(tls, response);
1341 if (payloadOffset < 0)
1347 char* buffer = Stream_BufferAs(response->data,
char);
1348 const char* line = Stream_BufferAs(response->data,
char);
1349 char* context =
nullptr;
1351 while ((line = string_strnstr(line,
"\r\n",
1352 WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset) -
1353 WINPR_ASSERTING_INT_CAST(
size_t, (line - buffer)) - 2UL)))
1359 clear_lines(response);
1360 response->count = count;
1364 response->lines = (
char**)calloc(response->count,
sizeof(
char*));
1366 if (!response->lines)
1370 buffer[payloadOffset - 1] =
'\0';
1371 buffer[payloadOffset - 2] =
'\0';
1373 line = strtok_s(buffer,
"\r\n", &context);
1375 while (line && (response->count > count))
1377 response->lines[count] = _strdup(line);
1378 if (!response->lines[count])
1380 line = strtok_s(
nullptr,
"\r\n", &context);
1384 if (!http_response_parse_header(response))
1387 response->BodyLength =
1388 Stream_GetPosition(response->data) - WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset);
1390 WINPR_ASSERT(response->BodyLength == 0);
1391 bodyLength = response->BodyLength;
1393 if (readContentLength && (response->ContentLength > 0))
1395 const char* cur = response->ContentType;
1397 while (cur !=
nullptr)
1399 if (http_use_content_length(cur))
1401 if (response->ContentLength < RESPONSE_SIZE_LIMIT)
1402 bodyLength = response->ContentLength;
1407 readContentLength = FALSE;
1409 cur = strchr(cur,
';');
1413 if (bodyLength > RESPONSE_SIZE_LIMIT)
1415 WLog_ERR(TAG,
"Expected request body too large! (%" PRIuz
" bytes) Aborting!",
1421 if (!http_response_recv_body(tls, response, readContentLength,
1422 WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset), bodyLength))
1425 Stream_SealLength(response->data);
1428 if (!Stream_EnsureRemainingCapacity(response->data, 2))
1430 Stream_Write_UINT16(response->data, 0);
1434 WLog_ERR(TAG,
"No response");
1435 http_response_free(response);
1439const char* http_response_get_body(
const HttpResponse* response)
1444 return response->BodyContent;
1447wHashTable* HashTable_New_String(
void)
1449 wHashTable* table = HashTable_New(FALSE);
1453 if (!HashTable_SetupForStringData(table, TRUE))
1455 HashTable_Free(table);
1458 HashTable_KeyObject(table)->
fnObjectEquals = strings_equals_nocase;
1459 HashTable_ValueObject(table)->
fnObjectEquals = strings_equals_nocase;
1463HttpResponse* http_response_new(
void)
1465 HttpResponse* response = (HttpResponse*)calloc(1,
sizeof(HttpResponse));
1470 response->Authenticates = HashTable_New_String();
1472 if (!response->Authenticates)
1475 response->SetCookie = HashTable_New_String();
1477 if (!response->SetCookie)
1480 response->data = Stream_New(
nullptr, 2048);
1482 if (!response->data)
1485 response->TransferEncoding = TransferEncodingIdentity;
1488 WINPR_PRAGMA_DIAG_PUSH
1489 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
1490 http_response_free(response);
1491 WINPR_PRAGMA_DIAG_POP
1495void http_response_free(HttpResponse* response)
1500 clear_lines(response);
1501 free(response->ReasonPhrase);
1502 free(response->ContentType);
1503 free(response->SecWebsocketAccept);
1504 free(response->SecWebsocketVersion);
1505 HashTable_Free(response->Authenticates);
1506 HashTable_Free(response->SetCookie);
1507 Stream_Free(response->data, TRUE);
1511const char* http_request_get_uri(HttpRequest* request)
1516 return request->URI;
1519SSIZE_T http_request_get_content_length(HttpRequest* request)
1524 return (SSIZE_T)request->ContentLength;
1527BOOL http_request_set_content_length(HttpRequest* request,
size_t length)
1532 request->ContentLength = length;
1536UINT16 http_response_get_status_code(
const HttpResponse* response)
1538 WINPR_ASSERT(response);
1540 return response->StatusCode;
1543size_t http_response_get_body_length(
const HttpResponse* response)
1545 WINPR_ASSERT(response);
1547 return response->BodyLength;
1550const char* http_response_get_auth_token(
const HttpResponse* response,
const char* method)
1552 if (!response || !method)
1555 return HashTable_GetItemValue(response->Authenticates, method);
1558const char* http_response_get_setcookie(
const HttpResponse* response,
const char* cookie)
1560 if (!response || !cookie)
1563 return HashTable_GetItemValue(response->SetCookie, cookie);
1566TRANSFER_ENCODING http_response_get_transfer_encoding(
const HttpResponse* response)
1569 return TransferEncodingUnknown;
1571 return response->TransferEncoding;
1574BOOL http_response_is_websocket(
const HttpContext* http,
const HttpResponse* response)
1576 BOOL isWebsocket = FALSE;
1577 WINPR_DIGEST_CTX* sha1 =
nullptr;
1578 char* base64accept =
nullptr;
1579 BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH];
1581 if (!http || !response)
1584 if (!http->websocketUpgrade || response->StatusCode != HTTP_STATUS_SWITCH_PROTOCOLS)
1587 if (response->SecWebsocketVersion && _stricmp(response->SecWebsocketVersion,
"13") != 0)
1590 if (!response->SecWebsocketAccept)
1595 sha1 = winpr_Digest_New();
1599 if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1))
1602 if (!winpr_Digest_Update(sha1, (BYTE*)http->SecWebsocketKey, strlen(http->SecWebsocketKey)))
1604 if (!winpr_Digest_Update(sha1, (
const BYTE*)WEBSOCKET_MAGIC_GUID, strlen(WEBSOCKET_MAGIC_GUID)))
1607 if (!winpr_Digest_Final(sha1, sha1_digest,
sizeof(sha1_digest)))
1610 base64accept = crypto_base64_encode(sha1_digest, WINPR_SHA1_DIGEST_LENGTH);
1614 if (_stricmp(response->SecWebsocketAccept, base64accept) != 0)
1616 WLog_WARN(TAG,
"Webserver gave Websocket Upgrade response but sanity check failed");
1621 winpr_Digest_Free(sha1);
1626void http_response_log_error_status_(wLog* log, DWORD level,
const HttpResponse* response,
1627 const char* file,
size_t line,
const char* fkt)
1630 WINPR_ASSERT(response);
1632 if (!WLog_IsLevelActive(log, level))
1635 char buffer[64] = WINPR_C_ARRAY_INIT;
1636 const UINT16 status = http_response_get_status_code(response);
1637 WLog_PrintTextMessage(log, level, line, file, fkt,
"Unexpected HTTP status: %s",
1638 freerdp_http_status_string_format(status, buffer, ARRAYSIZE(buffer)));
1639 http_response_print(log, level, response, file, line, fkt);
1642static BOOL extract_cookie(
const void* pkey,
void* pvalue,
void* arg)
1644 const char* key = pkey;
1645 const char* value = pvalue;
1646 HttpContext* context = arg;
1650 WINPR_ASSERT(value);
1652 return http_context_set_cookie(context, key, value);
1655BOOL http_response_extract_cookies(
const HttpResponse* response, HttpContext* context)
1657 WINPR_ASSERT(response);
1658 WINPR_ASSERT(context);
1660 return HashTable_Foreach(response->SetCookie, extract_cookie, context);
1663FREERDP_LOCAL BOOL http_context_set_header(HttpContext* context,
const char* key,
const char* value,
1666 WINPR_ASSERT(context);
1667 va_list ap = WINPR_C_ARRAY_INIT;
1668 va_start(ap, value);
1669 const BOOL rc = http_context_set_header_va(context, key, value, ap);
1674BOOL http_request_set_header(HttpRequest* request,
const char* key,
const char* value, ...)
1676 WINPR_ASSERT(request);
1679 va_list ap = WINPR_C_ARRAY_INIT;
1680 va_start(ap, value);
1681 winpr_vasprintf(&v, &vlen, value, ap);
1683 const BOOL rc = HashTable_Insert(request->headers, key, v);
1688BOOL http_context_set_header_va(HttpContext* context,
const char* key,
const char* value,
1693 winpr_vasprintf(&v, &vlen, value, ap);
1694 const BOOL rc = HashTable_Insert(context->headers, key, v);
WINPR_ATTR_NODISCARD FREERDP_API UINT32 freerdp_settings_get_uint32(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id)
Returns a UINT32 settings value.
This struct contains function pointer to initialize/free objects.
OBJECT_FREE_FN fnObjectFree
WINPR_ATTR_NODISCARD OBJECT_EQUALS_FN fnObjectEquals
WINPR_ATTR_NODISCARD OBJECT_NEW_FN fnObjectNew