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);
165 WINPR_PRAGMA_DIAG_PUSH
166 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
167 http_context_free(context);
168 WINPR_PRAGMA_DIAG_POP
172BOOL http_context_set_method(HttpContext* context,
const char* Method)
174 if (!context || !Method)
177 free(context->Method);
178 context->Method = _strdup(Method);
180 return (context->Method !=
nullptr);
183BOOL http_request_set_content_type(HttpRequest* request,
const char* ContentType)
185 if (!request || !ContentType)
188 return http_request_set_header(request,
"Content-Type",
"%s", ContentType);
191const char* http_context_get_uri(HttpContext* context)
199BOOL http_context_set_uri(HttpContext* context,
const char* URI)
201 if (!context || !URI)
205 context->URI = _strdup(URI);
207 return (context->URI !=
nullptr);
210BOOL http_context_set_user_agent(HttpContext* context,
const char* UserAgent)
212 if (!context || !UserAgent)
215 return http_context_set_header(context,
"User-Agent",
"%s", UserAgent);
218BOOL http_context_set_x_ms_user_agent(HttpContext* context,
const char* X_MS_UserAgent)
220 if (!context || !X_MS_UserAgent)
223 return http_context_set_header(context,
"X-MS-User-Agent",
"%s", X_MS_UserAgent);
226BOOL http_context_set_host(HttpContext* context,
const char* Host)
228 if (!context || !Host)
231 return http_context_set_header(context,
"Host",
"%s", Host);
234BOOL http_context_set_accept(HttpContext* context,
const char* Accept)
236 if (!context || !Accept)
239 return http_context_set_header(context,
"Accept",
"%s", Accept);
242BOOL http_context_set_cache_control(HttpContext* context,
const char* CacheControl)
244 if (!context || !CacheControl)
247 return http_context_set_header(context,
"Cache-Control",
"%s", CacheControl);
250BOOL http_context_set_connection(HttpContext* context,
const char* Connection)
252 if (!context || !Connection)
255 free(context->Connection);
256 context->Connection = _strdup(Connection);
258 return (context->Connection !=
nullptr);
261WINPR_ATTR_FORMAT_ARG(2, 0)
262static BOOL list_append(HttpContext* context, WINPR_FORMAT_ARG const
char* str, va_list ap)
265 va_list vat = WINPR_C_ARRAY_INIT;
266 char* Pragma =
nullptr;
267 size_t PragmaSize = 0;
270 const int size = winpr_vasprintf(&Pragma, &PragmaSize, str, ap);
277 char* sstr =
nullptr;
281 winpr_asprintf(&sstr, &slen,
"%s, %s", context->Pragma, Pragma);
288 free(context->Pragma);
289 context->Pragma = sstr;
299WINPR_ATTR_FORMAT_ARG(2, 3)
300BOOL http_context_set_pragma(HttpContext* context, WINPR_FORMAT_ARG const
char* Pragma, ...)
302 if (!context || !Pragma)
305 free(context->Pragma);
306 context->Pragma =
nullptr;
308 va_list ap = WINPR_C_ARRAY_INIT;
309 va_start(ap, Pragma);
310 return list_append(context, Pragma, ap);
313WINPR_ATTR_FORMAT_ARG(2, 3)
314BOOL http_context_append_pragma(HttpContext* context, const
char* Pragma, ...)
316 if (!context || !Pragma)
319 va_list ap = WINPR_C_ARRAY_INIT;
320 va_start(ap, Pragma);
321 return list_append(context, Pragma, ap);
324static char* guid2str(
const GUID* guid,
char* buffer,
size_t len)
328 RPC_CSTR strguid =
nullptr;
330 RPC_STATUS rpcStatus = UuidToStringA(guid, &strguid);
332 if (rpcStatus != RPC_S_OK)
335 (void)sprintf_s(buffer, len,
"{%s}", strguid);
336 RpcStringFreeA(&strguid);
340BOOL http_context_set_rdg_connection_id(HttpContext* context,
const GUID* RdgConnectionId)
342 if (!context || !RdgConnectionId)
345 char buffer[64] = WINPR_C_ARRAY_INIT;
346 return http_context_set_header(context,
"RDG-Connection-Id",
"%s",
347 guid2str(RdgConnectionId, buffer,
sizeof(buffer)));
350BOOL http_context_set_rdg_correlation_id(HttpContext* context,
const GUID* RdgCorrelationId)
352 if (!context || !RdgCorrelationId)
355 char buffer[64] = WINPR_C_ARRAY_INIT;
356 return http_context_set_header(context,
"RDG-Correlation-Id",
"%s",
357 guid2str(RdgCorrelationId, buffer,
sizeof(buffer)));
360BOOL http_context_enable_websocket_upgrade(HttpContext* context, BOOL enable)
362 WINPR_ASSERT(context);
366 GUID key = WINPR_C_ARRAY_INIT;
367 if (RPC_S_OK != UuidCreate(&key))
370 free(context->SecWebsocketKey);
371 context->SecWebsocketKey = crypto_base64_encode((BYTE*)&key,
sizeof(key));
372 if (!context->SecWebsocketKey)
376 context->websocketUpgrade = enable;
380BOOL http_context_is_websocket_upgrade_enabled(HttpContext* context)
382 return context->websocketUpgrade;
385BOOL http_context_set_rdg_auth_scheme(HttpContext* context,
const char* RdgAuthScheme)
387 if (!context || !RdgAuthScheme)
390 return http_context_set_header(context,
"RDG-Auth-Scheme",
"%s", RdgAuthScheme);
393BOOL http_context_set_cookie(HttpContext* context,
const char* CookieName,
const char* CookieValue)
395 if (!context || !CookieName || !CookieValue)
397 if (ListDictionary_Contains(context->cookies, CookieName))
399 if (!ListDictionary_SetItemValue(context->cookies, CookieName, CookieValue))
404 if (!ListDictionary_Add(context->cookies, CookieName, CookieValue))
410void http_context_free(HttpContext* context)
414 free(context->SecWebsocketKey);
416 free(context->Method);
417 free(context->Connection);
418 free(context->Pragma);
419 HashTable_Free(context->headers);
420 ListDictionary_Free(context->cookies);
425BOOL http_request_set_method(HttpRequest* request,
const char* Method)
427 if (!request || !Method)
430 free(request->Method);
431 request->Method = _strdup(Method);
433 return (request->Method !=
nullptr);
436BOOL http_request_set_uri(HttpRequest* request,
const char* URI)
438 if (!request || !URI)
442 request->URI = _strdup(URI);
444 return (request->URI !=
nullptr);
447BOOL http_request_set_auth_scheme(HttpRequest* request,
const char* AuthScheme)
449 if (!request || !AuthScheme)
452 free(request->AuthScheme);
453 request->AuthScheme = _strdup(AuthScheme);
455 return (request->AuthScheme !=
nullptr);
458BOOL http_request_set_auth_param(HttpRequest* request,
const char* AuthParam)
460 if (!request || !AuthParam)
463 free(request->AuthParam);
464 request->AuthParam = _strdup(AuthParam);
466 return (request->AuthParam !=
nullptr);
469BOOL http_request_set_transfer_encoding(HttpRequest* request, TRANSFER_ENCODING TransferEncoding)
471 if (!request || TransferEncoding == TransferEncodingUnknown)
474 request->TransferEncoding = TransferEncoding;
479WINPR_ATTR_FORMAT_ARG(2, 3)
480static BOOL http_encode_print(
wStream* s, WINPR_FORMAT_ARG const
char* fmt, ...)
483 va_list ap = WINPR_C_ARRAY_INIT;
491 length = vsnprintf(
nullptr, 0, fmt, ap) + 1;
494 if (!Stream_EnsureRemainingCapacity(s, (
size_t)length))
497 str = (
char*)Stream_Pointer(s);
499 used = vsnprintf(str, (
size_t)length, fmt, ap);
503 if ((used + 1) != length)
506 Stream_Seek(s, (
size_t)used);
510static BOOL http_encode_body_line(
wStream* s,
const char* param,
const char* value)
512 if (!s || !param || !value)
515 return http_encode_print(s,
"%s: %s\r\n", param, value);
518static BOOL http_encode_content_length_line(
wStream* s,
size_t ContentLength)
520 return http_encode_print(s,
"Content-Length: %" PRIuz
"\r\n", ContentLength);
523static BOOL http_encode_header_line(
wStream* s,
const char* Method,
const char* URI)
525 if (!s || !Method || !URI)
528 return http_encode_print(s,
"%s %s HTTP/1.1\r\n", Method, URI);
531static BOOL http_encode_authorization_line(
wStream* s,
const char* AuthScheme,
532 const char* AuthParam)
534 if (!s || !AuthScheme || !AuthParam)
537 return http_encode_print(s,
"Authorization: %s %s\r\n", AuthScheme, AuthParam);
540static BOOL http_encode_cookie_line(
wStream* s, wListDictionary* cookies)
542 ULONG_PTR* keys =
nullptr;
548 ListDictionary_Lock(cookies);
549 const size_t count = ListDictionary_GetKeys(cookies, &keys);
554 status = http_encode_print(s,
"Cookie: ");
558 for (
size_t x = 0; status && x < count; x++)
560 char* cur = (
char*)ListDictionary_GetItemValue(cookies, (
void*)keys[x]);
568 status = http_encode_print(s,
"; ");
572 status = http_encode_print(s,
"%s=%s", (
char*)keys[x], cur);
575 status = http_encode_print(s,
"\r\n");
578 ListDictionary_Unlock(cookies);
582static BOOL write_headers(
const void* pkey,
void* pvalue,
void* arg)
584 const char* key = pkey;
585 const char* value = pvalue;
592 return http_encode_body_line(s, key, value);
595wStream* http_request_write(HttpContext* context, HttpRequest* request)
599 if (!context || !request)
602 s = Stream_New(
nullptr, 1024);
607 if (!http_encode_header_line(s, request->Method, request->URI) ||
609 !http_encode_body_line(s,
"Pragma", context->Pragma))
612 if (!context->websocketUpgrade)
614 if (!http_encode_body_line(s,
"Connection", context->Connection))
619 if (!http_encode_body_line(s,
"Connection",
"Upgrade") ||
620 !http_encode_body_line(s,
"Upgrade",
"websocket") ||
621 !http_encode_body_line(s,
"Sec-Websocket-Version",
"13") ||
622 !http_encode_body_line(s,
"Sec-Websocket-Key", context->SecWebsocketKey))
626 if (request->TransferEncoding != TransferEncodingIdentity)
628 if (request->TransferEncoding == TransferEncodingChunked)
630 if (!http_encode_body_line(s,
"Transfer-Encoding",
"chunked"))
638 if (!http_encode_content_length_line(s, request->ContentLength))
642 if (!utils_str_is_empty(request->Authorization))
644 if (!http_encode_body_line(s,
"Authorization", request->Authorization))
647 else if (!utils_str_is_empty(request->AuthScheme) && !utils_str_is_empty(request->AuthParam))
649 if (!http_encode_authorization_line(s, request->AuthScheme, request->AuthParam))
653 if (!HashTable_Foreach(context->headers, write_headers, s))
656 if (!HashTable_Foreach(request->headers, write_headers, s))
659 if (!http_encode_cookie_line(s, context->cookies))
662 if (!http_encode_print(s,
"\r\n"))
665 Stream_SealLength(s);
668 Stream_Free(s, TRUE);
672HttpRequest* http_request_new(
void)
674 HttpRequest* request = (HttpRequest*)calloc(1,
sizeof(HttpRequest));
678 request->headers = HashTable_New_String();
679 if (!request->headers)
681 request->TransferEncoding = TransferEncodingIdentity;
684 http_request_free(request);
688void http_request_free(HttpRequest* request)
693 free(request->AuthParam);
694 free(request->AuthScheme);
695 free(request->Authorization);
696 free(request->Method);
698 HashTable_Free(request->headers);
702static BOOL http_response_parse_header_status_line(HttpResponse* response,
const char* status_line)
705 char* separator =
nullptr;
706 char* status_code =
nullptr;
712 separator = strchr(status_line,
' ');
717 status_code = separator + 1;
718 separator = strchr(status_code,
' ');
724 const char* reason_phrase = separator + 1;
728 long val = strtol(status_code,
nullptr, 0);
730 if ((errno != 0) || (val < 0) || (val > INT16_MAX))
733 response->StatusCode = (UINT16)val;
735 free(response->ReasonPhrase);
736 response->ReasonPhrase = _strdup(reason_phrase);
739 if (!response->ReasonPhrase)
747 WLog_ERR(TAG,
"http_response_parse_header_status_line failed [%s]", status_line);
752static BOOL http_response_parse_header_field(HttpResponse* response,
const char* name,
755 WINPR_ASSERT(response);
760 if (_stricmp(name,
"Content-Length") == 0)
762 unsigned long long val = 0;
764 val = _strtoui64(value,
nullptr, 0);
766 if ((errno != 0) || (val > INT32_MAX))
769 response->ContentLength = WINPR_ASSERTING_INT_CAST(
size_t, val);
773 if (_stricmp(name,
"Content-Type") == 0)
775 free(response->ContentType);
776 response->ContentType = _strdup(value);
778 return response->ContentType !=
nullptr;
781 if (_stricmp(name,
"Transfer-Encoding") == 0)
783 if (_stricmp(value,
"identity") == 0)
784 response->TransferEncoding = TransferEncodingIdentity;
785 else if (_stricmp(value,
"chunked") == 0)
786 response->TransferEncoding = TransferEncodingChunked;
788 response->TransferEncoding = TransferEncodingUnknown;
793 if (_stricmp(name,
"Sec-WebSocket-Version") == 0)
795 free(response->SecWebsocketVersion);
796 response->SecWebsocketVersion = _strdup(value);
798 return response->SecWebsocketVersion !=
nullptr;
801 if (_stricmp(name,
"Sec-WebSocket-Accept") == 0)
803 free(response->SecWebsocketAccept);
804 response->SecWebsocketAccept = _strdup(value);
806 return response->SecWebsocketAccept !=
nullptr;
809 if (_stricmp(name,
"WWW-Authenticate") == 0)
811 const char* authScheme = value;
812 const char* authValue =
"";
813 char* separator = strchr(value,
' ');
824 authValue = separator + 1;
827 return HashTable_Insert(response->Authenticates, authScheme, authValue);
830 if (_stricmp(name,
"Set-Cookie") == 0)
832 char* separator = strchr(value,
'=');
842 const char* CookieName = value;
843 char* CookieValue = separator + 1;
845 if (*CookieValue ==
'"')
847 char* p = CookieValue;
848 while (*p !=
'"' && *p !=
'\0')
858 char* p = CookieValue;
859 while (*p !=
';' && *p !=
'\0' && *p !=
' ')
865 return HashTable_Insert(response->SetCookie, CookieName, CookieValue);
872static BOOL http_response_parse_header(HttpResponse* response)
876 char* line =
nullptr;
877 char* name =
nullptr;
878 char* colon_pos =
nullptr;
879 char* end_of_header =
nullptr;
880 char end_of_header_char = 0;
885 if (!response->lines)
888 if (!http_response_parse_header_status_line(response, response->lines[0]))
891 for (
size_t count = 1; count < response->count; count++)
893 line = response->lines[count];
905 colon_pos = strchr(line,
':');
909 if ((colon_pos ==
nullptr) || (colon_pos == line))
913 for (end_of_header = colon_pos; end_of_header != line; end_of_header--)
915 c = end_of_header[-1];
917 if (c !=
' ' && c !=
'\t' && c !=
':')
921 if (end_of_header == line)
924 end_of_header_char = *end_of_header;
925 *end_of_header =
'\0';
929 char* value = colon_pos + 1;
930 for (; *value; value++)
932 if ((*value !=
' ') && (*value !=
'\t'))
936 const int res = http_response_parse_header_field(response, name, value);
937 *end_of_header = end_of_header_char;
946 WLog_ERR(TAG,
"parsing failed");
951static void http_response_print(wLog* log, DWORD level,
const HttpResponse* response,
952 const char* file,
size_t line,
const char* fkt)
954 char buffer[64] = WINPR_C_ARRAY_INIT;
957 WINPR_ASSERT(response);
959 if (!WLog_IsLevelActive(log, level))
962 const long status = http_response_get_status_code(response);
963 WLog_PrintTextMessage(log, level, line, file, fkt,
"HTTP status: %s",
964 freerdp_http_status_string_format(status, buffer, ARRAYSIZE(buffer)));
966 if (WLog_IsLevelActive(log, WLOG_DEBUG))
968 for (
size_t i = 0; i < response->count; i++)
969 WLog_PrintTextMessage(log, WLOG_DEBUG, line, file, fkt,
"[%" PRIuz
"] %s", i,
973 if (response->ReasonPhrase)
974 WLog_PrintTextMessage(log, level, line, file, fkt,
"[reason] %s", response->ReasonPhrase);
976 if (WLog_IsLevelActive(log, WLOG_TRACE))
978 WLog_PrintTextMessage(log, WLOG_TRACE, line, file, fkt,
"[body][%" PRIuz
"] %s",
979 response->BodyLength, response->BodyContent);
983static BOOL http_use_content_length(
const char* cur)
990 if (_strnicmp(cur,
"application/rpc", 15) == 0)
992 else if (_strnicmp(cur,
"text/plain", 10) == 0)
994 else if (_strnicmp(cur,
"text/html", 9) == 0)
996 else if (_strnicmp(cur,
"application/json", 16) == 0)
1001 char end = cur[pos];
1020static int print_bio_error(
const char* str,
size_t len,
void* bp)
1025 WLog_Print(log, WLOG_ERROR,
"%s", str);
1026 if (len > INT32_MAX)
1031int http_chuncked_read(BIO* bio, BYTE* pBuffer,
size_t size,
1035 int effectiveDataLen = 0;
1037 WINPR_ASSERT(pBuffer);
1038 WINPR_ASSERT(encodingContext !=
nullptr);
1039 WINPR_ASSERT(size <= INT32_MAX);
1042 switch (encodingContext->state)
1044 case ChunkStateData:
1047 (size > encodingContext->nextOffset ? encodingContext->nextOffset : size);
1052 status = BIO_read(bio, pBuffer, (
int)rd);
1054 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1056 encodingContext->nextOffset -= WINPR_ASSERTING_INT_CAST(uint32_t, status);
1057 if (encodingContext->nextOffset == 0)
1059 encodingContext->state = ChunkStateFooter;
1060 encodingContext->headerFooterPos = 0;
1062 effectiveDataLen += status;
1064 if ((
size_t)status == size)
1065 return effectiveDataLen;
1068 size -= (size_t)status;
1071 case ChunkStateFooter:
1073 char _dummy[2] = WINPR_C_ARRAY_INIT;
1074 WINPR_ASSERT(encodingContext->nextOffset == 0);
1075 WINPR_ASSERT(encodingContext->headerFooterPos < 2);
1077 status = BIO_read(bio, _dummy, (
int)(2 - encodingContext->headerFooterPos));
1080 encodingContext->headerFooterPos += (size_t)status;
1081 if (encodingContext->headerFooterPos == 2)
1083 encodingContext->state = ChunkStateLenghHeader;
1084 encodingContext->headerFooterPos = 0;
1088 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1091 case ChunkStateLenghHeader:
1093 BOOL _haveNewLine = FALSE;
1094 char* dst = &encodingContext->lenBuffer[encodingContext->headerFooterPos];
1095 WINPR_ASSERT(encodingContext->nextOffset == 0);
1096 while (encodingContext->headerFooterPos < 10 && !_haveNewLine)
1099 status = BIO_read(bio, dst, 1);
1103 _haveNewLine = TRUE;
1104 encodingContext->headerFooterPos += (size_t)status;
1108 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1114 size_t tmp = strtoul(encodingContext->lenBuffer,
nullptr, 16);
1115 if ((errno != 0) || (tmp > SIZE_MAX))
1118 encodingContext->nextOffset = 0;
1119 encodingContext->state = ChunkStateEnd;
1122 encodingContext->nextOffset = tmp;
1123 encodingContext->state = ChunkStateData;
1125 if (encodingContext->nextOffset == 0)
1127 WLog_DBG(TAG,
"chunked encoding end of stream received");
1128 encodingContext->headerFooterPos = 0;
1129 encodingContext->state = ChunkStateEnd;
1130 return (effectiveDataLen > 0 ? effectiveDataLen : 0);
1141#define sleep_or_timeout(tls, startMS, timeoutMS) \
1142 sleep_or_timeout_((tls), (startMS), (timeoutMS), __FILE__, __func__, __LINE__)
1143static BOOL sleep_or_timeout_(rdpTls* tls, UINT64 startMS, UINT32 timeoutMS,
const char* file,
1144 const char* fkt,
size_t line)
1149 const UINT64 nowMS = GetTickCount64();
1150 if (nowMS - startMS > timeoutMS)
1152 DWORD level = WLOG_ERROR;
1153 wLog* log = WLog_Get(TAG);
1154 if (WLog_IsLevelActive(log, level))
1155 WLog_PrintTextMessage(log, level, line, file, fkt,
"timeout [%" PRIu32
"ms] exceeded",
1159 if (!BIO_should_retry(tls->bio))
1161 DWORD level = WLOG_ERROR;
1162 wLog* log = WLog_Get(TAG);
1163 if (WLog_IsLevelActive(log, level))
1165 WLog_PrintTextMessage(log, level, line, file, fkt,
"Retries exceeded");
1166 ERR_print_errors_cb(print_bio_error, log);
1170 if (freerdp_shall_disconnect_context(tls->context))
1176static SSIZE_T http_response_recv_line(rdpTls* tls, HttpResponse* response)
1179 WINPR_ASSERT(response);
1181 SSIZE_T payloadOffset = -1;
1182 const UINT32 timeoutMS =
1184 const UINT64 startMS = GetTickCount64();
1185 while (payloadOffset <= 0)
1187 size_t bodyLength = 0;
1188 size_t position = 0;
1191 char* end =
nullptr;
1195 status = BIO_read(tls->bio, Stream_Pointer(response->data), 1);
1198 if (sleep_or_timeout(tls, startMS, timeoutMS))
1203#ifdef FREERDP_HAVE_VALGRIND_MEMCHECK_H
1204 VALGRIND_MAKE_MEM_DEFINED(Stream_Pointer(response->data), status);
1206 Stream_Seek(response->data, (
size_t)status);
1208 if (!Stream_EnsureRemainingCapacity(response->data, 1024))
1211 position = Stream_GetPosition(response->data);
1215 else if (position > RESPONSE_SIZE_LIMIT)
1217 WLog_ERR(TAG,
"Request header too large! (%" PRIuz
" bytes) Aborting!", bodyLength);
1223 s = (position > 8) ? 8 : position;
1224 end = (
char*)Stream_Pointer(response->data) - s;
1226 if (string_strnstr(end,
"\r\n\r\n", s) !=
nullptr)
1227 payloadOffset = WINPR_ASSERTING_INT_CAST(SSIZE_T, Stream_GetPosition(response->data));
1231 return payloadOffset;
1234static BOOL http_response_recv_body(rdpTls* tls, HttpResponse* response, BOOL readContentLength,
1235 size_t payloadOffset,
size_t bodyLength)
1240 WINPR_ASSERT(response);
1242 const UINT64 startMS = GetTickCount64();
1243 const UINT32 timeoutMS =
1246 if ((response->TransferEncoding == TransferEncodingChunked) && readContentLength)
1249 ctx.state = ChunkStateLenghHeader;
1251 ctx.headerFooterPos = 0;
1255 if (!Stream_EnsureRemainingCapacity(response->data, 2048))
1258 int status = http_chuncked_read(tls->bio, Stream_Pointer(response->data),
1259 Stream_GetRemainingCapacity(response->data), &ctx);
1262 if (sleep_or_timeout(tls, startMS, timeoutMS))
1267 Stream_Seek(response->data, (
size_t)status);
1270 }
while (ctx.state != ChunkStateEnd);
1271 response->BodyLength = WINPR_ASSERTING_INT_CAST(uint32_t, full_len);
1272 if (response->BodyLength > 0)
1273 response->BodyContent = &(Stream_BufferAs(response->data,
char))[payloadOffset];
1277 while (response->BodyLength < bodyLength)
1281 if (!Stream_EnsureRemainingCapacity(response->data, bodyLength - response->BodyLength))
1285 size_t diff = bodyLength - response->BodyLength;
1286 if (diff > INT32_MAX)
1288 status = BIO_read(tls->bio, Stream_Pointer(response->data), (
int)diff);
1292 if (sleep_or_timeout(tls, startMS, timeoutMS))
1297 Stream_Seek(response->data, (
size_t)status);
1298 response->BodyLength += (
unsigned long)status;
1300 if (response->BodyLength > RESPONSE_SIZE_LIMIT)
1302 WLog_ERR(TAG,
"Request body too large! (%" PRIuz
" bytes) Aborting!",
1303 response->BodyLength);
1308 if (response->BodyLength > 0)
1309 response->BodyContent = &(Stream_BufferAs(response->data,
char))[payloadOffset];
1311 if (bodyLength != response->BodyLength)
1313 WLog_WARN(TAG,
"%s unexpected body length: actual: %" PRIuz
", expected: %" PRIuz,
1314 response->ContentType, response->BodyLength, bodyLength);
1317 response->BodyLength = MIN(bodyLength, response->BodyLength);
1321 if (!Stream_EnsureRemainingCapacity(response->data,
sizeof(UINT16)))
1323 Stream_Write_UINT16(response->data, 0);
1331static void clear_lines(HttpResponse* response)
1333 WINPR_ASSERT(response);
1335 for (
size_t x = 0; x < response->count; x++)
1337 WINPR_ASSERT(response->lines);
1338 char* line = response->lines[x];
1342 free((
void*)response->lines);
1343 response->lines =
nullptr;
1344 response->count = 0;
1347HttpResponse* http_response_recv(rdpTls* tls, BOOL readContentLength)
1349 size_t bodyLength = 0;
1350 HttpResponse* response = http_response_new();
1355 response->ContentLength = 0;
1357 const SSIZE_T payloadOffset = http_response_recv_line(tls, response);
1358 if (payloadOffset < 0)
1364 char* buffer = Stream_BufferAs(response->data,
char);
1365 const char* line = Stream_BufferAs(response->data,
char);
1366 char* context =
nullptr;
1368 while ((line = string_strnstr(line,
"\r\n",
1369 WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset) -
1370 WINPR_ASSERTING_INT_CAST(
size_t, (line - buffer)) - 2UL)))
1376 clear_lines(response);
1377 response->count = count;
1381 response->lines = (
char**)calloc(response->count,
sizeof(
char*));
1383 if (!response->lines)
1387 buffer[payloadOffset - 1] =
'\0';
1388 buffer[payloadOffset - 2] =
'\0';
1390 line = strtok_s(buffer,
"\r\n", &context);
1392 while (line && (response->count > count))
1394 response->lines[count] = _strdup(line);
1395 if (!response->lines[count])
1397 line = strtok_s(
nullptr,
"\r\n", &context);
1401 if (!http_response_parse_header(response))
1404 response->BodyLength =
1405 Stream_GetPosition(response->data) - WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset);
1407 WINPR_ASSERT(response->BodyLength == 0);
1408 bodyLength = response->BodyLength;
1410 if (readContentLength && (response->ContentLength > 0))
1412 const char* cur = response->ContentType;
1414 while (cur !=
nullptr)
1416 if (http_use_content_length(cur))
1418 if (response->ContentLength < RESPONSE_SIZE_LIMIT)
1419 bodyLength = response->ContentLength;
1424 readContentLength = FALSE;
1426 cur = strchr(cur,
';');
1430 if (bodyLength > RESPONSE_SIZE_LIMIT)
1432 WLog_ERR(TAG,
"Expected request body too large! (%" PRIuz
" bytes) Aborting!",
1438 if (!http_response_recv_body(tls, response, readContentLength,
1439 WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset), bodyLength))
1442 Stream_SealLength(response->data);
1445 if (!Stream_EnsureRemainingCapacity(response->data, 2))
1447 Stream_Write_UINT16(response->data, 0);
1451 WLog_ERR(TAG,
"No response");
1452 http_response_free(response);
1456const char* http_response_get_body(
const HttpResponse* response)
1461 return response->BodyContent;
1464wHashTable* HashTable_New_String(
void)
1466 wHashTable* table = HashTable_New(FALSE);
1470 if (!HashTable_SetupForStringData(table, TRUE))
1472 HashTable_Free(table);
1475 HashTable_KeyObject(table)->
fnObjectEquals = strings_equals_nocase;
1476 HashTable_ValueObject(table)->
fnObjectEquals = strings_equals_nocase;
1480HttpResponse* http_response_new(
void)
1482 HttpResponse* response = (HttpResponse*)calloc(1,
sizeof(HttpResponse));
1487 response->Authenticates = HashTable_New_String();
1489 if (!response->Authenticates)
1492 response->SetCookie = HashTable_New_String();
1494 if (!response->SetCookie)
1497 response->data = Stream_New(
nullptr, 2048);
1499 if (!response->data)
1502 response->TransferEncoding = TransferEncodingIdentity;
1505 WINPR_PRAGMA_DIAG_PUSH
1506 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
1507 http_response_free(response);
1508 WINPR_PRAGMA_DIAG_POP
1512void http_response_free(HttpResponse* response)
1517 clear_lines(response);
1518 free(response->ReasonPhrase);
1519 free(response->ContentType);
1520 free(response->SecWebsocketAccept);
1521 free(response->SecWebsocketVersion);
1522 HashTable_Free(response->Authenticates);
1523 HashTable_Free(response->SetCookie);
1524 Stream_Free(response->data, TRUE);
1528const char* http_request_get_uri(HttpRequest* request)
1533 return request->URI;
1536SSIZE_T http_request_get_content_length(HttpRequest* request)
1541 return (SSIZE_T)request->ContentLength;
1544BOOL http_request_set_content_length(HttpRequest* request,
size_t length)
1549 request->ContentLength = length;
1553UINT16 http_response_get_status_code(
const HttpResponse* response)
1555 WINPR_ASSERT(response);
1557 return response->StatusCode;
1560size_t http_response_get_body_length(
const HttpResponse* response)
1562 WINPR_ASSERT(response);
1564 return response->BodyLength;
1567const char* http_response_get_auth_token(
const HttpResponse* response,
const char* method)
1569 if (!response || !method)
1572 return HashTable_GetItemValue(response->Authenticates, method);
1575const char* http_response_get_setcookie(
const HttpResponse* response,
const char* cookie)
1577 if (!response || !cookie)
1580 return HashTable_GetItemValue(response->SetCookie, cookie);
1583TRANSFER_ENCODING http_response_get_transfer_encoding(
const HttpResponse* response)
1586 return TransferEncodingUnknown;
1588 return response->TransferEncoding;
1591BOOL http_response_is_websocket(
const HttpContext* http,
const HttpResponse* response)
1593 BOOL isWebsocket = FALSE;
1594 WINPR_DIGEST_CTX* sha1 =
nullptr;
1595 char* base64accept =
nullptr;
1596 BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH];
1598 if (!http || !response)
1601 if (!http->websocketUpgrade || response->StatusCode != HTTP_STATUS_SWITCH_PROTOCOLS)
1604 if (response->SecWebsocketVersion && _stricmp(response->SecWebsocketVersion,
"13") != 0)
1607 if (!response->SecWebsocketAccept)
1612 sha1 = winpr_Digest_New();
1616 if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1))
1619 if (!winpr_Digest_Update(sha1, (BYTE*)http->SecWebsocketKey, strlen(http->SecWebsocketKey)))
1621 if (!winpr_Digest_Update(sha1, (
const BYTE*)WEBSOCKET_MAGIC_GUID, strlen(WEBSOCKET_MAGIC_GUID)))
1624 if (!winpr_Digest_Final(sha1, sha1_digest,
sizeof(sha1_digest)))
1627 base64accept = crypto_base64_encode(sha1_digest, WINPR_SHA1_DIGEST_LENGTH);
1631 if (_stricmp(response->SecWebsocketAccept, base64accept) != 0)
1633 WLog_WARN(TAG,
"Webserver gave Websocket Upgrade response but sanity check failed");
1638 winpr_Digest_Free(sha1);
1643void http_response_log_error_status_(wLog* log, DWORD level,
const HttpResponse* response,
1644 const char* file,
size_t line,
const char* fkt)
1647 WINPR_ASSERT(response);
1649 if (!WLog_IsLevelActive(log, level))
1652 char buffer[64] = WINPR_C_ARRAY_INIT;
1653 const UINT16 status = http_response_get_status_code(response);
1654 WLog_PrintTextMessage(log, level, line, file, fkt,
"Unexpected HTTP status: %s",
1655 freerdp_http_status_string_format(status, buffer, ARRAYSIZE(buffer)));
1656 http_response_print(log, level, response, file, line, fkt);
1659static BOOL extract_cookie(
const void* pkey,
void* pvalue,
void* arg)
1661 const char* key = pkey;
1662 const char* value = pvalue;
1663 HttpContext* context = arg;
1667 WINPR_ASSERT(value);
1669 return http_context_set_cookie(context, key, value);
1672BOOL http_response_extract_cookies(
const HttpResponse* response, HttpContext* context)
1674 WINPR_ASSERT(response);
1675 WINPR_ASSERT(context);
1677 return HashTable_Foreach(response->SetCookie, extract_cookie, context);
1680FREERDP_LOCAL BOOL http_context_set_header(HttpContext* context,
const char* key,
const char* value,
1683 WINPR_ASSERT(context);
1684 va_list ap = WINPR_C_ARRAY_INIT;
1685 va_start(ap, value);
1686 const BOOL rc = http_context_set_header_va(context, key, value, ap);
1691BOOL http_request_set_header(HttpRequest* request,
const char* key,
const char* value, ...)
1693 WINPR_ASSERT(request);
1696 va_list ap = WINPR_C_ARRAY_INIT;
1697 va_start(ap, value);
1698 winpr_vasprintf(&v, &vlen, value, ap);
1700 const BOOL rc = HashTable_Insert(request->headers, key, v);
1705BOOL http_context_set_header_va(HttpContext* context,
const char* key,
const char* value,
1710 winpr_vasprintf(&v, &vlen, value, ap);
1711 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
OBJECT_EQUALS_FN fnObjectEquals
OBJECT_NEW_FN fnObjectNew