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);
325static char* guid2str(
const GUID* guid,
char* buffer,
size_t len)
329 RPC_CSTR strguid =
nullptr;
331 RPC_STATUS rpcStatus = UuidToStringA(guid, &strguid);
333 if (rpcStatus != RPC_S_OK)
336 (void)sprintf_s(buffer, len,
"{%s}", strguid);
337 RpcStringFreeA(&strguid);
341BOOL http_context_set_rdg_connection_id(HttpContext* context,
const GUID* RdgConnectionId)
343 if (!context || !RdgConnectionId)
346 char buffer[64] = WINPR_C_ARRAY_INIT;
347 return http_context_set_header(context,
"RDG-Connection-Id",
"%s",
348 guid2str(RdgConnectionId, buffer,
sizeof(buffer)));
351BOOL http_context_set_rdg_correlation_id(HttpContext* context,
const GUID* RdgCorrelationId)
353 if (!context || !RdgCorrelationId)
356 char buffer[64] = WINPR_C_ARRAY_INIT;
357 return http_context_set_header(context,
"RDG-Correlation-Id",
"%s",
358 guid2str(RdgCorrelationId, buffer,
sizeof(buffer)));
361BOOL http_context_enable_websocket_upgrade(HttpContext* context, BOOL enable)
363 WINPR_ASSERT(context);
367 GUID key = WINPR_C_ARRAY_INIT;
368 if (RPC_S_OK != UuidCreate(&key))
371 free(context->SecWebsocketKey);
372 context->SecWebsocketKey = crypto_base64_encode((BYTE*)&key,
sizeof(key));
373 if (!context->SecWebsocketKey)
377 context->websocketUpgrade = enable;
381BOOL http_context_is_websocket_upgrade_enabled(HttpContext* context)
383 return context->websocketUpgrade;
386BOOL http_context_set_rdg_auth_scheme(HttpContext* context,
const char* RdgAuthScheme)
388 if (!context || !RdgAuthScheme)
391 return http_context_set_header(context,
"RDG-Auth-Scheme",
"%s", RdgAuthScheme);
394BOOL http_context_set_cookie(HttpContext* context,
const char* CookieName,
const char* CookieValue)
396 if (!context || !CookieName || !CookieValue)
398 if (ListDictionary_Contains(context->cookies, CookieName))
400 if (!ListDictionary_SetItemValue(context->cookies, CookieName, CookieValue))
405 if (!ListDictionary_Add(context->cookies, CookieName, CookieValue))
411void http_context_free(HttpContext* context)
415 free(context->SecWebsocketKey);
417 free(context->Method);
418 free(context->Connection);
419 free(context->Pragma);
420 HashTable_Free(context->headers);
421 ListDictionary_Free(context->cookies);
426BOOL http_request_set_method(HttpRequest* request,
const char* Method)
428 if (!request || !Method)
431 free(request->Method);
432 request->Method = _strdup(Method);
434 return (request->Method !=
nullptr);
437BOOL http_request_set_uri(HttpRequest* request,
const char* URI)
439 if (!request || !URI)
443 request->URI = _strdup(URI);
445 return (request->URI !=
nullptr);
448BOOL http_request_set_auth_scheme(HttpRequest* request,
const char* AuthScheme)
450 if (!request || !AuthScheme)
453 free(request->AuthScheme);
454 request->AuthScheme = _strdup(AuthScheme);
456 return (request->AuthScheme !=
nullptr);
459BOOL http_request_set_auth_param(HttpRequest* request,
const char* AuthParam)
461 if (!request || !AuthParam)
464 free(request->AuthParam);
465 request->AuthParam = _strdup(AuthParam);
467 return (request->AuthParam !=
nullptr);
470BOOL http_request_set_transfer_encoding(HttpRequest* request, TRANSFER_ENCODING TransferEncoding)
472 if (!request || TransferEncoding == TransferEncodingUnknown)
475 request->TransferEncoding = TransferEncoding;
480WINPR_ATTR_FORMAT_ARG(2, 3)
481static BOOL http_encode_print(
wStream* s, WINPR_FORMAT_ARG const
char* fmt, ...)
484 va_list ap = WINPR_C_ARRAY_INIT;
492 length = vsnprintf(
nullptr, 0, fmt, ap) + 1;
495 if (!Stream_EnsureRemainingCapacity(s, (
size_t)length))
498 str = (
char*)Stream_Pointer(s);
500 used = vsnprintf(str, (
size_t)length, fmt, ap);
504 if ((used + 1) != length)
507 Stream_Seek(s, (
size_t)used);
511static BOOL http_encode_body_line(
wStream* s,
const char* param,
const char* value)
513 if (!s || !param || !value)
516 return http_encode_print(s,
"%s: %s\r\n", param, value);
519static BOOL http_encode_content_length_line(
wStream* s,
size_t ContentLength)
521 return http_encode_print(s,
"Content-Length: %" PRIuz
"\r\n", ContentLength);
524static BOOL http_encode_header_line(
wStream* s,
const char* Method,
const char* URI)
526 if (!s || !Method || !URI)
529 return http_encode_print(s,
"%s %s HTTP/1.1\r\n", Method, URI);
532static BOOL http_encode_authorization_line(
wStream* s,
const char* AuthScheme,
533 const char* AuthParam)
535 if (!s || !AuthScheme || !AuthParam)
538 return http_encode_print(s,
"Authorization: %s %s\r\n", AuthScheme, AuthParam);
541static BOOL http_encode_cookie_line(
wStream* s, wListDictionary* cookies)
543 ULONG_PTR* keys =
nullptr;
549 ListDictionary_Lock(cookies);
550 const size_t count = ListDictionary_GetKeys(cookies, &keys);
555 status = http_encode_print(s,
"Cookie: ");
559 for (
size_t x = 0; status && x < count; x++)
561 char* cur = (
char*)ListDictionary_GetItemValue(cookies, (
void*)keys[x]);
569 status = http_encode_print(s,
"; ");
573 status = http_encode_print(s,
"%s=%s", (
char*)keys[x], cur);
576 status = http_encode_print(s,
"\r\n");
579 ListDictionary_Unlock(cookies);
583static BOOL write_headers(
const void* pkey,
void* pvalue,
void* arg)
585 const char* key = pkey;
586 const char* value = pvalue;
593 return http_encode_body_line(s, key, value);
596wStream* http_request_write(HttpContext* context, HttpRequest* request)
598 if (!context || !request)
601 wStream* s = Stream_New(
nullptr, 1024);
606 if (!http_encode_header_line(s, request->Method, request->URI) ||
608 !http_encode_body_line(s,
"Pragma", context->Pragma))
611 if (!context->websocketUpgrade)
613 if (!http_encode_body_line(s,
"Connection", context->Connection))
618 if (!http_encode_body_line(s,
"Connection",
"Upgrade") ||
619 !http_encode_body_line(s,
"Upgrade",
"websocket") ||
620 !http_encode_body_line(s,
"Sec-Websocket-Version",
"13") ||
621 !http_encode_body_line(s,
"Sec-Websocket-Key", context->SecWebsocketKey))
625 if (request->TransferEncoding != TransferEncodingIdentity)
627 if (request->TransferEncoding == TransferEncodingChunked)
629 if (!http_encode_body_line(s,
"Transfer-Encoding",
"chunked"))
637 if (!http_encode_content_length_line(s, request->ContentLength))
641 if (!utils_str_is_empty(request->Authorization))
643 if (!http_encode_body_line(s,
"Authorization", request->Authorization))
646 else if (!utils_str_is_empty(request->AuthScheme) && !utils_str_is_empty(request->AuthParam))
648 if (!http_encode_authorization_line(s, request->AuthScheme, request->AuthParam))
652 if (!HashTable_Foreach(context->headers, write_headers, s))
655 if (!HashTable_Foreach(request->headers, write_headers, s))
658 if (!http_encode_cookie_line(s, context->cookies))
661 if (!http_encode_print(s,
"\r\n"))
664 Stream_SealLength(s);
667 Stream_Free(s, TRUE);
671HttpRequest* http_request_new(
void)
673 HttpRequest* request = (HttpRequest*)calloc(1,
sizeof(HttpRequest));
677 request->headers = HashTable_New_String();
678 if (!request->headers)
680 request->TransferEncoding = TransferEncodingIdentity;
683 http_request_free(request);
687void http_request_free(HttpRequest* request)
692 free(request->AuthParam);
693 free(request->AuthScheme);
694 free(request->Authorization);
695 free(request->Method);
697 HashTable_Free(request->headers);
701static BOOL http_response_parse_header_status_line(HttpResponse* response,
const char* status_line)
704 char* separator =
nullptr;
705 char* status_code =
nullptr;
711 separator = strchr(status_line,
' ');
716 status_code = separator + 1;
717 separator = strchr(status_code,
' ');
723 const char* reason_phrase = separator + 1;
727 long val = strtol(status_code,
nullptr, 0);
729 if ((errno != 0) || (val < 0) || (val > INT16_MAX))
732 response->StatusCode = (UINT16)val;
734 free(response->ReasonPhrase);
735 response->ReasonPhrase = _strdup(reason_phrase);
738 if (!response->ReasonPhrase)
746 WLog_ERR(TAG,
"http_response_parse_header_status_line failed [%s]", status_line);
751static BOOL http_response_parse_header_field(HttpResponse* response,
const char* name,
754 WINPR_ASSERT(response);
759 if (_stricmp(name,
"Content-Length") == 0)
761 unsigned long long val = 0;
763 val = _strtoui64(value,
nullptr, 0);
765 if ((errno != 0) || (val > INT32_MAX))
768 response->ContentLength = WINPR_ASSERTING_INT_CAST(
size_t, val);
772 if (_stricmp(name,
"Content-Type") == 0)
774 free(response->ContentType);
775 response->ContentType = _strdup(value);
777 return response->ContentType !=
nullptr;
780 if (_stricmp(name,
"Transfer-Encoding") == 0)
782 if (_stricmp(value,
"identity") == 0)
783 response->TransferEncoding = TransferEncodingIdentity;
784 else if (_stricmp(value,
"chunked") == 0)
785 response->TransferEncoding = TransferEncodingChunked;
787 response->TransferEncoding = TransferEncodingUnknown;
792 if (_stricmp(name,
"Sec-WebSocket-Version") == 0)
794 free(response->SecWebsocketVersion);
795 response->SecWebsocketVersion = _strdup(value);
797 return response->SecWebsocketVersion !=
nullptr;
800 if (_stricmp(name,
"Sec-WebSocket-Accept") == 0)
802 free(response->SecWebsocketAccept);
803 response->SecWebsocketAccept = _strdup(value);
805 return response->SecWebsocketAccept !=
nullptr;
808 if (_stricmp(name,
"WWW-Authenticate") == 0)
810 const char* authScheme = value;
811 const char* authValue =
"";
812 char* separator = strchr(value,
' ');
823 authValue = separator + 1;
826 return HashTable_Insert(response->Authenticates, authScheme, authValue);
829 if (_stricmp(name,
"Set-Cookie") == 0)
831 char* separator = strchr(value,
'=');
841 const char* CookieName = value;
842 char* CookieValue = separator + 1;
844 if (*CookieValue ==
'"')
846 char* p = CookieValue;
847 while (*p !=
'"' && *p !=
'\0')
857 char* p = CookieValue;
858 while (*p !=
';' && *p !=
'\0' && *p !=
' ')
864 return HashTable_Insert(response->SetCookie, CookieName, CookieValue);
871static BOOL http_response_parse_header(HttpResponse* response)
875 char* line =
nullptr;
876 char* name =
nullptr;
877 char* colon_pos =
nullptr;
878 char* end_of_header =
nullptr;
879 char end_of_header_char = 0;
884 if (!response->lines)
887 if (!http_response_parse_header_status_line(response, response->lines[0]))
890 for (
size_t count = 1; count < response->count; count++)
892 line = response->lines[count];
904 colon_pos = strchr(line,
':');
908 if ((colon_pos ==
nullptr) || (colon_pos == line))
912 for (end_of_header = colon_pos; end_of_header != line; end_of_header--)
914 c = end_of_header[-1];
916 if (c !=
' ' && c !=
'\t' && c !=
':')
920 if (end_of_header == line)
923 end_of_header_char = *end_of_header;
924 *end_of_header =
'\0';
928 char* value = colon_pos + 1;
929 for (; *value; value++)
931 if ((*value !=
' ') && (*value !=
'\t'))
935 const int res = http_response_parse_header_field(response, name, value);
936 *end_of_header = end_of_header_char;
945 WLog_ERR(TAG,
"parsing failed");
950static void http_response_print(wLog* log, DWORD level,
const HttpResponse* response,
951 const char* file,
size_t line,
const char* fkt)
953 char buffer[64] = WINPR_C_ARRAY_INIT;
956 WINPR_ASSERT(response);
958 if (!WLog_IsLevelActive(log, level))
961 const long status = http_response_get_status_code(response);
962 WLog_PrintTextMessage(log, level, line, file, fkt,
"HTTP status: %s",
963 freerdp_http_status_string_format(status, buffer, ARRAYSIZE(buffer)));
965 if (WLog_IsLevelActive(log, WLOG_DEBUG))
967 for (
size_t i = 0; i < response->count; i++)
968 WLog_PrintTextMessage(log, WLOG_DEBUG, line, file, fkt,
"[%" PRIuz
"] %s", i,
972 if (response->ReasonPhrase)
973 WLog_PrintTextMessage(log, level, line, file, fkt,
"[reason] %s", response->ReasonPhrase);
975 if (WLog_IsLevelActive(log, WLOG_TRACE))
977 WLog_PrintTextMessage(log, WLOG_TRACE, line, file, fkt,
"[body][%" PRIuz
"] %s",
978 response->BodyLength, response->BodyContent);
982static BOOL http_use_content_length(
const char* cur)
989 if (_strnicmp(cur,
"application/rpc", 15) == 0)
991 else if (_strnicmp(cur,
"text/plain", 10) == 0)
993 else if (_strnicmp(cur,
"text/html", 9) == 0)
995 else if (_strnicmp(cur,
"application/json", 16) == 0)
1000 char end = cur[pos];
1019static int print_bio_error(
const char* str,
size_t len,
void* bp)
1024 WLog_Print(log, WLOG_ERROR,
"%s", str);
1025 if (len > INT32_MAX)
1030int http_chuncked_read(BIO* bio, BYTE* pBuffer,
size_t size,
1034 int effectiveDataLen = 0;
1036 WINPR_ASSERT(pBuffer);
1037 WINPR_ASSERT(encodingContext !=
nullptr);
1038 WINPR_ASSERT(size <= INT32_MAX);
1041 switch (encodingContext->state)
1043 case ChunkStateData:
1046 (size > encodingContext->nextOffset ? encodingContext->nextOffset : size);
1051 status = BIO_read(bio, pBuffer, (
int)rd);
1053 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1055 encodingContext->nextOffset -= WINPR_ASSERTING_INT_CAST(uint32_t, status);
1056 if (encodingContext->nextOffset == 0)
1058 encodingContext->state = ChunkStateFooter;
1059 encodingContext->headerFooterPos = 0;
1061 effectiveDataLen += status;
1063 if ((
size_t)status == size)
1064 return effectiveDataLen;
1067 size -= (size_t)status;
1070 case ChunkStateFooter:
1072 char _dummy[2] = WINPR_C_ARRAY_INIT;
1073 WINPR_ASSERT(encodingContext->nextOffset == 0);
1074 WINPR_ASSERT(encodingContext->headerFooterPos < 2);
1076 status = BIO_read(bio, _dummy, (
int)(2 - encodingContext->headerFooterPos));
1079 encodingContext->headerFooterPos += (size_t)status;
1080 if (encodingContext->headerFooterPos == 2)
1082 encodingContext->state = ChunkStateLenghHeader;
1083 encodingContext->headerFooterPos = 0;
1087 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1090 case ChunkStateLenghHeader:
1092 BOOL _haveNewLine = FALSE;
1093 char* dst = &encodingContext->lenBuffer[encodingContext->headerFooterPos];
1094 WINPR_ASSERT(encodingContext->nextOffset == 0);
1095 while (encodingContext->headerFooterPos < 10 && !_haveNewLine)
1098 status = BIO_read(bio, dst, 1);
1102 _haveNewLine = TRUE;
1103 encodingContext->headerFooterPos += (size_t)status;
1107 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1113 size_t tmp = strtoul(encodingContext->lenBuffer,
nullptr, 16);
1114 if ((errno != 0) || (tmp > SIZE_MAX))
1117 encodingContext->nextOffset = 0;
1118 encodingContext->state = ChunkStateEnd;
1121 encodingContext->nextOffset = tmp;
1122 encodingContext->state = ChunkStateData;
1124 if (encodingContext->nextOffset == 0)
1126 WLog_DBG(TAG,
"chunked encoding end of stream received");
1127 encodingContext->headerFooterPos = 0;
1128 encodingContext->state = ChunkStateEnd;
1129 return (effectiveDataLen > 0 ? effectiveDataLen : 0);
1140#define sleep_or_timeout(tls, startMS, timeoutMS) \
1141 sleep_or_timeout_((tls), (startMS), (timeoutMS), __FILE__, __func__, __LINE__)
1142static BOOL sleep_or_timeout_(rdpTls* tls, UINT64 startMS, UINT32 timeoutMS,
const char* file,
1143 const char* fkt,
size_t line)
1148 const UINT64 nowMS = GetTickCount64();
1149 if (nowMS - startMS > timeoutMS)
1151 DWORD level = WLOG_ERROR;
1152 wLog* log = WLog_Get(TAG);
1153 if (WLog_IsLevelActive(log, level))
1154 WLog_PrintTextMessage(log, level, line, file, fkt,
"timeout [%" PRIu32
"ms] exceeded",
1158 if (!BIO_should_retry(tls->bio))
1160 DWORD level = WLOG_ERROR;
1161 wLog* log = WLog_Get(TAG);
1162 if (WLog_IsLevelActive(log, level))
1164 WLog_PrintTextMessage(log, level, line, file, fkt,
"Retries exceeded");
1165 ERR_print_errors_cb(print_bio_error, log);
1169 if (freerdp_shall_disconnect_context(tls->context))
1175static SSIZE_T http_response_recv_line(rdpTls* tls, HttpResponse* response)
1178 WINPR_ASSERT(response);
1180 SSIZE_T payloadOffset = -1;
1181 const UINT32 timeoutMS =
1183 const UINT64 startMS = GetTickCount64();
1184 while (payloadOffset <= 0)
1186 size_t bodyLength = 0;
1187 size_t position = 0;
1190 char* end =
nullptr;
1194 status = BIO_read(tls->bio, Stream_Pointer(response->data), 1);
1197 if (sleep_or_timeout(tls, startMS, timeoutMS))
1202#ifdef FREERDP_HAVE_VALGRIND_MEMCHECK_H
1203 VALGRIND_MAKE_MEM_DEFINED(Stream_Pointer(response->data), status);
1205 Stream_Seek(response->data, (
size_t)status);
1207 if (!Stream_EnsureRemainingCapacity(response->data, 1024))
1210 position = Stream_GetPosition(response->data);
1214 else if (position > RESPONSE_SIZE_LIMIT)
1216 WLog_ERR(TAG,
"Request header too large! (%" PRIuz
" bytes) Aborting!", bodyLength);
1222 s = (position > 8) ? 8 : position;
1223 end = (
char*)Stream_Pointer(response->data) - s;
1225 if (string_strnstr(end,
"\r\n\r\n", s) !=
nullptr)
1226 payloadOffset = WINPR_ASSERTING_INT_CAST(SSIZE_T, Stream_GetPosition(response->data));
1230 return payloadOffset;
1233static BOOL http_response_recv_body(rdpTls* tls, HttpResponse* response, BOOL readContentLength,
1234 size_t payloadOffset,
size_t bodyLength)
1239 WINPR_ASSERT(response);
1241 const UINT64 startMS = GetTickCount64();
1242 const UINT32 timeoutMS =
1245 if ((response->TransferEncoding == TransferEncodingChunked) && readContentLength)
1248 ctx.state = ChunkStateLenghHeader;
1250 ctx.headerFooterPos = 0;
1254 if (!Stream_EnsureRemainingCapacity(response->data, 2048))
1257 int status = http_chuncked_read(tls->bio, Stream_Pointer(response->data),
1258 Stream_GetRemainingCapacity(response->data), &ctx);
1261 if (sleep_or_timeout(tls, startMS, timeoutMS))
1266 Stream_Seek(response->data, (
size_t)status);
1269 }
while (ctx.state != ChunkStateEnd);
1270 response->BodyLength = WINPR_ASSERTING_INT_CAST(uint32_t, full_len);
1271 if (response->BodyLength > 0)
1272 response->BodyContent = &(Stream_BufferAs(response->data,
char))[payloadOffset];
1276 while (response->BodyLength < bodyLength)
1280 if (!Stream_EnsureRemainingCapacity(response->data, bodyLength - response->BodyLength))
1284 size_t diff = bodyLength - response->BodyLength;
1285 if (diff > INT32_MAX)
1287 status = BIO_read(tls->bio, Stream_Pointer(response->data), (
int)diff);
1291 if (sleep_or_timeout(tls, startMS, timeoutMS))
1296 Stream_Seek(response->data, (
size_t)status);
1297 response->BodyLength += (
unsigned long)status;
1299 if (response->BodyLength > RESPONSE_SIZE_LIMIT)
1301 WLog_ERR(TAG,
"Request body too large! (%" PRIuz
" bytes) Aborting!",
1302 response->BodyLength);
1307 if (response->BodyLength > 0)
1308 response->BodyContent = &(Stream_BufferAs(response->data,
char))[payloadOffset];
1310 if (bodyLength != response->BodyLength)
1312 WLog_WARN(TAG,
"%s unexpected body length: actual: %" PRIuz
", expected: %" PRIuz,
1313 response->ContentType, response->BodyLength, bodyLength);
1316 response->BodyLength = MIN(bodyLength, response->BodyLength);
1320 if (!Stream_EnsureRemainingCapacity(response->data,
sizeof(UINT16)))
1322 Stream_Write_UINT16(response->data, 0);
1330static void clear_lines(HttpResponse* response)
1332 WINPR_ASSERT(response);
1334 for (
size_t x = 0; x < response->count; x++)
1336 WINPR_ASSERT(response->lines);
1337 char* line = response->lines[x];
1341 free((
void*)response->lines);
1342 response->lines =
nullptr;
1343 response->count = 0;
1346HttpResponse* http_response_recv(rdpTls* tls, BOOL readContentLength)
1348 size_t bodyLength = 0;
1349 HttpResponse* response = http_response_new();
1354 response->ContentLength = 0;
1356 const SSIZE_T payloadOffset = http_response_recv_line(tls, response);
1357 if (payloadOffset < 0)
1363 char* buffer = Stream_BufferAs(response->data,
char);
1364 const char* line = Stream_BufferAs(response->data,
char);
1365 char* context =
nullptr;
1367 while ((line = string_strnstr(line,
"\r\n",
1368 WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset) -
1369 WINPR_ASSERTING_INT_CAST(
size_t, (line - buffer)) - 2UL)))
1375 clear_lines(response);
1376 response->count = count;
1380 response->lines = (
char**)calloc(response->count,
sizeof(
char*));
1382 if (!response->lines)
1386 buffer[payloadOffset - 1] =
'\0';
1387 buffer[payloadOffset - 2] =
'\0';
1389 line = strtok_s(buffer,
"\r\n", &context);
1391 while (line && (response->count > count))
1393 response->lines[count] = _strdup(line);
1394 if (!response->lines[count])
1396 line = strtok_s(
nullptr,
"\r\n", &context);
1400 if (!http_response_parse_header(response))
1403 response->BodyLength =
1404 Stream_GetPosition(response->data) - WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset);
1406 WINPR_ASSERT(response->BodyLength == 0);
1407 bodyLength = response->BodyLength;
1409 if (readContentLength && (response->ContentLength > 0))
1411 const char* cur = response->ContentType;
1413 while (cur !=
nullptr)
1415 if (http_use_content_length(cur))
1417 if (response->ContentLength < RESPONSE_SIZE_LIMIT)
1418 bodyLength = response->ContentLength;
1423 readContentLength = FALSE;
1425 cur = strchr(cur,
';');
1429 if (bodyLength > RESPONSE_SIZE_LIMIT)
1431 WLog_ERR(TAG,
"Expected request body too large! (%" PRIuz
" bytes) Aborting!",
1437 if (!http_response_recv_body(tls, response, readContentLength,
1438 WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset), bodyLength))
1441 Stream_SealLength(response->data);
1444 if (!Stream_EnsureRemainingCapacity(response->data, 2))
1446 Stream_Write_UINT16(response->data, 0);
1450 WLog_ERR(TAG,
"No response");
1451 http_response_free(response);
1455const char* http_response_get_body(
const HttpResponse* response)
1460 return response->BodyContent;
1463wHashTable* HashTable_New_String(
void)
1465 wHashTable* table = HashTable_New(FALSE);
1469 if (!HashTable_SetupForStringData(table, TRUE))
1471 HashTable_Free(table);
1474 HashTable_KeyObject(table)->
fnObjectEquals = strings_equals_nocase;
1475 HashTable_ValueObject(table)->
fnObjectEquals = strings_equals_nocase;
1479HttpResponse* http_response_new(
void)
1481 HttpResponse* response = (HttpResponse*)calloc(1,
sizeof(HttpResponse));
1486 response->Authenticates = HashTable_New_String();
1488 if (!response->Authenticates)
1491 response->SetCookie = HashTable_New_String();
1493 if (!response->SetCookie)
1496 response->data = Stream_New(
nullptr, 2048);
1498 if (!response->data)
1501 response->TransferEncoding = TransferEncodingIdentity;
1504 WINPR_PRAGMA_DIAG_PUSH
1505 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
1506 http_response_free(response);
1507 WINPR_PRAGMA_DIAG_POP
1511void http_response_free(HttpResponse* response)
1516 clear_lines(response);
1517 free(response->ReasonPhrase);
1518 free(response->ContentType);
1519 free(response->SecWebsocketAccept);
1520 free(response->SecWebsocketVersion);
1521 HashTable_Free(response->Authenticates);
1522 HashTable_Free(response->SetCookie);
1523 Stream_Free(response->data, TRUE);
1527const char* http_request_get_uri(HttpRequest* request)
1532 return request->URI;
1535SSIZE_T http_request_get_content_length(HttpRequest* request)
1540 return (SSIZE_T)request->ContentLength;
1543BOOL http_request_set_content_length(HttpRequest* request,
size_t length)
1548 request->ContentLength = length;
1552UINT16 http_response_get_status_code(
const HttpResponse* response)
1554 WINPR_ASSERT(response);
1556 return response->StatusCode;
1559size_t http_response_get_body_length(
const HttpResponse* response)
1561 WINPR_ASSERT(response);
1563 return response->BodyLength;
1566const char* http_response_get_auth_token(
const HttpResponse* response,
const char* method)
1568 if (!response || !method)
1571 return HashTable_GetItemValue(response->Authenticates, method);
1574const char* http_response_get_setcookie(
const HttpResponse* response,
const char* cookie)
1576 if (!response || !cookie)
1579 return HashTable_GetItemValue(response->SetCookie, cookie);
1582TRANSFER_ENCODING http_response_get_transfer_encoding(
const HttpResponse* response)
1585 return TransferEncodingUnknown;
1587 return response->TransferEncoding;
1590BOOL http_response_is_websocket(
const HttpContext* http,
const HttpResponse* response)
1592 BOOL isWebsocket = FALSE;
1593 WINPR_DIGEST_CTX* sha1 =
nullptr;
1594 char* base64accept =
nullptr;
1595 BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH];
1597 if (!http || !response)
1600 if (!http->websocketUpgrade || response->StatusCode != HTTP_STATUS_SWITCH_PROTOCOLS)
1603 if (response->SecWebsocketVersion && _stricmp(response->SecWebsocketVersion,
"13") != 0)
1606 if (!response->SecWebsocketAccept)
1611 sha1 = winpr_Digest_New();
1615 if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1))
1618 if (!winpr_Digest_Update(sha1, (BYTE*)http->SecWebsocketKey, strlen(http->SecWebsocketKey)))
1620 if (!winpr_Digest_Update(sha1, (
const BYTE*)WEBSOCKET_MAGIC_GUID, strlen(WEBSOCKET_MAGIC_GUID)))
1623 if (!winpr_Digest_Final(sha1, sha1_digest,
sizeof(sha1_digest)))
1626 base64accept = crypto_base64_encode(sha1_digest, WINPR_SHA1_DIGEST_LENGTH);
1630 if (_stricmp(response->SecWebsocketAccept, base64accept) != 0)
1632 WLog_WARN(TAG,
"Webserver gave Websocket Upgrade response but sanity check failed");
1637 winpr_Digest_Free(sha1);
1642void http_response_log_error_status_(wLog* log, DWORD level,
const HttpResponse* response,
1643 const char* file,
size_t line,
const char* fkt)
1646 WINPR_ASSERT(response);
1648 if (!WLog_IsLevelActive(log, level))
1651 char buffer[64] = WINPR_C_ARRAY_INIT;
1652 const UINT16 status = http_response_get_status_code(response);
1653 WLog_PrintTextMessage(log, level, line, file, fkt,
"Unexpected HTTP status: %s",
1654 freerdp_http_status_string_format(status, buffer, ARRAYSIZE(buffer)));
1655 http_response_print(log, level, response, file, line, fkt);
1658static BOOL extract_cookie(
const void* pkey,
void* pvalue,
void* arg)
1660 const char* key = pkey;
1661 const char* value = pvalue;
1662 HttpContext* context = arg;
1666 WINPR_ASSERT(value);
1668 return http_context_set_cookie(context, key, value);
1671BOOL http_response_extract_cookies(
const HttpResponse* response, HttpContext* context)
1673 WINPR_ASSERT(response);
1674 WINPR_ASSERT(context);
1676 return HashTable_Foreach(response->SetCookie, extract_cookie, context);
1679FREERDP_LOCAL BOOL http_context_set_header(HttpContext* context,
const char* key,
const char* value,
1682 WINPR_ASSERT(context);
1683 va_list ap = WINPR_C_ARRAY_INIT;
1684 va_start(ap, value);
1685 const BOOL rc = http_context_set_header_va(context, key, value, ap);
1690BOOL http_request_set_header(HttpRequest* request,
const char* key,
const char* value, ...)
1692 WINPR_ASSERT(request);
1695 va_list ap = WINPR_C_ARRAY_INIT;
1696 va_start(ap, value);
1697 winpr_vasprintf(&v, &vlen, value, ap);
1699 const BOOL rc = HashTable_Insert(request->headers, key, v);
1704BOOL http_context_set_header_va(HttpContext* context,
const char* key,
const char* value,
1709 winpr_vasprintf(&v, &vlen, value, ap);
1710 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