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)
330 GUID RdgConnectionId;
331 if (UuidCreate(&RdgConnectionId) != RPC_S_OK)
334 char buffer[64] = WINPR_C_ARRAY_INIT;
335 return http_context_set_header(context,
"RDG-Connection-Id",
"{%s}",
336 guid2str(&RdgConnectionId, buffer,
sizeof(buffer)));
339BOOL http_context_set_rdg_correlation_id(HttpContext* context,
const GUID* RdgCorrelationId)
341 if (!context || !RdgCorrelationId)
344 char buffer[64] = WINPR_C_ARRAY_INIT;
345 return http_context_set_header(context,
"RDG-Correlation-Id",
"{%s}",
346 guid2str(RdgCorrelationId, buffer,
sizeof(buffer)));
349BOOL http_context_enable_websocket_upgrade(HttpContext* context, BOOL enable)
351 WINPR_ASSERT(context);
355 GUID key = WINPR_C_ARRAY_INIT;
356 if (RPC_S_OK != UuidCreate(&key))
359 free(context->SecWebsocketKey);
360 context->SecWebsocketKey = crypto_base64_encode((BYTE*)&key,
sizeof(key));
361 if (!context->SecWebsocketKey)
365 context->websocketUpgrade = enable;
369BOOL http_context_is_websocket_upgrade_enabled(HttpContext* context)
371 return context->websocketUpgrade;
374BOOL http_context_set_rdg_auth_scheme(HttpContext* context,
const char* RdgAuthScheme)
376 if (!context || !RdgAuthScheme)
379 return http_context_set_header(context,
"RDG-Auth-Scheme",
"%s", RdgAuthScheme);
382BOOL http_context_set_cookie(HttpContext* context,
const char* CookieName,
const char* CookieValue)
384 if (!context || !CookieName || !CookieValue)
386 if (ListDictionary_Contains(context->cookies, CookieName))
388 if (!ListDictionary_SetItemValue(context->cookies, CookieName, CookieValue))
393 if (!ListDictionary_Add(context->cookies, CookieName, CookieValue))
399void http_context_free(HttpContext* context)
403 free(context->SecWebsocketKey);
405 free(context->Method);
406 free(context->Connection);
407 free(context->Pragma);
408 HashTable_Free(context->headers);
409 ListDictionary_Free(context->cookies);
414BOOL http_request_set_method(HttpRequest* request,
const char* Method)
416 if (!request || !Method)
419 free(request->Method);
420 request->Method = _strdup(Method);
422 return (request->Method !=
nullptr);
425BOOL http_request_set_uri(HttpRequest* request,
const char* URI)
427 if (!request || !URI)
431 request->URI = _strdup(URI);
433 return (request->URI !=
nullptr);
436BOOL http_request_set_auth_scheme(HttpRequest* request,
const char* AuthScheme)
438 if (!request || !AuthScheme)
441 free(request->AuthScheme);
442 request->AuthScheme = _strdup(AuthScheme);
444 return (request->AuthScheme !=
nullptr);
447BOOL http_request_set_auth_param(HttpRequest* request,
const char* AuthParam)
449 if (!request || !AuthParam)
452 free(request->AuthParam);
453 request->AuthParam = _strdup(AuthParam);
455 return (request->AuthParam !=
nullptr);
458BOOL http_request_set_transfer_encoding(HttpRequest* request, TRANSFER_ENCODING TransferEncoding)
460 if (!request || TransferEncoding == TransferEncodingUnknown)
463 request->TransferEncoding = TransferEncoding;
468WINPR_ATTR_FORMAT_ARG(2, 3)
469static BOOL http_encode_print(
wStream* s, WINPR_FORMAT_ARG const
char* fmt, ...)
472 va_list ap = WINPR_C_ARRAY_INIT;
480 length = vsnprintf(
nullptr, 0, fmt, ap) + 1;
483 if (!Stream_EnsureRemainingCapacity(s, (
size_t)length))
486 str = (
char*)Stream_Pointer(s);
488 used = vsnprintf(str, (
size_t)length, fmt, ap);
492 if ((used + 1) != length)
495 Stream_Seek(s, (
size_t)used);
499static BOOL http_encode_body_line(
wStream* s,
const char* param,
const char* value)
501 if (!s || !param || !value)
504 return http_encode_print(s,
"%s: %s\r\n", param, value);
507static BOOL http_encode_content_length_line(
wStream* s,
size_t ContentLength)
509 return http_encode_print(s,
"Content-Length: %" PRIuz
"\r\n", ContentLength);
512static BOOL http_encode_header_line(
wStream* s,
const char* Method,
const char* URI)
514 if (!s || !Method || !URI)
517 return http_encode_print(s,
"%s %s HTTP/1.1\r\n", Method, URI);
520static BOOL http_encode_authorization_line(
wStream* s,
const char* AuthScheme,
521 const char* AuthParam)
523 if (!s || !AuthScheme || !AuthParam)
526 return http_encode_print(s,
"Authorization: %s %s\r\n", AuthScheme, AuthParam);
529static BOOL http_encode_cookie_line(
wStream* s, wListDictionary* cookies)
531 ULONG_PTR* keys =
nullptr;
537 ListDictionary_Lock(cookies);
538 const size_t count = ListDictionary_GetKeys(cookies, &keys);
543 status = http_encode_print(s,
"Cookie: ");
547 for (
size_t x = 0; status && x < count; x++)
549 char* cur = (
char*)ListDictionary_GetItemValue(cookies, (
void*)keys[x]);
557 status = http_encode_print(s,
"; ");
561 status = http_encode_print(s,
"%s=%s", (
char*)keys[x], cur);
564 status = http_encode_print(s,
"\r\n");
567 ListDictionary_Unlock(cookies);
571static BOOL write_headers(
const void* pkey,
void* pvalue,
void* arg)
573 const char* key = pkey;
574 const char* value = pvalue;
581 return http_encode_body_line(s, key, value);
584wStream* http_request_write(HttpContext* context, HttpRequest* request)
586 if (!context || !request)
589 wStream* s = Stream_New(
nullptr, 1024);
594 if (!http_encode_header_line(s, request->Method, request->URI) ||
596 !http_encode_body_line(s,
"Pragma", context->Pragma))
599 if (!context->websocketUpgrade)
601 if (!http_encode_body_line(s,
"Connection", context->Connection))
606 if (!http_encode_body_line(s,
"Connection",
"Upgrade") ||
607 !http_encode_body_line(s,
"Upgrade",
"websocket") ||
608 !http_encode_body_line(s,
"Sec-Websocket-Version",
"13") ||
609 !http_encode_body_line(s,
"Sec-Websocket-Key", context->SecWebsocketKey))
613 if (request->TransferEncoding != TransferEncodingIdentity)
615 if (request->TransferEncoding == TransferEncodingChunked)
617 if (!http_encode_body_line(s,
"Transfer-Encoding",
"chunked"))
625 if (!http_encode_content_length_line(s, request->ContentLength))
629 if (!utils_str_is_empty(request->Authorization))
631 if (!http_encode_body_line(s,
"Authorization", request->Authorization))
634 else if (!utils_str_is_empty(request->AuthScheme) && !utils_str_is_empty(request->AuthParam))
636 if (!http_encode_authorization_line(s, request->AuthScheme, request->AuthParam))
640 if (!HashTable_Foreach(context->headers, write_headers, s))
643 if (!HashTable_Foreach(request->headers, write_headers, s))
646 if (!http_encode_cookie_line(s, context->cookies))
649 if (!http_encode_print(s,
"\r\n"))
652 Stream_SealLength(s);
655 Stream_Free(s, TRUE);
659HttpRequest* http_request_new(
void)
661 HttpRequest* request = (HttpRequest*)calloc(1,
sizeof(HttpRequest));
665 request->headers = HashTable_New_String();
666 if (!request->headers)
668 request->TransferEncoding = TransferEncodingIdentity;
671 http_request_free(request);
675void http_request_free(HttpRequest* request)
680 free(request->AuthParam);
681 free(request->AuthScheme);
682 free(request->Authorization);
683 free(request->Method);
685 HashTable_Free(request->headers);
689static BOOL http_response_parse_header_status_line(HttpResponse* response,
const char* status_line)
692 char* separator =
nullptr;
693 char* status_code =
nullptr;
699 separator = strchr(status_line,
' ');
704 status_code = separator + 1;
705 separator = strchr(status_code,
' ');
711 const char* reason_phrase = separator + 1;
715 long val = strtol(status_code,
nullptr, 0);
717 if ((errno != 0) || (val < 0) || (val > INT16_MAX))
720 response->StatusCode = (UINT16)val;
722 free(response->ReasonPhrase);
723 response->ReasonPhrase = _strdup(reason_phrase);
726 if (!response->ReasonPhrase)
734 WLog_ERR(TAG,
"http_response_parse_header_status_line failed [%s]", status_line);
739static BOOL http_response_parse_header_field(HttpResponse* response,
const char* name,
742 WINPR_ASSERT(response);
747 if (_stricmp(name,
"Content-Length") == 0)
749 unsigned long long val = 0;
751 val = _strtoui64(value,
nullptr, 0);
753 if ((errno != 0) || (val > INT32_MAX))
756 response->ContentLength = WINPR_ASSERTING_INT_CAST(
size_t, val);
760 if (_stricmp(name,
"Content-Type") == 0)
762 free(response->ContentType);
763 response->ContentType = _strdup(value);
765 return response->ContentType !=
nullptr;
768 if (_stricmp(name,
"Transfer-Encoding") == 0)
770 if (_stricmp(value,
"identity") == 0)
771 response->TransferEncoding = TransferEncodingIdentity;
772 else if (_stricmp(value,
"chunked") == 0)
773 response->TransferEncoding = TransferEncodingChunked;
775 response->TransferEncoding = TransferEncodingUnknown;
780 if (_stricmp(name,
"Sec-WebSocket-Version") == 0)
782 free(response->SecWebsocketVersion);
783 response->SecWebsocketVersion = _strdup(value);
785 return response->SecWebsocketVersion !=
nullptr;
788 if (_stricmp(name,
"Sec-WebSocket-Accept") == 0)
790 free(response->SecWebsocketAccept);
791 response->SecWebsocketAccept = _strdup(value);
793 return response->SecWebsocketAccept !=
nullptr;
796 if (_stricmp(name,
"WWW-Authenticate") == 0)
798 const char* authScheme = value;
799 const char* authValue =
"";
800 char* separator = strchr(value,
' ');
811 authValue = separator + 1;
814 return HashTable_Insert(response->Authenticates, authScheme, authValue);
817 if (_stricmp(name,
"Set-Cookie") == 0)
819 char* separator = strchr(value,
'=');
829 const char* CookieName = value;
830 char* CookieValue = separator + 1;
832 if (*CookieValue ==
'"')
834 char* p = CookieValue;
835 while (*p !=
'"' && *p !=
'\0')
845 char* p = CookieValue;
846 while (*p !=
';' && *p !=
'\0' && *p !=
' ')
852 return HashTable_Insert(response->SetCookie, CookieName, CookieValue);
859static BOOL http_response_parse_header(HttpResponse* response)
863 char* line =
nullptr;
864 char* name =
nullptr;
865 char* colon_pos =
nullptr;
866 char* end_of_header =
nullptr;
867 char end_of_header_char = 0;
872 if (!response->lines)
875 if (!http_response_parse_header_status_line(response, response->lines[0]))
878 for (
size_t count = 1; count < response->count; count++)
880 line = response->lines[count];
892 colon_pos = strchr(line,
':');
896 if ((colon_pos ==
nullptr) || (colon_pos == line))
900 for (end_of_header = colon_pos; end_of_header != line; end_of_header--)
902 c = end_of_header[-1];
904 if (c !=
' ' && c !=
'\t' && c !=
':')
908 if (end_of_header == line)
911 end_of_header_char = *end_of_header;
912 *end_of_header =
'\0';
916 char* value = colon_pos + 1;
917 for (; *value; value++)
919 if ((*value !=
' ') && (*value !=
'\t'))
923 const int res = http_response_parse_header_field(response, name, value);
924 *end_of_header = end_of_header_char;
933 WLog_ERR(TAG,
"parsing failed");
938static void http_response_print(wLog* log, DWORD level,
const HttpResponse* response,
939 const char* file,
size_t line,
const char* fkt)
941 char buffer[64] = WINPR_C_ARRAY_INIT;
944 WINPR_ASSERT(response);
946 if (!WLog_IsLevelActive(log, level))
949 const long status = http_response_get_status_code(response);
950 WLog_PrintTextMessage(log, level, line, file, fkt,
"HTTP status: %s",
951 freerdp_http_status_string_format(status, buffer, ARRAYSIZE(buffer)));
953 if (WLog_IsLevelActive(log, WLOG_DEBUG))
955 for (
size_t i = 0; i < response->count; i++)
956 WLog_PrintTextMessage(log, WLOG_DEBUG, line, file, fkt,
"[%" PRIuz
"] %s", i,
960 if (response->ReasonPhrase)
961 WLog_PrintTextMessage(log, level, line, file, fkt,
"[reason] %s", response->ReasonPhrase);
963 if (WLog_IsLevelActive(log, WLOG_TRACE))
965 WLog_PrintTextMessage(log, WLOG_TRACE, line, file, fkt,
"[body][%" PRIuz
"] %s",
966 response->BodyLength, response->BodyContent);
970static BOOL http_use_content_length(
const char* cur)
977 if (_strnicmp(cur,
"application/rpc", 15) == 0)
979 else if (_strnicmp(cur,
"text/plain", 10) == 0)
981 else if (_strnicmp(cur,
"text/html", 9) == 0)
983 else if (_strnicmp(cur,
"application/json", 16) == 0)
1007static int print_bio_error(
const char* str,
size_t len,
void* bp)
1012 WLog_Print(log, WLOG_ERROR,
"%s", str);
1013 if (len > INT32_MAX)
1018int http_chuncked_read(BIO* bio, BYTE* pBuffer,
size_t size,
1022 int effectiveDataLen = 0;
1024 WINPR_ASSERT(pBuffer);
1025 WINPR_ASSERT(encodingContext !=
nullptr);
1026 WINPR_ASSERT(size <= INT32_MAX);
1029 switch (encodingContext->state)
1031 case ChunkStateData:
1034 (size > encodingContext->nextOffset ? encodingContext->nextOffset : size);
1039 status = BIO_read(bio, pBuffer, (
int)rd);
1041 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1043 encodingContext->nextOffset -= WINPR_ASSERTING_INT_CAST(uint32_t, status);
1044 if (encodingContext->nextOffset == 0)
1046 encodingContext->state = ChunkStateFooter;
1047 encodingContext->headerFooterPos = 0;
1049 effectiveDataLen += status;
1051 if ((
size_t)status == size)
1052 return effectiveDataLen;
1055 size -= (size_t)status;
1058 case ChunkStateFooter:
1060 char _dummy[2] = WINPR_C_ARRAY_INIT;
1061 WINPR_ASSERT(encodingContext->nextOffset == 0);
1062 WINPR_ASSERT(encodingContext->headerFooterPos < 2);
1064 status = BIO_read(bio, _dummy, (
int)(2 - encodingContext->headerFooterPos));
1067 encodingContext->headerFooterPos += (size_t)status;
1068 if (encodingContext->headerFooterPos == 2)
1070 encodingContext->state = ChunkStateLenghHeader;
1071 encodingContext->headerFooterPos = 0;
1075 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1078 case ChunkStateLenghHeader:
1080 BOOL _haveNewLine = FALSE;
1081 char* dst = &encodingContext->lenBuffer[encodingContext->headerFooterPos];
1082 WINPR_ASSERT(encodingContext->nextOffset == 0);
1083 while (encodingContext->headerFooterPos < 10 && !_haveNewLine)
1086 status = BIO_read(bio, dst, 1);
1090 _haveNewLine = TRUE;
1091 encodingContext->headerFooterPos += (size_t)status;
1095 return (effectiveDataLen > 0 ? effectiveDataLen : status);
1101 size_t tmp = strtoul(encodingContext->lenBuffer,
nullptr, 16);
1102 if ((errno != 0) || (tmp > SIZE_MAX))
1105 encodingContext->nextOffset = 0;
1106 encodingContext->state = ChunkStateEnd;
1109 encodingContext->nextOffset = tmp;
1110 encodingContext->state = ChunkStateData;
1112 if (encodingContext->nextOffset == 0)
1114 WLog_DBG(TAG,
"chunked encoding end of stream received");
1115 encodingContext->headerFooterPos = 0;
1116 encodingContext->state = ChunkStateEnd;
1117 return (effectiveDataLen > 0 ? effectiveDataLen : 0);
1128#define sleep_or_timeout(tls, startMS, timeoutMS) \
1129 sleep_or_timeout_((tls), (startMS), (timeoutMS), __FILE__, __func__, __LINE__)
1130static BOOL sleep_or_timeout_(rdpTls* tls, UINT64 startMS, UINT32 timeoutMS,
const char* file,
1131 const char* fkt,
size_t line)
1136 const UINT64 nowMS = GetTickCount64();
1137 if (nowMS - startMS > timeoutMS)
1139 DWORD level = WLOG_ERROR;
1140 wLog* log = WLog_Get(TAG);
1141 if (WLog_IsLevelActive(log, level))
1142 WLog_PrintTextMessage(log, level, line, file, fkt,
"timeout [%" PRIu32
"ms] exceeded",
1146 if (!BIO_should_retry(tls->bio))
1148 DWORD level = WLOG_ERROR;
1149 wLog* log = WLog_Get(TAG);
1150 if (WLog_IsLevelActive(log, level))
1152 WLog_PrintTextMessage(log, level, line, file, fkt,
"Retries exceeded");
1153 ERR_print_errors_cb(print_bio_error, log);
1157 if (freerdp_shall_disconnect_context(tls->context))
1163static SSIZE_T http_response_recv_line(rdpTls* tls, HttpResponse* response)
1166 WINPR_ASSERT(response);
1168 SSIZE_T payloadOffset = -1;
1169 const UINT32 timeoutMS =
1171 const UINT64 startMS = GetTickCount64();
1172 while (payloadOffset <= 0)
1174 size_t bodyLength = 0;
1175 size_t position = 0;
1178 char* end =
nullptr;
1182 status = BIO_read(tls->bio, Stream_Pointer(response->data), 1);
1185 if (sleep_or_timeout(tls, startMS, timeoutMS))
1190#ifdef FREERDP_HAVE_VALGRIND_MEMCHECK_H
1191 VALGRIND_MAKE_MEM_DEFINED(Stream_Pointer(response->data), status);
1193 Stream_Seek(response->data, (
size_t)status);
1195 if (!Stream_EnsureRemainingCapacity(response->data, 1024))
1198 position = Stream_GetPosition(response->data);
1202 else if (position > RESPONSE_SIZE_LIMIT)
1204 WLog_ERR(TAG,
"Request header too large! (%" PRIuz
" bytes) Aborting!", bodyLength);
1210 s = (position > 8) ? 8 : position;
1211 end = (
char*)Stream_Pointer(response->data) - s;
1213 if (string_strnstr(end,
"\r\n\r\n", s) !=
nullptr)
1214 payloadOffset = WINPR_ASSERTING_INT_CAST(SSIZE_T, Stream_GetPosition(response->data));
1218 return payloadOffset;
1221static BOOL http_response_recv_body(rdpTls* tls, HttpResponse* response, BOOL readContentLength,
1222 size_t payloadOffset,
size_t bodyLength)
1227 WINPR_ASSERT(response);
1229 const UINT64 startMS = GetTickCount64();
1230 const UINT32 timeoutMS =
1233 if ((response->TransferEncoding == TransferEncodingChunked) && readContentLength)
1236 ctx.state = ChunkStateLenghHeader;
1238 ctx.headerFooterPos = 0;
1242 if (!Stream_EnsureRemainingCapacity(response->data, 2048))
1245 int status = http_chuncked_read(tls->bio, Stream_Pointer(response->data),
1246 Stream_GetRemainingCapacity(response->data), &ctx);
1249 if (sleep_or_timeout(tls, startMS, timeoutMS))
1254 Stream_Seek(response->data, (
size_t)status);
1257 }
while (ctx.state != ChunkStateEnd);
1258 response->BodyLength = WINPR_ASSERTING_INT_CAST(uint32_t, full_len);
1259 if (response->BodyLength > 0)
1260 response->BodyContent = &(Stream_BufferAs(response->data,
char))[payloadOffset];
1264 while (response->BodyLength < bodyLength)
1268 if (!Stream_EnsureRemainingCapacity(response->data, bodyLength - response->BodyLength))
1272 size_t diff = bodyLength - response->BodyLength;
1273 if (diff > INT32_MAX)
1275 status = BIO_read(tls->bio, Stream_Pointer(response->data), (
int)diff);
1279 if (sleep_or_timeout(tls, startMS, timeoutMS))
1284 Stream_Seek(response->data, (
size_t)status);
1285 response->BodyLength += (
unsigned long)status;
1287 if (response->BodyLength > RESPONSE_SIZE_LIMIT)
1289 WLog_ERR(TAG,
"Request body too large! (%" PRIuz
" bytes) Aborting!",
1290 response->BodyLength);
1295 if (response->BodyLength > 0)
1296 response->BodyContent = &(Stream_BufferAs(response->data,
char))[payloadOffset];
1298 if (bodyLength != response->BodyLength)
1300 WLog_WARN(TAG,
"%s unexpected body length: actual: %" PRIuz
", expected: %" PRIuz,
1301 response->ContentType, response->BodyLength, bodyLength);
1304 response->BodyLength = MIN(bodyLength, response->BodyLength);
1308 if (!Stream_EnsureRemainingCapacity(response->data,
sizeof(UINT16)))
1310 Stream_Write_UINT16(response->data, 0);
1318static void clear_lines(HttpResponse* response)
1320 WINPR_ASSERT(response);
1322 for (
size_t x = 0; x < response->count; x++)
1324 WINPR_ASSERT(response->lines);
1325 char* line = response->lines[x];
1329 free((
void*)response->lines);
1330 response->lines =
nullptr;
1331 response->count = 0;
1334HttpResponse* http_response_recv(rdpTls* tls, BOOL readContentLength)
1336 size_t bodyLength = 0;
1337 HttpResponse* response = http_response_new();
1342 response->ContentLength = 0;
1344 const SSIZE_T payloadOffset = http_response_recv_line(tls, response);
1345 if (payloadOffset < 0)
1351 char* buffer = Stream_BufferAs(response->data,
char);
1352 const char* line = Stream_BufferAs(response->data,
char);
1353 char* context =
nullptr;
1355 while ((line = string_strnstr(line,
"\r\n",
1356 WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset) -
1357 WINPR_ASSERTING_INT_CAST(
size_t, (line - buffer)) - 2UL)))
1363 clear_lines(response);
1364 response->count = count;
1368 response->lines = (
char**)calloc(response->count,
sizeof(
char*));
1370 if (!response->lines)
1374 buffer[payloadOffset - 1] =
'\0';
1375 buffer[payloadOffset - 2] =
'\0';
1377 line = strtok_s(buffer,
"\r\n", &context);
1379 while (line && (response->count > count))
1381 response->lines[count] = _strdup(line);
1382 if (!response->lines[count])
1384 line = strtok_s(
nullptr,
"\r\n", &context);
1388 if (!http_response_parse_header(response))
1391 response->BodyLength =
1392 Stream_GetPosition(response->data) - WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset);
1394 WINPR_ASSERT(response->BodyLength == 0);
1395 bodyLength = response->BodyLength;
1397 if (readContentLength && (response->ContentLength > 0))
1399 const char* cur = response->ContentType;
1401 while (cur !=
nullptr)
1403 if (http_use_content_length(cur))
1405 if (response->ContentLength < RESPONSE_SIZE_LIMIT)
1406 bodyLength = response->ContentLength;
1411 readContentLength = FALSE;
1413 cur = strchr(cur,
';');
1417 if (bodyLength > RESPONSE_SIZE_LIMIT)
1419 WLog_ERR(TAG,
"Expected request body too large! (%" PRIuz
" bytes) Aborting!",
1425 if (!http_response_recv_body(tls, response, readContentLength,
1426 WINPR_ASSERTING_INT_CAST(
size_t, payloadOffset), bodyLength))
1429 Stream_SealLength(response->data);
1432 if (!Stream_EnsureRemainingCapacity(response->data, 2))
1434 Stream_Write_UINT16(response->data, 0);
1438 WLog_ERR(TAG,
"No response");
1439 http_response_free(response);
1443const char* http_response_get_body(
const HttpResponse* response)
1448 return response->BodyContent;
1451wHashTable* HashTable_New_String(
void)
1453 wHashTable* table = HashTable_New(FALSE);
1457 if (!HashTable_SetupForStringData(table, TRUE))
1459 HashTable_Free(table);
1462 HashTable_KeyObject(table)->
fnObjectEquals = strings_equals_nocase;
1463 HashTable_ValueObject(table)->
fnObjectEquals = strings_equals_nocase;
1467HttpResponse* http_response_new(
void)
1469 HttpResponse* response = (HttpResponse*)calloc(1,
sizeof(HttpResponse));
1474 response->Authenticates = HashTable_New_String();
1476 if (!response->Authenticates)
1479 response->SetCookie = HashTable_New_String();
1481 if (!response->SetCookie)
1484 response->data = Stream_New(
nullptr, 2048);
1486 if (!response->data)
1489 response->TransferEncoding = TransferEncodingIdentity;
1492 WINPR_PRAGMA_DIAG_PUSH
1493 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
1494 http_response_free(response);
1495 WINPR_PRAGMA_DIAG_POP
1499void http_response_free(HttpResponse* response)
1504 clear_lines(response);
1505 free(response->ReasonPhrase);
1506 free(response->ContentType);
1507 free(response->SecWebsocketAccept);
1508 free(response->SecWebsocketVersion);
1509 HashTable_Free(response->Authenticates);
1510 HashTable_Free(response->SetCookie);
1511 Stream_Free(response->data, TRUE);
1515const char* http_request_get_uri(HttpRequest* request)
1520 return request->URI;
1523SSIZE_T http_request_get_content_length(HttpRequest* request)
1528 return (SSIZE_T)request->ContentLength;
1531BOOL http_request_set_content_length(HttpRequest* request,
size_t length)
1536 request->ContentLength = length;
1540UINT16 http_response_get_status_code(
const HttpResponse* response)
1542 WINPR_ASSERT(response);
1544 return response->StatusCode;
1547size_t http_response_get_body_length(
const HttpResponse* response)
1549 WINPR_ASSERT(response);
1551 return response->BodyLength;
1554const char* http_response_get_auth_token(
const HttpResponse* response,
const char* method)
1556 if (!response || !method)
1559 return HashTable_GetItemValue(response->Authenticates, method);
1562const char* http_response_get_setcookie(
const HttpResponse* response,
const char* cookie)
1564 if (!response || !cookie)
1567 return HashTable_GetItemValue(response->SetCookie, cookie);
1570TRANSFER_ENCODING http_response_get_transfer_encoding(
const HttpResponse* response)
1573 return TransferEncodingUnknown;
1575 return response->TransferEncoding;
1578BOOL http_response_is_websocket(
const HttpContext* http,
const HttpResponse* response)
1580 BOOL isWebsocket = FALSE;
1581 WINPR_DIGEST_CTX* sha1 =
nullptr;
1582 char* base64accept =
nullptr;
1583 BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH];
1585 if (!http || !response)
1588 if (!http->websocketUpgrade || response->StatusCode != HTTP_STATUS_SWITCH_PROTOCOLS)
1591 if (response->SecWebsocketVersion && _stricmp(response->SecWebsocketVersion,
"13") != 0)
1594 if (!response->SecWebsocketAccept)
1599 sha1 = winpr_Digest_New();
1603 if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1))
1606 if (!winpr_Digest_Update(sha1, (BYTE*)http->SecWebsocketKey, strlen(http->SecWebsocketKey)))
1608 if (!winpr_Digest_Update(sha1, (
const BYTE*)WEBSOCKET_MAGIC_GUID, strlen(WEBSOCKET_MAGIC_GUID)))
1611 if (!winpr_Digest_Final(sha1, sha1_digest,
sizeof(sha1_digest)))
1614 base64accept = crypto_base64_encode(sha1_digest, WINPR_SHA1_DIGEST_LENGTH);
1618 if (_stricmp(response->SecWebsocketAccept, base64accept) != 0)
1620 WLog_WARN(TAG,
"Webserver gave Websocket Upgrade response but sanity check failed");
1625 winpr_Digest_Free(sha1);
1630void http_response_log_error_status_(wLog* log, DWORD level,
const HttpResponse* response,
1631 const char* file,
size_t line,
const char* fkt)
1634 WINPR_ASSERT(response);
1636 if (!WLog_IsLevelActive(log, level))
1639 char buffer[64] = WINPR_C_ARRAY_INIT;
1640 const UINT16 status = http_response_get_status_code(response);
1641 WLog_PrintTextMessage(log, level, line, file, fkt,
"Unexpected HTTP status: %s",
1642 freerdp_http_status_string_format(status, buffer, ARRAYSIZE(buffer)));
1643 http_response_print(log, level, response, file, line, fkt);
1646static BOOL extract_cookie(
const void* pkey,
void* pvalue,
void* arg)
1648 const char* key = pkey;
1649 const char* value = pvalue;
1650 HttpContext* context = arg;
1654 WINPR_ASSERT(value);
1656 return http_context_set_cookie(context, key, value);
1659BOOL http_response_extract_cookies(
const HttpResponse* response, HttpContext* context)
1661 WINPR_ASSERT(response);
1662 WINPR_ASSERT(context);
1664 return HashTable_Foreach(response->SetCookie, extract_cookie, context);
1667FREERDP_LOCAL BOOL http_context_set_header(HttpContext* context,
const char* key,
const char* value,
1670 WINPR_ASSERT(context);
1671 va_list ap = WINPR_C_ARRAY_INIT;
1672 va_start(ap, value);
1673 const BOOL rc = http_context_set_header_va(context, key, value, ap);
1678BOOL http_request_set_header(HttpRequest* request,
const char* key,
const char* value, ...)
1680 WINPR_ASSERT(request);
1683 va_list ap = WINPR_C_ARRAY_INIT;
1684 va_start(ap, value);
1685 winpr_vasprintf(&v, &vlen, value, ap);
1687 const BOOL rc = HashTable_Insert(request->headers, key, v);
1692BOOL http_context_set_header_va(HttpContext* context,
const char* key,
const char* value,
1697 winpr_vasprintf(&v, &vlen, value, ap);
1698 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