3 * Copyright 2004--2005, Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
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"
35 static const ProxyType TEST_ORDER[] = {
36 PROXY_HTTPS, PROXY_SOCKS5, PROXY_UNKNOWN
39 static const int kSavedStringLimit = 128;
41 static void SaveStringToStack(char *dst,
42 const std::string &src,
44 strncpy(dst, src.c_str(), dst_size - 1);
45 dst[dst_size - 1] = '\0';
48 AutoDetectProxy::AutoDetectProxy(const std::string& user_agent)
49 : agent_(user_agent), resolver_(NULL), socket_(NULL), next_(0) {
52 AutoDetectProxy::~AutoDetectProxy() {
54 resolver_->Destroy(false);
58 void 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";
65 Url<char> url(proxy_.address.HostAsURIString());
67 LOG(LS_WARNING) << "AutoDetectProxy removing http prefix on proxy host";
68 proxy_.address.SetIP(url.host());
70 LOG(LS_INFO) << "AutoDetectProxy found proxy at " << proxy_.address;
71 if (proxy_.type == PROXY_UNKNOWN) {
72 LOG(LS_INFO) << "AutoDetectProxy initiating proxy classification";
74 // Process I/O until Stop()
75 Thread::Current()->ProcessMessages(kForever);
76 // Clean up the autodetect socket, from the thread that created it
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.
84 void AutoDetectProxy::OnMessage(Message *msg) {
85 if (MSG_TIMEOUT == msg->message_id) {
86 OnCloseEvent(socket_, ETIMEDOUT);
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
95 // Save the user agent and the number of auto-detection passes that we
97 char agent[kSavedStringLimit];
98 SaveStringToStack(agent, agent_, sizeof agent);
102 // Now the detected proxy config (minus the password field, which could be
104 ProxyType type = proxy().type;
106 char address_hostname[kSavedStringLimit];
107 SaveStringToStack(address_hostname,
108 proxy().address.hostname(),
109 sizeof address_hostname);
111 IPAddress address_ip = proxy().address.ipaddr();
113 uint16 address_port = proxy().address.port();
115 char autoconfig_url[kSavedStringLimit];
116 SaveStringToStack(autoconfig_url,
117 proxy().autoconfig_url,
118 sizeof autoconfig_url);
120 bool autodetect = proxy().autodetect;
122 char bypass_list[kSavedStringLimit];
123 SaveStringToStack(bypass_list, proxy().bypass_list, sizeof bypass_list);
125 char username[kSavedStringLimit];
126 SaveStringToStack(username, proxy().username, sizeof username);
128 SignalThread::OnMessage(msg);
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;
139 void AutoDetectProxy::OnResolveResult(SignalThread* thread) {
140 if (thread != resolver_) {
143 int error = resolver_->error();
145 LOG(LS_VERBOSE) << "Resolved " << proxy_.address << " to "
146 << resolver_->address();
147 proxy_.address = resolver_->address();
150 LOG(LS_INFO) << "Failed to resolve " << resolver_->address();
151 resolver_->Destroy(false);
153 proxy_.address = SocketAddress();
154 Thread::Current()->Post(this, MSG_TIMEOUT);
158 void AutoDetectProxy::Next() {
159 if (TEST_ORDER[next_] >= PROXY_UNKNOWN) {
160 Complete(PROXY_UNKNOWN);
164 LOG(LS_VERBOSE) << "AutoDetectProxy connecting to "
165 << proxy_.address.ToSensitiveString();
168 Thread::Current()->Clear(this, MSG_TIMEOUT);
170 Thread::Current()->Dispose(socket_);
174 if (proxy_.address.IsUnresolvedIP()) {
175 // Launch an asyncresolver. This thread will spin waiting for it.
178 resolver_ = new AsyncResolver();
180 resolver_->set_address(proxy_.address);
181 resolver_->SignalWorkDone.connect(this,
182 &AutoDetectProxy::OnResolveResult);
187 Thread::Current()->PostDelayed(timeout, this, MSG_TIMEOUT);
190 void AutoDetectProxy::DoConnect() {
192 resolver_->Destroy(false);
196 Thread::Current()->socketserver()->CreateAsyncSocket(
197 proxy_.address.family(), SOCK_STREAM);
199 LOG(LS_VERBOSE) << "Unable to create socket for " << proxy_.address;
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);
208 void AutoDetectProxy::Complete(ProxyType type) {
209 Thread::Current()->Clear(this, MSG_TIMEOUT);
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;
220 Thread::Current()->Quit();
223 void AutoDetectProxy::OnConnectEvent(AsyncSocket * socket) {
226 switch (TEST_ORDER[next_]) {
228 probe.assign("CONNECT www.google.com:443 HTTP/1.0\r\n"
230 probe.append(agent_);
232 "Host: www.google.com\r\n"
233 "Content-Length: 0\r\n"
234 "Proxy-Connection: Keep-Alive\r\n"
238 probe.assign("\005\001\000", 3);
245 LOG(LS_VERBOSE) << "AutoDetectProxy probing type " << TEST_ORDER[next_]
246 << " sending " << probe.size() << " bytes";
247 socket_->Send(probe.data(), probe.size());
250 void AutoDetectProxy::OnReadEvent(AsyncSocket * socket) {
252 int len = socket_->Recv(data, 256);
255 LOG(LS_VERBOSE) << "AutoDetectProxy read " << len << " bytes";
258 switch (TEST_ORDER[next_]) {
260 if ((len >= 2) && (data[0] == '\x05')) {
261 Complete(PROXY_SOCKS5);
264 if ((len >= 5) && (strncmp(data, "HTTP/", 5) == 0)) {
265 Complete(PROXY_HTTPS);
270 if ((len >= 2) && (data[0] == '\x05')) {
271 Complete(PROXY_SOCKS5);
284 void AutoDetectProxy::OnCloseEvent(AsyncSocket * socket, int error) {
285 LOG(LS_VERBOSE) << "AutoDetectProxy closed with error: " << error;
290 } // namespace talk_base