Welcome to mirror list, hosted at ThFree Co, Russian Federation.

http_client_apple.mm « platform - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2157776b3c5fd3909ae5487e3b8fe7e2c50b6937 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/*******************************************************************************
The MIT License (MIT)

Copyright (c) 2015 Alexander Zolotarev <me@alex.bio> 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 <Foundation/NSString.h>
#import <Foundation/NSURL.h>
#import <Foundation/NSURLError.h>
#import <Foundation/NSData.h>
#import <Foundation/NSStream.h>
#import <Foundation/NSURLRequest.h>
#import <Foundation/NSURLResponse.h>
#import <Foundation/NSURLConnection.h>
#import <Foundation/NSError.h>
#import <Foundation/NSFileManager.h>

#include <TargetConditionals.h> // 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()];
  for (auto const & header : m_headers)
  {
    [request setValue:@(header.second.c_str()) forHTTPHeaderField:@(header.first.c_str())];
  }

  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_bodyData.empty())
  {
    request.HTTPBody = [NSData dataWithBytes:m_bodyData.data() length:m_bodyData.size()];
    LOG(LDEBUG, ("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<int>(err.code);
      LOG(LDEBUG, ("Error: ", m_errorCode, [err.localizedDescription UTF8String]));

      return false;
    }
    request.HTTPBodyStream = [NSInputStream inputStreamWithFileAtPath:path];
    [request setValue:[NSString stringWithFormat:@"%llu", file_size] forHTTPHeaderField:@"Content-Length"];
    LOG(LDEBUG, ("Uploading file", m_inputFile, file_size, "bytes"));
  }

  NSHTTPURLResponse * response = nil;
  NSError * err = nil;
  NSData * url_data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

  m_headers.clear();

  if (response)
  {
    m_errorCode = static_cast<int>(response.statusCode);
    m_urlReceived = [response.URL.absoluteString UTF8String];

    if (m_loadHeaders)
    {
      [response.allHeaderFields enumerateKeysAndObjectsUsingBlock:^(NSString * key, NSString * obj, BOOL * stop)
      {
        m_headers.emplace(key.lowercaseString.UTF8String, obj.UTF8String);
      }];
    }
    else
    {
      NSString * cookies = [response.allHeaderFields objectForKey:@"Set-Cookie"];
      if (cookies)
        m_headers.emplace("Set-Cookie", NormalizeServerCookies(std::move([cookies UTF8String])));
    }

    if (url_data)
    {
      if (m_outputFile.empty())
        m_serverResponse.assign(reinterpret_cast<char const *>(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<int>(err.code);
  LOG(LDEBUG, ("Error: ", m_errorCode, ':', [err.localizedDescription UTF8String], "while connecting to", m_urlRequested));

  return false;
}
} // namespace platform