| 1 | #include "http.h" |
| 2 | |
| 3 | #include <base/dbg.h> |
| 4 | #include <base/fs.h> |
| 5 | #include <base/io.h> |
| 6 | #include <base/log.h> |
| 7 | #include <base/mem.h> |
| 8 | #include <base/str.h> |
| 9 | |
| 10 | #include <engine/external/json-parser/json.h> |
| 11 | #include <engine/shared/config.h> |
| 12 | #include <engine/shared/json.h> |
| 13 | #include <engine/storage.h> |
| 14 | |
| 15 | #include <game/version.h> |
| 16 | |
| 17 | #include <algorithm> |
| 18 | |
| 19 | IHttpRequest::IHttpRequest(const char *pUrl) |
| 20 | { |
| 21 | str_copy(dst&: m_aUrl, src: pUrl); |
| 22 | sha256_init(ctxt: &m_ActualSha256Ctx); |
| 23 | } |
| 24 | |
| 25 | IHttpRequest::~IHttpRequest() |
| 26 | { |
| 27 | dbg_assert(m_File == nullptr, "HTTP request file was not closed" ); |
| 28 | free(ptr: m_pBody); |
| 29 | free(ptr: m_pBuffer); |
| 30 | if(m_State == EHttpState::DONE && m_ValidateBeforeOverwrite) |
| 31 | { |
| 32 | OnValidation(Success: false); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | void IHttpRequest::WriteToMemory() |
| 37 | { |
| 38 | m_WriteToMemory = true; |
| 39 | m_WriteToFile = false; |
| 40 | } |
| 41 | |
| 42 | void IHttpRequest::WriteToFile(IStorage *pStorage, const char *pDest, int StorageType) |
| 43 | { |
| 44 | m_WriteToMemory = false; |
| 45 | m_WriteToFile = true; |
| 46 | str_copy(dst&: m_aDest, src: pDest); |
| 47 | if(StorageType == -2) |
| 48 | { |
| 49 | pStorage->GetBinaryPath(pFilename: m_aDest, pBuffer: m_aDestAbsolute, BufferSize: sizeof(m_aDestAbsolute)); |
| 50 | } |
| 51 | else |
| 52 | { |
| 53 | pStorage->GetCompletePath(Type: StorageType, pDir: m_aDest, pBuffer: m_aDestAbsolute, BufferSize: sizeof(m_aDestAbsolute)); |
| 54 | } |
| 55 | IStorage::FormatTmpPath(aBuf: m_aDestAbsoluteTmp, BufSize: sizeof(m_aDestAbsoluteTmp), pPath: m_aDestAbsolute); |
| 56 | } |
| 57 | |
| 58 | void IHttpRequest::WriteToFileAndMemory(IStorage *pStorage, const char *pDest, int StorageType) |
| 59 | { |
| 60 | WriteToFile(pStorage, pDest, StorageType); |
| 61 | m_WriteToMemory = true; |
| 62 | } |
| 63 | |
| 64 | void IHttpRequest::Head() |
| 65 | { |
| 66 | m_Type = REQUEST::HEAD; |
| 67 | } |
| 68 | |
| 69 | void IHttpRequest::Post(const unsigned char *pData, size_t DataLength) |
| 70 | { |
| 71 | m_Type = REQUEST::POST; |
| 72 | m_BodyLength = DataLength; |
| 73 | m_pBody = (unsigned char *)malloc(size: std::max(a: (size_t)1, b: DataLength)); |
| 74 | mem_copy(dest: m_pBody, source: pData, size: DataLength); |
| 75 | } |
| 76 | |
| 77 | void IHttpRequest::PostJson(const char *pJson) |
| 78 | { |
| 79 | m_Type = REQUEST::POST_JSON; |
| 80 | m_BodyLength = str_length(str: pJson); |
| 81 | m_pBody = (unsigned char *)malloc(size: m_BodyLength); |
| 82 | mem_copy(dest: m_pBody, source: pJson, size: m_BodyLength); |
| 83 | } |
| 84 | |
| 85 | void IHttpRequest::(const char *pName, const char *pValue) |
| 86 | { |
| 87 | char [256]; |
| 88 | str_format(buffer: aHeader, buffer_size: sizeof(aHeader), format: "%s: %s" , pName, pValue); |
| 89 | Header(pNameColonValue: aHeader); |
| 90 | } |
| 91 | |
| 92 | void IHttpRequest::(const char *pName, int Value) |
| 93 | { |
| 94 | char [256]; |
| 95 | str_format(buffer: aHeader, buffer_size: sizeof(aHeader), format: "%s: %d" , pName, Value); |
| 96 | Header(pNameColonValue: aHeader); |
| 97 | } |
| 98 | |
| 99 | const char *IHttpRequest::Dest() const |
| 100 | { |
| 101 | if(m_WriteToFile) |
| 102 | { |
| 103 | return m_aDest; |
| 104 | } |
| 105 | else |
| 106 | { |
| 107 | return nullptr; |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | void IHttpRequest::Wait() |
| 112 | { |
| 113 | std::unique_lock Lock(m_WaitMutex); |
| 114 | m_WaitCondition.wait(lock&: Lock, p: [this]() { |
| 115 | EHttpState State = m_State.load(m: std::memory_order_seq_cst); |
| 116 | return State != EHttpState::QUEUED && State != EHttpState::RUNNING; |
| 117 | }); |
| 118 | } |
| 119 | |
| 120 | void IHttpRequest::OnValidation(bool Success) |
| 121 | { |
| 122 | dbg_assert(m_ValidateBeforeOverwrite, "this function is illegal to call without having set ValidateBeforeOverwrite" ); |
| 123 | m_ValidateBeforeOverwrite = false; |
| 124 | if(Success) |
| 125 | { |
| 126 | if(m_StatusCode == 304) // 304 Not Modified |
| 127 | { |
| 128 | if(m_IfModifiedSince < 0) |
| 129 | { |
| 130 | log_error("http" , "got unexpected '304 Not Modified' status: %s" , m_aDest); |
| 131 | m_State = EHttpState::ERROR; |
| 132 | } |
| 133 | (void)fs_remove(filename: m_aDestAbsoluteTmp); |
| 134 | return; |
| 135 | } |
| 136 | if(fs_rename(oldname: m_aDestAbsoluteTmp, newname: m_aDestAbsolute)) |
| 137 | { |
| 138 | log_error("http" , "i/o error, cannot move file: %s" , m_aDest); |
| 139 | m_State = EHttpState::ERROR; |
| 140 | (void)fs_remove(filename: m_aDestAbsoluteTmp); |
| 141 | } |
| 142 | } |
| 143 | else |
| 144 | { |
| 145 | m_State = EHttpState::ERROR; |
| 146 | (void)fs_remove(filename: m_aDestAbsoluteTmp); |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | void IHttpRequest::Result(unsigned char **ppResult, size_t *pResultLength) const |
| 151 | { |
| 152 | dbg_assert(State() == EHttpState::DONE, "Request not done" ); |
| 153 | dbg_assert(m_WriteToMemory, "Result only usable when written to memory" ); |
| 154 | *ppResult = m_pBuffer; |
| 155 | *pResultLength = m_ResponseLength; |
| 156 | } |
| 157 | |
| 158 | json_value *IHttpRequest::ResultJson() const |
| 159 | { |
| 160 | unsigned char *pResult; |
| 161 | size_t ResultLength; |
| 162 | Result(ppResult: &pResult, pResultLength: &ResultLength); |
| 163 | return JsonParse(pJson: (char *)pResult, Length: ResultLength); |
| 164 | } |
| 165 | |
| 166 | const SHA256_DIGEST &IHttpRequest::ResultSha256() const |
| 167 | { |
| 168 | dbg_assert(State() == EHttpState::DONE, "Request not done" ); |
| 169 | dbg_assert(m_ActualSha256.has_value(), "Result SHA256 missing" ); |
| 170 | return m_ActualSha256.value(); |
| 171 | } |
| 172 | |
| 173 | int IHttpRequest::StatusCode() const |
| 174 | { |
| 175 | dbg_assert(State() == EHttpState::DONE, "Request not done" ); |
| 176 | return m_StatusCode; |
| 177 | } |
| 178 | |
| 179 | std::optional<int64_t> IHttpRequest::ResultAgeSeconds() const |
| 180 | { |
| 181 | dbg_assert(State() == EHttpState::DONE, "Request not done" ); |
| 182 | if(!m_ResultDate || !m_ResultLastModified) |
| 183 | { |
| 184 | return {}; |
| 185 | } |
| 186 | return *m_ResultDate - *m_ResultLastModified; |
| 187 | } |
| 188 | |
| 189 | std::optional<int64_t> IHttpRequest::ResultLastModified() const |
| 190 | { |
| 191 | dbg_assert(State() == EHttpState::DONE, "Request not done" ); |
| 192 | return m_ResultLastModified; |
| 193 | } |
| 194 | |
| 195 | static bool CalculateSha256(const char *pAbsoluteFilename, SHA256_DIGEST *pSha256) |
| 196 | { |
| 197 | IOHANDLE File = io_open(filename: pAbsoluteFilename, flags: IOFLAG_READ); |
| 198 | if(!File) |
| 199 | { |
| 200 | return false; |
| 201 | } |
| 202 | SHA256_CTX Sha256Ctxt; |
| 203 | sha256_init(ctxt: &Sha256Ctxt); |
| 204 | unsigned char aBuffer[64 * 1024]; |
| 205 | while(true) |
| 206 | { |
| 207 | unsigned Bytes = io_read(io: File, buffer: aBuffer, size: sizeof(aBuffer)); |
| 208 | if(Bytes == 0) |
| 209 | break; |
| 210 | sha256_update(ctxt: &Sha256Ctxt, data: aBuffer, data_len: Bytes); |
| 211 | } |
| 212 | io_close(io: File); |
| 213 | *pSha256 = sha256_finish(ctxt: &Sha256Ctxt); |
| 214 | return true; |
| 215 | } |
| 216 | |
| 217 | const char *const IHttpRequest::USER_AGENT_STRING = GAME_NAME " " GAME_RELEASE_VERSION " (" CONF_PLATFORM_STRING "; " CONF_ARCH_STRING ")" ; |
| 218 | |
| 219 | const char *IHttpRequest::GetRequestType(REQUEST Type) |
| 220 | { |
| 221 | switch(Type) |
| 222 | { |
| 223 | case REQUEST::GET: |
| 224 | return "GET" ; |
| 225 | case REQUEST::HEAD: |
| 226 | return "HEAD" ; |
| 227 | case REQUEST::POST: |
| 228 | case REQUEST::POST_JSON: |
| 229 | return "POST" ; |
| 230 | default: |
| 231 | dbg_assert_failed("Invalid Type: %d" , (int)Type); |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | bool IHttpRequest::ShouldSkipRequest() |
| 236 | { |
| 237 | if(m_WriteToFile && m_ExpectedSha256.has_value()) |
| 238 | { |
| 239 | SHA256_DIGEST Sha256; |
| 240 | if(CalculateSha256(pAbsoluteFilename: m_aDestAbsolute, pSha256: &Sha256) && Sha256 == m_ExpectedSha256.value()) |
| 241 | { |
| 242 | log_debug("http" , "skipping download because expected file already exists: %s" , m_aDest); |
| 243 | return true; |
| 244 | } |
| 245 | } |
| 246 | return false; |
| 247 | } |
| 248 | |
| 249 | bool IHttpRequest::BeforeInit() |
| 250 | { |
| 251 | if(m_WriteToFile) |
| 252 | { |
| 253 | if(m_SkipByFileTime) |
| 254 | { |
| 255 | time_t FileCreatedTime, FileModifiedTime; |
| 256 | if(fs_file_time(name: m_aDestAbsolute, created: &FileCreatedTime, modified: &FileModifiedTime) == 0) |
| 257 | { |
| 258 | m_IfModifiedSince = FileModifiedTime; |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | if(fs_makedir_rec_for(path: m_aDestAbsoluteTmp) < 0) |
| 263 | { |
| 264 | log_error("http" , "i/o error, cannot create folder for: %s" , m_aDest); |
| 265 | return false; |
| 266 | } |
| 267 | |
| 268 | m_File = io_open(filename: m_aDestAbsoluteTmp, flags: IOFLAG_WRITE); |
| 269 | if(!m_File) |
| 270 | { |
| 271 | log_error("http" , "i/o error, cannot open file: %s" , m_aDest); |
| 272 | return false; |
| 273 | } |
| 274 | } |
| 275 | return true; |
| 276 | } |
| 277 | |
| 278 | size_t IHttpRequest::OnData(const char *pData, size_t DataSize) |
| 279 | { |
| 280 | // Need to check for the maximum response size here as implementation may not support it, |
| 281 | // e.g. curl can only guarantee it if the server sets a Content-Length header. |
| 282 | if(m_MaxResponseSize >= 0 && m_ResponseLength + DataSize > (uint64_t)m_MaxResponseSize) |
| 283 | { |
| 284 | return 0; |
| 285 | } |
| 286 | |
| 287 | if(DataSize == 0) |
| 288 | { |
| 289 | return DataSize; |
| 290 | } |
| 291 | |
| 292 | sha256_update(ctxt: &m_ActualSha256Ctx, data: pData, data_len: DataSize); |
| 293 | |
| 294 | size_t Result = DataSize; |
| 295 | |
| 296 | if(m_WriteToMemory) |
| 297 | { |
| 298 | size_t NewBufferSize = std::max(a: (size_t)1024, b: m_BufferSize); |
| 299 | while(m_ResponseLength + DataSize > NewBufferSize) |
| 300 | { |
| 301 | NewBufferSize *= 2; |
| 302 | } |
| 303 | if(NewBufferSize != m_BufferSize) |
| 304 | { |
| 305 | m_pBuffer = (unsigned char *)realloc(ptr: m_pBuffer, size: NewBufferSize); |
| 306 | m_BufferSize = NewBufferSize; |
| 307 | } |
| 308 | mem_copy(dest: m_pBuffer + m_ResponseLength, source: pData, size: DataSize); |
| 309 | } |
| 310 | if(m_WriteToFile) |
| 311 | { |
| 312 | Result = io_write(io: m_File, buffer: pData, size: DataSize); |
| 313 | } |
| 314 | m_ResponseLength += DataSize; |
| 315 | return Result; |
| 316 | } |
| 317 | |
| 318 | void IHttpRequest::OnCompletionInternal(EHttpState State) |
| 319 | { |
| 320 | if(State == EHttpState::DONE) |
| 321 | { |
| 322 | m_ActualSha256 = sha256_finish(ctxt: &m_ActualSha256Ctx); |
| 323 | if(m_ExpectedSha256.has_value() && m_ActualSha256.value() != m_ExpectedSha256.value()) |
| 324 | { |
| 325 | if(g_Config.m_DbgHttp || m_LogProgress >= HTTPLOG::FAILURE) |
| 326 | { |
| 327 | char aActualSha256[SHA256_MAXSTRSIZE]; |
| 328 | sha256_str(digest: m_ActualSha256.value(), str: aActualSha256, max_len: sizeof(aActualSha256)); |
| 329 | char aExpectedSha256[SHA256_MAXSTRSIZE]; |
| 330 | sha256_str(digest: m_ExpectedSha256.value(), str: aExpectedSha256, max_len: sizeof(aExpectedSha256)); |
| 331 | log_error("http" , "SHA256 mismatch: got=%s, expected=%s, url=%s" , aActualSha256, aExpectedSha256, m_aUrl); |
| 332 | } |
| 333 | State = EHttpState::ERROR; |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | if(m_WriteToFile) |
| 338 | { |
| 339 | if(m_File && io_close(io: m_File) != 0) |
| 340 | { |
| 341 | log_error("http" , "i/o error, cannot close file: %s" , m_aDest); |
| 342 | State = EHttpState::ERROR; |
| 343 | } |
| 344 | m_File = nullptr; |
| 345 | |
| 346 | if(State == EHttpState::ERROR || State == EHttpState::ABORTED) |
| 347 | { |
| 348 | (void)fs_remove(filename: m_aDestAbsoluteTmp); |
| 349 | } |
| 350 | else if(m_StatusCode == 304) // 304 Not Modified |
| 351 | { |
| 352 | (void)fs_remove(filename: m_aDestAbsoluteTmp); |
| 353 | if(m_IfModifiedSince < 0) |
| 354 | { |
| 355 | log_error("http" , "got unexpected '304 Not Modified' status: %s" , m_aDest); |
| 356 | State = EHttpState::ERROR; |
| 357 | } |
| 358 | else if(m_WriteToMemory) |
| 359 | { |
| 360 | free(ptr: m_pBuffer); |
| 361 | m_pBuffer = nullptr; |
| 362 | m_ResponseLength = 0; |
| 363 | void *pBuffer; |
| 364 | unsigned Length; |
| 365 | IOHANDLE File = io_open(filename: m_aDestAbsolute, flags: IOFLAG_READ); |
| 366 | bool Success = File && io_read_all(io: File, result: &pBuffer, result_len: &Length); |
| 367 | if(File) |
| 368 | { |
| 369 | io_close(io: File); |
| 370 | } |
| 371 | if(Success) |
| 372 | { |
| 373 | m_pBuffer = (unsigned char *)pBuffer; |
| 374 | m_ResponseLength = Length; |
| 375 | } |
| 376 | else |
| 377 | { |
| 378 | log_error("http" , "i/o error, cannot read existing file: %s" , m_aDest); |
| 379 | State = EHttpState::ERROR; |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | else if(!m_ValidateBeforeOverwrite) |
| 384 | { |
| 385 | if(fs_rename(oldname: m_aDestAbsoluteTmp, newname: m_aDestAbsolute)) |
| 386 | { |
| 387 | log_error("http" , "i/o error, cannot move file: %s" , m_aDest); |
| 388 | State = EHttpState::ERROR; |
| 389 | (void)fs_remove(filename: m_aDestAbsoluteTmp); |
| 390 | } |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | // The globally visible state must be updated after OnCompletion has finished, |
| 395 | // or other threads may try to access the result of a completed HTTP request, |
| 396 | // before the result has been initialized/updated in OnCompletion. |
| 397 | if(m_pProgressCallback != nullptr) |
| 398 | { |
| 399 | m_pProgressCallback->OnCompletion(State); |
| 400 | } |
| 401 | { |
| 402 | std::unique_lock WaitLock(m_WaitMutex); |
| 403 | m_State = State; |
| 404 | } |
| 405 | m_WaitCondition.notify_all(); |
| 406 | } |
| 407 | |