blob: 02cbaade5177c1b384230110b78d87316e6dddab [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004--2005, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/base/autodetectproxy.h"
29#include "talk/base/httpcommon.h"
30#include "talk/base/httpcommon-inl.h"
31#include "talk/base/nethelpers.h"
32
33namespace talk_base {
34
35static const ProxyType TEST_ORDER[] = {
36 PROXY_HTTPS, PROXY_SOCKS5, PROXY_UNKNOWN
37};
38
39static const int kSavedStringLimit = 128;
40
41static void SaveStringToStack(char *dst,
42 const std::string &src,
43 size_t dst_size) {
44 strncpy(dst, src.c_str(), dst_size - 1);
45 dst[dst_size - 1] = '\0';
46}
47
48AutoDetectProxy::AutoDetectProxy(const std::string& user_agent)
49 : agent_(user_agent), resolver_(NULL), socket_(NULL), next_(0) {
50}
51
52AutoDetectProxy::~AutoDetectProxy() {
53 if (resolver_) {
54 resolver_->Destroy(false);
55 }
56}
57
58void AutoDetectProxy::DoWork() {
59 // TODO: Try connecting to server_url without proxy first here?
60 if (!server_url_.empty()) {
61 LOG(LS_INFO) << "GetProxySettingsForUrl(" << server_url_ << ") - start";
62 GetProxyForUrl(agent_.c_str(), server_url_.c_str(), &proxy_);
63 LOG(LS_INFO) << "GetProxySettingsForUrl - stop";
64 }
65 Url<char> url(proxy_.address.HostAsURIString());
66 if (url.valid()) {
67 LOG(LS_WARNING) << "AutoDetectProxy removing http prefix on proxy host";
68 proxy_.address.SetIP(url.host());
69 }
70 LOG(LS_INFO) << "AutoDetectProxy found proxy at " << proxy_.address;
71 if (proxy_.type == PROXY_UNKNOWN) {
72 LOG(LS_INFO) << "AutoDetectProxy initiating proxy classification";
73 Next();
74 // Process I/O until Stop()
75 Thread::Current()->ProcessMessages(kForever);
76 // Clean up the autodetect socket, from the thread that created it
77 delete socket_;
78 }
79 // TODO: If we found a proxy, try to use it to verify that it
80 // works by sending a request to server_url. This could either be
81 // done here or by the HttpPortAllocator.
82}
83
84void AutoDetectProxy::OnMessage(Message *msg) {
85 if (MSG_TIMEOUT == msg->message_id) {
86 OnCloseEvent(socket_, ETIMEDOUT);
87 } else {
88 // This must be the ST_MSG_WORKER_DONE message that deletes the
89 // AutoDetectProxy object. We have observed crashes within this stack that
90 // seem to be highly reproducible for a small subset of users and thus are
91 // probably correlated with a specific proxy setting, so copy potentially
92 // relevant information onto the stack to make it available in Windows
93 // minidumps.
94
95 // Save the user agent and the number of auto-detection passes that we
96 // needed.
97 char agent[kSavedStringLimit];
98 SaveStringToStack(agent, agent_, sizeof agent);
99
100 int next = next_;
101
102 // Now the detected proxy config (minus the password field, which could be
103 // sensitive).
104 ProxyType type = proxy().type;
105
106 char address_hostname[kSavedStringLimit];
107 SaveStringToStack(address_hostname,
108 proxy().address.hostname(),
109 sizeof address_hostname);
110
111 IPAddress address_ip = proxy().address.ipaddr();
112
113 uint16 address_port = proxy().address.port();
114
115 char autoconfig_url[kSavedStringLimit];
116 SaveStringToStack(autoconfig_url,
117 proxy().autoconfig_url,
118 sizeof autoconfig_url);
119
120 bool autodetect = proxy().autodetect;
121
122 char bypass_list[kSavedStringLimit];
123 SaveStringToStack(bypass_list, proxy().bypass_list, sizeof bypass_list);
124
125 char username[kSavedStringLimit];
126 SaveStringToStack(username, proxy().username, sizeof username);
127
128 SignalThread::OnMessage(msg);
129
130 // Log the gathered data at a log level that will never actually be enabled
131 // so that the compiler is forced to retain the data on the stack.
132 LOG(LS_SENSITIVE) << agent << " " << next << " " << type << " "
133 << address_hostname << " " << address_ip << " "
134 << address_port << " " << autoconfig_url << " "
135 << autodetect << " " << bypass_list << " " << username;
136 }
137}
138
139void AutoDetectProxy::OnResolveResult(SignalThread* thread) {
140 if (thread != resolver_) {
141 return;
142 }
143 int error = resolver_->error();
144 if (error == 0) {
145 LOG(LS_VERBOSE) << "Resolved " << proxy_.address << " to "
146 << resolver_->address();
147 proxy_.address = resolver_->address();
148 DoConnect();
149 } else {
150 LOG(LS_INFO) << "Failed to resolve " << resolver_->address();
151 resolver_->Destroy(false);
152 resolver_ = NULL;
153 proxy_.address = SocketAddress();
154 Thread::Current()->Post(this, MSG_TIMEOUT);
155 }
156}
157
158void AutoDetectProxy::Next() {
159 if (TEST_ORDER[next_] >= PROXY_UNKNOWN) {
160 Complete(PROXY_UNKNOWN);
161 return;
162 }
163
164 LOG(LS_VERBOSE) << "AutoDetectProxy connecting to "
165 << proxy_.address.ToSensitiveString();
166
167 if (socket_) {
168 Thread::Current()->Clear(this, MSG_TIMEOUT);
169 socket_->Close();
170 Thread::Current()->Dispose(socket_);
171 socket_ = NULL;
172 }
173 int timeout = 2000;
174 if (proxy_.address.IsUnresolvedIP()) {
175 // Launch an asyncresolver. This thread will spin waiting for it.
176 timeout += 2000;
177 if (!resolver_) {
178 resolver_ = new AsyncResolver();
179 }
180 resolver_->set_address(proxy_.address);
181 resolver_->SignalWorkDone.connect(this,
182 &AutoDetectProxy::OnResolveResult);
183 resolver_->Start();
184 } else {
185 DoConnect();
186 }
187 Thread::Current()->PostDelayed(timeout, this, MSG_TIMEOUT);
188}
189
190void AutoDetectProxy::DoConnect() {
191 if (resolver_) {
192 resolver_->Destroy(false);
193 resolver_ = NULL;
194 }
195 socket_ =
196 Thread::Current()->socketserver()->CreateAsyncSocket(
197 proxy_.address.family(), SOCK_STREAM);
198 if (!socket_) {
199 LOG(LS_VERBOSE) << "Unable to create socket for " << proxy_.address;
200 return;
201 }
202 socket_->SignalConnectEvent.connect(this, &AutoDetectProxy::OnConnectEvent);
203 socket_->SignalReadEvent.connect(this, &AutoDetectProxy::OnReadEvent);
204 socket_->SignalCloseEvent.connect(this, &AutoDetectProxy::OnCloseEvent);
205 socket_->Connect(proxy_.address);
206}
207
208void AutoDetectProxy::Complete(ProxyType type) {
209 Thread::Current()->Clear(this, MSG_TIMEOUT);
210 if (socket_) {
211 socket_->Close();
212 }
213
214 proxy_.type = type;
215 LoggingSeverity sev = (proxy_.type == PROXY_UNKNOWN) ? LS_ERROR : LS_INFO;
216 LOG_V(sev) << "AutoDetectProxy detected "
217 << proxy_.address.ToSensitiveString()
218 << " as type " << proxy_.type;
219
220 Thread::Current()->Quit();
221}
222
223void AutoDetectProxy::OnConnectEvent(AsyncSocket * socket) {
224 std::string probe;
225
226 switch (TEST_ORDER[next_]) {
227 case PROXY_HTTPS:
228 probe.assign("CONNECT www.google.com:443 HTTP/1.0\r\n"
229 "User-Agent: ");
230 probe.append(agent_);
231 probe.append("\r\n"
232 "Host: www.google.com\r\n"
233 "Content-Length: 0\r\n"
234 "Proxy-Connection: Keep-Alive\r\n"
235 "\r\n");
236 break;
237 case PROXY_SOCKS5:
238 probe.assign("\005\001\000", 3);
239 break;
240 default:
241 ASSERT(false);
242 return;
243 }
244
245 LOG(LS_VERBOSE) << "AutoDetectProxy probing type " << TEST_ORDER[next_]
246 << " sending " << probe.size() << " bytes";
247 socket_->Send(probe.data(), probe.size());
248}
249
250void AutoDetectProxy::OnReadEvent(AsyncSocket * socket) {
251 char data[257];
252 int len = socket_->Recv(data, 256);
253 if (len > 0) {
254 data[len] = 0;
255 LOG(LS_VERBOSE) << "AutoDetectProxy read " << len << " bytes";
256 }
257
258 switch (TEST_ORDER[next_]) {
259 case PROXY_HTTPS:
260 if ((len >= 2) && (data[0] == '\x05')) {
261 Complete(PROXY_SOCKS5);
262 return;
263 }
264 if ((len >= 5) && (strncmp(data, "HTTP/", 5) == 0)) {
265 Complete(PROXY_HTTPS);
266 return;
267 }
268 break;
269 case PROXY_SOCKS5:
270 if ((len >= 2) && (data[0] == '\x05')) {
271 Complete(PROXY_SOCKS5);
272 return;
273 }
274 break;
275 default:
276 ASSERT(false);
277 return;
278 }
279
280 ++next_;
281 Next();
282}
283
284void AutoDetectProxy::OnCloseEvent(AsyncSocket * socket, int error) {
285 LOG(LS_VERBOSE) << "AutoDetectProxy closed with error: " << error;
286 ++next_;
287 Next();
288}
289
290} // namespace talk_base