/******************************************************************************* The MIT License (MIT) Copyright (c) 2015 Alexander Zolotarev from Minsk, Belarus Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************/ #if ! __has_feature(objc_arc) #error This file must be compiled with ARC. Either turn on ARC for the project or use -fobjc-arc flag #endif #import #import #import #import #import #import #import #import #import #import #include // TARGET_OS_IPHONE #if (TARGET_OS_IPHONE > 0) // Works for all iOS devices, including iPad. extern NSString * gBrowserUserAgent; #endif #include "platform/http_client.hpp" #include "base/logging.hpp" namespace platform { // If we try to upload our data from the background fetch handler on iOS, we have ~30 seconds to do that gracefully. static const double kTimeoutInSeconds = 24.0; // TODO(AlexZ): Rewrite to use async implementation for better redirects handling and ability to cancel request from destructor. bool HttpClient::RunHttpRequest() { NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[NSString stringWithUTF8String:m_urlRequested.c_str()]] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:kTimeoutInSeconds]; // We handle cookies manually. request.HTTPShouldHandleCookies = NO; request.HTTPMethod = [NSString stringWithUTF8String:m_httpMethod.c_str()]; if (!m_contentType.empty()) [request setValue:[NSString stringWithUTF8String:m_contentType.c_str()] forHTTPHeaderField:@"Content-Type"]; if (!m_contentEncoding.empty()) [request setValue:[NSString stringWithUTF8String:m_contentEncoding.c_str()] forHTTPHeaderField:@"Content-Encoding"]; if (!m_userAgent.empty()) [request setValue:[NSString stringWithUTF8String:m_userAgent.c_str()] forHTTPHeaderField:@"User-Agent"]; if (!m_cookies.empty()) [request setValue:[NSString stringWithUTF8String:m_cookies.c_str()] forHTTPHeaderField:@"Cookie"]; #if (TARGET_OS_IPHONE > 0) else if (gBrowserUserAgent) [request setValue:gBrowserUserAgent forHTTPHeaderField:@"User-Agent"]; #endif // TARGET_OS_IPHONE if (!m_basicAuthUser.empty()) { NSData * loginAndPassword = [[NSString stringWithUTF8String:(m_basicAuthUser + ":" + m_basicAuthPassword).c_str()] dataUsingEncoding:NSUTF8StringEncoding]; [request setValue:[NSString stringWithFormat:@"Basic %@", [loginAndPassword base64EncodedStringWithOptions:0]] forHTTPHeaderField:@"Authorization"]; } if (!m_bodyData.empty()) { request.HTTPBody = [NSData dataWithBytes:m_bodyData.data() length:m_bodyData.size()]; if (m_debugMode) LOG(LINFO, ("Uploading buffer of size", m_bodyData.size(), "bytes")); } else if (!m_inputFile.empty()) { NSError * err = nil; NSString * path = [NSString stringWithUTF8String:m_inputFile.c_str()]; const unsigned long long file_size = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&err].fileSize; if (err) { m_errorCode = static_cast(err.code); if (m_debugMode) LOG(LERROR, ("Error: ", m_errorCode, [err.localizedDescription UTF8String])); return false; } request.HTTPBodyStream = [NSInputStream inputStreamWithFileAtPath:path]; [request setValue:[NSString stringWithFormat:@"%llu", file_size] forHTTPHeaderField:@"Content-Length"]; if (m_debugMode) LOG(LINFO, ("Uploading file", m_inputFile, file_size, "bytes")); } NSHTTPURLResponse * response = nil; NSError * err = nil; NSData * url_data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; if (response) { m_errorCode = static_cast(response.statusCode); m_urlReceived = [response.URL.absoluteString UTF8String]; NSString * content = [response.allHeaderFields objectForKey:@"Content-Type"]; if (content) m_contentTypeReceived = std::move([content UTF8String]); NSString * encoding = [response.allHeaderFields objectForKey:@"Content-Encoding"]; if (encoding) m_contentEncodingReceived = std::move([encoding UTF8String]); // Apple merges all Set-Cookie fields into one NSDictionary key delimited by commas. NSString * cookies = [response.allHeaderFields objectForKey:@"Set-Cookie"]; if (cookies) m_serverCookies = NormalizeServerCookies(std::move([cookies UTF8String])); if (url_data) { if (m_outputFile.empty()) m_serverResponse.assign(reinterpret_cast(url_data.bytes), url_data.length); else [url_data writeToFile:[NSString stringWithUTF8String:m_outputFile.c_str()] atomically:YES]; } return true; } // Request has failed if we are here. // MacOSX/iOS-specific workaround for HTTP 401 error bug. // @see bit.ly/1TrHlcS for more details. if (err.code == NSURLErrorUserCancelledAuthentication) { m_errorCode = 401; return true; } m_errorCode = static_cast(err.code); if (m_debugMode) LOG(LERROR, ("Error: ", m_errorCode, ':', [err.localizedDescription UTF8String], "while connecting to", m_urlRequested)); return false; } } // namespace platform