You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1263 lines
41 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  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. #include "talk/base/proxydetect.h"
  28. #ifdef WIN32
  29. #include "talk/base/win32.h"
  30. #include <shlobj.h>
  31. #endif // WIN32
  32. #ifdef HAVE_CONFIG_H
  33. #include "config.h"
  34. #endif
  35. #ifdef OSX
  36. #include <SystemConfiguration/SystemConfiguration.h>
  37. #include <CoreFoundation/CoreFoundation.h>
  38. #include <CoreServices/CoreServices.h>
  39. #include <Security/Security.h>
  40. #include "macconversion.h"
  41. #endif
  42. #include <map>
  43. #include "talk/base/fileutils.h"
  44. #include "talk/base/httpcommon.h"
  45. #include "talk/base/httpcommon-inl.h"
  46. #include "talk/base/pathutils.h"
  47. #include "talk/base/stringutils.h"
  48. #ifdef WIN32
  49. #define _TRY_WINHTTP 1
  50. #define _TRY_JSPROXY 0
  51. #define _TRY_WM_FINDPROXY 0
  52. #define _TRY_IE_LAN_SETTINGS 1
  53. #endif // WIN32
  54. // For all platforms try Firefox.
  55. #define _TRY_FIREFOX 1
  56. // Use profiles.ini to find the correct profile for this user.
  57. // If not set, we'll just look for the default one.
  58. #define USE_FIREFOX_PROFILES_INI 1
  59. static const size_t kMaxLineLength = 1024;
  60. static const char kFirefoxPattern[] = "Firefox";
  61. static const char kInternetExplorerPattern[] = "MSIE";
  62. struct StringMap {
  63. public:
  64. void Add(const char * name, const char * value) { map_[name] = value; }
  65. const std::string& Get(const char * name, const char * def = "") const {
  66. std::map<std::string, std::string>::const_iterator it =
  67. map_.find(name);
  68. if (it != map_.end())
  69. return it->second;
  70. def_ = def;
  71. return def_;
  72. }
  73. bool IsSet(const char * name) const {
  74. return (map_.find(name) != map_.end());
  75. }
  76. private:
  77. std::map<std::string, std::string> map_;
  78. mutable std::string def_;
  79. };
  80. enum UserAgent {
  81. UA_FIREFOX,
  82. UA_INTERNETEXPLORER,
  83. UA_OTHER,
  84. UA_UNKNOWN
  85. };
  86. #if _TRY_WINHTTP
  87. //#include <winhttp.h>
  88. // Note: From winhttp.h
  89. const char WINHTTP[] = "winhttp";
  90. typedef LPVOID HINTERNET;
  91. typedef struct {
  92. DWORD dwAccessType; // see WINHTTP_ACCESS_* types below
  93. LPWSTR lpszProxy; // proxy server list
  94. LPWSTR lpszProxyBypass; // proxy bypass list
  95. } WINHTTP_PROXY_INFO, * LPWINHTTP_PROXY_INFO;
  96. typedef struct {
  97. DWORD dwFlags;
  98. DWORD dwAutoDetectFlags;
  99. LPCWSTR lpszAutoConfigUrl;
  100. LPVOID lpvReserved;
  101. DWORD dwReserved;
  102. BOOL fAutoLogonIfChallenged;
  103. } WINHTTP_AUTOPROXY_OPTIONS;
  104. typedef struct {
  105. BOOL fAutoDetect;
  106. LPWSTR lpszAutoConfigUrl;
  107. LPWSTR lpszProxy;
  108. LPWSTR lpszProxyBypass;
  109. } WINHTTP_CURRENT_USER_IE_PROXY_CONFIG;
  110. extern "C" {
  111. typedef HINTERNET (WINAPI * pfnWinHttpOpen)
  112. (
  113. IN LPCWSTR pwszUserAgent,
  114. IN DWORD dwAccessType,
  115. IN LPCWSTR pwszProxyName OPTIONAL,
  116. IN LPCWSTR pwszProxyBypass OPTIONAL,
  117. IN DWORD dwFlags
  118. );
  119. typedef BOOL (STDAPICALLTYPE * pfnWinHttpCloseHandle)
  120. (
  121. IN HINTERNET hInternet
  122. );
  123. typedef BOOL (STDAPICALLTYPE * pfnWinHttpGetProxyForUrl)
  124. (
  125. IN HINTERNET hSession,
  126. IN LPCWSTR lpcwszUrl,
  127. IN WINHTTP_AUTOPROXY_OPTIONS * pAutoProxyOptions,
  128. OUT WINHTTP_PROXY_INFO * pProxyInfo
  129. );
  130. typedef BOOL (STDAPICALLTYPE * pfnWinHttpGetIEProxyConfig)
  131. (
  132. IN OUT WINHTTP_CURRENT_USER_IE_PROXY_CONFIG * pProxyConfig
  133. );
  134. } // extern "C"
  135. #define WINHTTP_AUTOPROXY_AUTO_DETECT 0x00000001
  136. #define WINHTTP_AUTOPROXY_CONFIG_URL 0x00000002
  137. #define WINHTTP_AUTOPROXY_RUN_INPROCESS 0x00010000
  138. #define WINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY 0x00020000
  139. #define WINHTTP_AUTO_DETECT_TYPE_DHCP 0x00000001
  140. #define WINHTTP_AUTO_DETECT_TYPE_DNS_A 0x00000002
  141. #define WINHTTP_ACCESS_TYPE_DEFAULT_PROXY 0
  142. #define WINHTTP_ACCESS_TYPE_NO_PROXY 1
  143. #define WINHTTP_ACCESS_TYPE_NAMED_PROXY 3
  144. #define WINHTTP_NO_PROXY_NAME NULL
  145. #define WINHTTP_NO_PROXY_BYPASS NULL
  146. #endif // _TRY_WINHTTP
  147. #if _TRY_JSPROXY
  148. extern "C" {
  149. typedef BOOL (STDAPICALLTYPE * pfnInternetGetProxyInfo)
  150. (
  151. LPCSTR lpszUrl,
  152. DWORD dwUrlLength,
  153. LPSTR lpszUrlHostName,
  154. DWORD dwUrlHostNameLength,
  155. LPSTR * lplpszProxyHostName,
  156. LPDWORD lpdwProxyHostNameLength
  157. );
  158. } // extern "C"
  159. #endif // _TRY_JSPROXY
  160. #if _TRY_WM_FINDPROXY
  161. #include <comutil.h>
  162. #include <wmnetsourcecreator.h>
  163. #include <wmsinternaladminnetsource.h>
  164. #endif // _TRY_WM_FINDPROXY
  165. #if _TRY_IE_LAN_SETTINGS
  166. #include <wininet.h>
  167. #include <string>
  168. #endif // _TRY_IE_LAN_SETTINGS
  169. namespace talk_base {
  170. //////////////////////////////////////////////////////////////////////
  171. // Utility Functions
  172. //////////////////////////////////////////////////////////////////////
  173. #ifdef WIN32
  174. #ifdef _UNICODE
  175. typedef std::wstring tstring;
  176. std::string Utf8String(const tstring& str) { return ToUtf8(str); }
  177. #else // !_UNICODE
  178. typedef std::string tstring;
  179. std::string Utf8String(const tstring& str) { return str; }
  180. #endif // !_UNICODE
  181. #endif // WIN32
  182. bool ProxyItemMatch(const Url<char>& url, char * item, size_t len) {
  183. // hostname:443
  184. if (char * port = ::strchr(item, ':')) {
  185. *port++ = '\0';
  186. if (url.port() != atol(port)) {
  187. return false;
  188. }
  189. }
  190. // A.B.C.D or A.B.C.D/24
  191. int a, b, c, d, m;
  192. int match = sscanf(item, "%d.%d.%d.%d/%d", &a, &b, &c, &d, &m);
  193. if (match >= 4) {
  194. uint32 ip = ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) |
  195. (d & 0xFF);
  196. if ((match < 5) || (m > 32))
  197. m = 32;
  198. else if (m < 0)
  199. m = 0;
  200. uint32 mask = (m == 0) ? 0 : (~0UL) << (32 - m);
  201. SocketAddress addr(url.host(), 0);
  202. // TODO: Support IPv6 proxyitems. This code block is IPv4 only anyway.
  203. return !addr.IsUnresolved() &&
  204. ((addr.ipaddr().v4AddressAsHostOrderInteger() & mask) == (ip & mask));
  205. }
  206. // .foo.com
  207. if (*item == '.') {
  208. size_t hostlen = url.host().length();
  209. return (hostlen > len)
  210. && (stricmp(url.host().c_str() + (hostlen - len), item) == 0);
  211. }
  212. // localhost or www.*.com
  213. if (!string_match(url.host().c_str(), item))
  214. return false;
  215. return true;
  216. }
  217. bool ProxyListMatch(const Url<char>& url, const std::string& proxy_list,
  218. char sep) {
  219. const size_t BUFSIZE = 256;
  220. char buffer[BUFSIZE];
  221. const char* list = proxy_list.c_str();
  222. while (*list) {
  223. // Remove leading space
  224. if (isspace(*list)) {
  225. ++list;
  226. continue;
  227. }
  228. // Break on separator
  229. size_t len;
  230. const char * start = list;
  231. if (const char * end = ::strchr(list, sep)) {
  232. len = (end - list);
  233. list += len + 1;
  234. } else {
  235. len = strlen(list);
  236. list += len;
  237. }
  238. // Remove trailing space
  239. while ((len > 0) && isspace(start[len-1]))
  240. --len;
  241. // Check for oversized entry
  242. if (len >= BUFSIZE)
  243. continue;
  244. memcpy(buffer, start, len);
  245. buffer[len] = 0;
  246. if (!ProxyItemMatch(url, buffer, len))
  247. continue;
  248. return true;
  249. }
  250. return false;
  251. }
  252. bool Better(ProxyType lhs, const ProxyType rhs) {
  253. // PROXY_NONE, PROXY_HTTPS, PROXY_SOCKS5, PROXY_UNKNOWN
  254. const int PROXY_VALUE[5] = { 0, 2, 3, 1 };
  255. return (PROXY_VALUE[lhs] > PROXY_VALUE[rhs]);
  256. }
  257. bool ParseProxy(const std::string& saddress, ProxyInfo* proxy) {
  258. const size_t kMaxAddressLength = 1024;
  259. // Allow semicolon, space, or tab as an address separator
  260. const char* const kAddressSeparator = " ;\t";
  261. ProxyType ptype;
  262. std::string host;
  263. uint16 port;
  264. const char* address = saddress.c_str();
  265. while (*address) {
  266. size_t len;
  267. const char * start = address;
  268. if (const char * sep = strchr(address, kAddressSeparator)) {
  269. len = (sep - address);
  270. address += len + 1;
  271. while (*address != '\0' && ::strchr(kAddressSeparator, *address)) {
  272. address += 1;
  273. }
  274. } else {
  275. len = strlen(address);
  276. address += len;
  277. }
  278. if (len > kMaxAddressLength - 1) {
  279. LOG(LS_WARNING) << "Proxy address too long [" << start << "]";
  280. continue;
  281. }
  282. char buffer[kMaxAddressLength];
  283. memcpy(buffer, start, len);
  284. buffer[len] = 0;
  285. char * colon = ::strchr(buffer, ':');
  286. if (!colon) {
  287. LOG(LS_WARNING) << "Proxy address without port [" << buffer << "]";
  288. continue;
  289. }
  290. *colon = 0;
  291. char * endptr;
  292. port = static_cast<uint16>(strtol(colon + 1, &endptr, 0));
  293. if (*endptr != 0) {
  294. LOG(LS_WARNING) << "Proxy address with invalid port [" << buffer << "]";
  295. continue;
  296. }
  297. if (char * equals = ::strchr(buffer, '=')) {
  298. *equals = 0;
  299. host = equals + 1;
  300. if (_stricmp(buffer, "socks") == 0) {
  301. ptype = PROXY_SOCKS5;
  302. } else if (_stricmp(buffer, "https") == 0) {
  303. ptype = PROXY_HTTPS;
  304. } else {
  305. LOG(LS_WARNING) << "Proxy address with unknown protocol ["
  306. << buffer << "]";
  307. ptype = PROXY_UNKNOWN;
  308. }
  309. } else {
  310. host = buffer;
  311. ptype = PROXY_UNKNOWN;
  312. }
  313. if (Better(ptype, proxy->type)) {
  314. proxy->type = ptype;
  315. proxy->address.SetIP(host);
  316. proxy->address.SetPort(port);
  317. }
  318. }
  319. return proxy->type != PROXY_NONE;
  320. }
  321. UserAgent GetAgent(const char* agent) {
  322. if (agent) {
  323. std::string agent_str(agent);
  324. if (agent_str.find(kFirefoxPattern) != std::string::npos) {
  325. return UA_FIREFOX;
  326. } else if (agent_str.find(kInternetExplorerPattern) != std::string::npos) {
  327. return UA_INTERNETEXPLORER;
  328. } else if (agent_str.empty()) {
  329. return UA_UNKNOWN;
  330. }
  331. }
  332. return UA_OTHER;
  333. }
  334. bool EndsWith(const std::string& a, const std::string& b) {
  335. if (b.size() > a.size()) {
  336. return false;
  337. }
  338. int result = a.compare(a.size() - b.size(), b.size(), b);
  339. return result == 0;
  340. }
  341. bool GetFirefoxProfilePath(Pathname* path) {
  342. #ifdef WIN32
  343. wchar_t w_path[MAX_PATH];
  344. if (SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, w_path) !=
  345. S_OK) {
  346. LOG(LS_ERROR) << "SHGetFolderPath failed";
  347. return false;
  348. }
  349. path->SetFolder(ToUtf8(w_path, wcslen(w_path)));
  350. path->AppendFolder("Mozilla");
  351. path->AppendFolder("Firefox");
  352. #elif OSX
  353. FSRef fr;
  354. if (0 != FSFindFolder(kUserDomain, kApplicationSupportFolderType,
  355. kCreateFolder, &fr)) {
  356. LOG(LS_ERROR) << "FSFindFolder failed";
  357. return false;
  358. }
  359. char buffer[NAME_MAX + 1];
  360. if (0 != FSRefMakePath(&fr, reinterpret_cast<uint8*>(buffer),
  361. ARRAY_SIZE(buffer))) {
  362. LOG(LS_ERROR) << "FSRefMakePath failed";
  363. return false;
  364. }
  365. path->SetFolder(std::string(buffer));
  366. path->AppendFolder("Firefox");
  367. #else
  368. char* user_home = getenv("HOME");
  369. if (user_home == NULL) {
  370. return false;
  371. }
  372. path->SetFolder(std::string(user_home));
  373. path->AppendFolder(".mozilla");
  374. path->AppendFolder("firefox");
  375. #endif // WIN32
  376. return true;
  377. }
  378. bool GetDefaultFirefoxProfile(Pathname* profile_path) {
  379. ASSERT(NULL != profile_path);
  380. Pathname path;
  381. if (!GetFirefoxProfilePath(&path)) {
  382. return false;
  383. }
  384. #if USE_FIREFOX_PROFILES_INI
  385. // [Profile0]
  386. // Name=default
  387. // IsRelative=1
  388. // Path=Profiles/2de53ejb.default
  389. // Default=1
  390. // Note: we are looking for the first entry with "Default=1", or the last
  391. // entry in the file
  392. path.SetFilename("profiles.ini");
  393. FileStream* fs = Filesystem::OpenFile(path, "r");
  394. if (!fs) {
  395. return false;
  396. }
  397. Pathname candidate;
  398. bool relative = true;
  399. std::string line;
  400. while (fs->ReadLine(&line) == SR_SUCCESS) {
  401. if (line.length() == 0) {
  402. continue;
  403. }
  404. if (line.at(0) == '[') {
  405. relative = true;
  406. candidate.clear();
  407. } else if (line.find("IsRelative=") == 0 &&
  408. line.length() >= 12) {
  409. // TODO: The initial Linux public launch revealed a fairly
  410. // high number of machines where IsRelative= did not have anything after
  411. // it. Perhaps that is legal profiles.ini syntax?
  412. relative = (line.at(11) != '0');
  413. } else if (line.find("Path=") == 0 &&
  414. line.length() >= 6) {
  415. if (relative) {
  416. candidate = path;
  417. } else {
  418. candidate.clear();
  419. }
  420. candidate.AppendFolder(line.substr(5));
  421. } else if (line.find("Default=") == 0 &&
  422. line.length() >= 9) {
  423. if ((line.at(8) != '0') && !candidate.empty()) {
  424. break;
  425. }
  426. }
  427. }
  428. fs->Close();
  429. if (candidate.empty()) {
  430. return false;
  431. }
  432. profile_path->SetPathname(candidate.pathname());
  433. #else // !USE_FIREFOX_PROFILES_INI
  434. path.AppendFolder("Profiles");
  435. DirectoryIterator* it = Filesystem::IterateDirectory();
  436. it->Iterate(path);
  437. std::string extension(".default");
  438. while (!EndsWith(it->Name(), extension)) {
  439. if (!it->Next()) {
  440. return false;
  441. }
  442. }
  443. profile_path->SetPathname(path);
  444. profile->AppendFolder("Profiles");
  445. profile->AppendFolder(it->Name());
  446. delete it;
  447. #endif // !USE_FIREFOX_PROFILES_INI
  448. return true;
  449. }
  450. bool ReadFirefoxPrefs(const Pathname& filename,
  451. const char * prefix,
  452. StringMap* settings) {
  453. FileStream* fs = Filesystem::OpenFile(filename, "r");
  454. if (!fs) {
  455. LOG(LS_ERROR) << "Failed to open file: " << filename.pathname();
  456. return false;
  457. }
  458. std::string line;
  459. while (fs->ReadLine(&line) == SR_SUCCESS) {
  460. size_t prefix_len = strlen(prefix);
  461. // Skip blank lines and too long lines.
  462. if ((line.length() == 0) || (line.length() > kMaxLineLength)
  463. || (line.at(0) == '#') || line.compare(0, 2, "/*") == 0
  464. || line.compare(0, 2, " *") == 0) {
  465. continue;
  466. }
  467. char buffer[kMaxLineLength];
  468. strcpyn(buffer, sizeof(buffer), line.c_str());
  469. int nstart = 0, nend = 0, vstart = 0, vend = 0;
  470. sscanf(buffer, "user_pref(\"%n%*[^\"]%n\", %n%*[^)]%n);",
  471. &nstart, &nend, &vstart, &vend);
  472. if (vend > 0) {
  473. char* name = buffer + nstart;
  474. name[nend - nstart] = 0;
  475. if ((vend - vstart >= 2) && (buffer[vstart] == '"')) {
  476. vstart += 1;
  477. vend -= 1;
  478. }
  479. char* value = buffer + vstart;
  480. value[vend - vstart] = 0;
  481. if ((strncmp(name, prefix, prefix_len) == 0) && *value) {
  482. settings->Add(name + prefix_len, value);
  483. }
  484. } else {
  485. LOG_F(LS_WARNING) << "Unparsed pref [" << buffer << "]";
  486. }
  487. }
  488. fs->Close();
  489. return true;
  490. }
  491. bool GetFirefoxProxySettings(const char* url, ProxyInfo* proxy) {
  492. Url<char> purl(url);
  493. Pathname path;
  494. bool success = false;
  495. if (GetDefaultFirefoxProfile(&path)) {
  496. StringMap settings;
  497. path.SetFilename("prefs.js");
  498. if (ReadFirefoxPrefs(path, "network.proxy.", &settings)) {
  499. success = true;
  500. proxy->bypass_list =
  501. settings.Get("no_proxies_on", "localhost, 127.0.0.1");
  502. if (settings.Get("type") == "1") {
  503. // User has manually specified a proxy, try to figure out what
  504. // type it is.
  505. if (ProxyListMatch(purl, proxy->bypass_list.c_str(), ',')) {
  506. // Our url is in the list of url's to bypass proxy.
  507. } else if (settings.Get("share_proxy_settings") == "true") {
  508. proxy->type = PROXY_UNKNOWN;
  509. proxy->address.SetIP(settings.Get("http"));
  510. proxy->address.SetPort(atoi(settings.Get("http_port").c_str()));
  511. } else if (settings.IsSet("socks")) {
  512. proxy->type = PROXY_SOCKS5;
  513. proxy->address.SetIP(settings.Get("socks"));
  514. proxy->address.SetPort(atoi(settings.Get("socks_port").c_str()));
  515. } else if (settings.IsSet("ssl")) {
  516. proxy->type = PROXY_HTTPS;
  517. proxy->address.SetIP(settings.Get("ssl"));
  518. proxy->address.SetPort(atoi(settings.Get("ssl_port").c_str()));
  519. } else if (settings.IsSet("http")) {
  520. proxy->type = PROXY_HTTPS;
  521. proxy->address.SetIP(settings.Get("http"));
  522. proxy->address.SetPort(atoi(settings.Get("http_port").c_str()));
  523. }
  524. } else if (settings.Get("type") == "2") {
  525. // Browser is configured to get proxy settings from a given url.
  526. proxy->autoconfig_url = settings.Get("autoconfig_url").c_str();
  527. } else if (settings.Get("type") == "4") {
  528. // Browser is configured to auto detect proxy config.
  529. proxy->autodetect = true;
  530. } else {
  531. // No proxy set.
  532. }
  533. }
  534. }
  535. return success;
  536. }
  537. #ifdef WIN32 // Windows specific implementation for reading Internet
  538. // Explorer proxy settings.
  539. void LogGetProxyFault() {
  540. LOG_GLEM(LERROR, WINHTTP) << "WinHttpGetProxyForUrl faulted!!";
  541. }
  542. BOOL MyWinHttpGetProxyForUrl(pfnWinHttpGetProxyForUrl pWHGPFU,
  543. HINTERNET hWinHttp, LPCWSTR url,
  544. WINHTTP_AUTOPROXY_OPTIONS *options,
  545. WINHTTP_PROXY_INFO *info) {
  546. // WinHttpGetProxyForUrl() can call plugins which can crash.
  547. // In the case of McAfee scriptproxy.dll, it does crash in
  548. // older versions. Try to catch crashes here and treat as an
  549. // error.
  550. BOOL success = FALSE;
  551. #if (_HAS_EXCEPTIONS == 0)
  552. __try {
  553. success = pWHGPFU(hWinHttp, url, options, info);
  554. } __except(EXCEPTION_EXECUTE_HANDLER) {
  555. // This is a separate function to avoid
  556. // Visual C++ error 2712 when compiling with C++ EH
  557. LogGetProxyFault();
  558. }
  559. #else
  560. success = pWHGPFU(hWinHttp, url, options, info);
  561. #endif // (_HAS_EXCEPTIONS == 0)
  562. return success;
  563. }
  564. bool IsDefaultBrowserFirefox() {
  565. HKEY key;
  566. LONG result = RegOpenKeyEx(HKEY_CLASSES_ROOT, L"http\\shell\\open\\command",
  567. 0, KEY_READ, &key);
  568. if (ERROR_SUCCESS != result)
  569. return false;
  570. wchar_t* value = NULL;
  571. DWORD size, type;
  572. result = RegQueryValueEx(key, L"", 0, &type, NULL, &size);
  573. if (REG_SZ != type) {
  574. result = ERROR_ACCESS_DENIED; // Any error is fine
  575. } else if (ERROR_SUCCESS == result) {
  576. value = new wchar_t[size+1];
  577. BYTE* buffer = reinterpret_cast<BYTE*>(value);
  578. result = RegQueryValueEx(key, L"", 0, &type, buffer, &size);
  579. }
  580. RegCloseKey(key);
  581. bool success = false;
  582. if (ERROR_SUCCESS == result) {
  583. value[size] = L'\0';
  584. for (size_t i = 0; i < size; ++i) {
  585. value[i] = tolowercase(value[i]);
  586. }
  587. success = (NULL != strstr(value, L"firefox.exe"));
  588. }
  589. delete [] value;
  590. return success;
  591. }
  592. bool GetWinHttpProxySettings(const char* url, ProxyInfo* proxy) {
  593. HMODULE winhttp_handle = LoadLibrary(L"winhttp.dll");
  594. if (winhttp_handle == NULL) {
  595. LOG(LS_ERROR) << "Failed to load winhttp.dll.";
  596. return false;
  597. }
  598. WINHTTP_CURRENT_USER_IE_PROXY_CONFIG iecfg;
  599. memset(&iecfg, 0, sizeof(iecfg));
  600. Url<char> purl(url);
  601. pfnWinHttpGetIEProxyConfig pWHGIEPC =
  602. reinterpret_cast<pfnWinHttpGetIEProxyConfig>(
  603. GetProcAddress(winhttp_handle,
  604. "WinHttpGetIEProxyConfigForCurrentUser"));
  605. bool success = false;
  606. if (pWHGIEPC && pWHGIEPC(&iecfg)) {
  607. // We were read proxy config successfully.
  608. success = true;
  609. if (iecfg.fAutoDetect) {
  610. proxy->autodetect = true;
  611. }
  612. if (iecfg.lpszAutoConfigUrl) {
  613. proxy->autoconfig_url = ToUtf8(iecfg.lpszAutoConfigUrl);
  614. GlobalFree(iecfg.lpszAutoConfigUrl);
  615. }
  616. if (iecfg.lpszProxyBypass) {
  617. proxy->bypass_list = ToUtf8(iecfg.lpszProxyBypass);
  618. GlobalFree(iecfg.lpszProxyBypass);
  619. }
  620. if (iecfg.lpszProxy) {
  621. if (!ProxyListMatch(purl, proxy->bypass_list, ';')) {
  622. ParseProxy(ToUtf8(iecfg.lpszProxy), proxy);
  623. }
  624. GlobalFree(iecfg.lpszProxy);
  625. }
  626. }
  627. FreeLibrary(winhttp_handle);
  628. return success;
  629. }
  630. // Uses the WinHTTP API to auto detect proxy for the given url. Firefox and IE
  631. // have slightly different option dialogs for proxy settings. In Firefox,
  632. // either a location of a proxy configuration file can be specified or auto
  633. // detection can be selected. In IE theese two options can be independently
  634. // selected. For the case where both options are selected (only IE) we try to
  635. // fetch the config file first, and if that fails we'll perform an auto
  636. // detection.
  637. //
  638. // Returns true if we successfully performed an auto detection not depending on
  639. // whether we found a proxy or not. Returns false on error.
  640. bool WinHttpAutoDetectProxyForUrl(const char* agent, const char* url,
  641. ProxyInfo* proxy) {
  642. Url<char> purl(url);
  643. bool success = true;
  644. HMODULE winhttp_handle = LoadLibrary(L"winhttp.dll");
  645. if (winhttp_handle == NULL) {
  646. LOG(LS_ERROR) << "Failed to load winhttp.dll.";
  647. return false;
  648. }
  649. pfnWinHttpOpen pWHO =
  650. reinterpret_cast<pfnWinHttpOpen>(GetProcAddress(winhttp_handle,
  651. "WinHttpOpen"));
  652. pfnWinHttpCloseHandle pWHCH =
  653. reinterpret_cast<pfnWinHttpCloseHandle>(
  654. GetProcAddress(winhttp_handle, "WinHttpCloseHandle"));
  655. pfnWinHttpGetProxyForUrl pWHGPFU =
  656. reinterpret_cast<pfnWinHttpGetProxyForUrl>(
  657. GetProcAddress(winhttp_handle, "WinHttpGetProxyForUrl"));
  658. if (pWHO && pWHCH && pWHGPFU) {
  659. if (HINTERNET hWinHttp = pWHO(ToUtf16(agent).c_str(),
  660. WINHTTP_ACCESS_TYPE_NO_PROXY,
  661. WINHTTP_NO_PROXY_NAME,
  662. WINHTTP_NO_PROXY_BYPASS,
  663. 0)) {
  664. BOOL result = FALSE;
  665. WINHTTP_PROXY_INFO info;
  666. memset(&info, 0, sizeof(info));
  667. if (proxy->autodetect) {
  668. // Use DHCP and DNS to try to find any proxy to use.
  669. WINHTTP_AUTOPROXY_OPTIONS options;
  670. memset(&options, 0, sizeof(options));
  671. options.fAutoLogonIfChallenged = TRUE;
  672. options.dwFlags |= WINHTTP_AUTOPROXY_AUTO_DETECT;
  673. options.dwAutoDetectFlags |= WINHTTP_AUTO_DETECT_TYPE_DHCP
  674. | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
  675. result = MyWinHttpGetProxyForUrl(
  676. pWHGPFU, hWinHttp, ToUtf16(url).c_str(), &options, &info);
  677. }
  678. if (!result && !proxy->autoconfig_url.empty()) {
  679. // We have the location of a proxy config file. Download it and
  680. // execute it to find proxy settings for our url.
  681. WINHTTP_AUTOPROXY_OPTIONS options;
  682. memset(&options, 0, sizeof(options));
  683. memset(&info, 0, sizeof(info));
  684. options.fAutoLogonIfChallenged = TRUE;
  685. std::wstring autoconfig_url16((ToUtf16)(proxy->autoconfig_url));
  686. options.dwFlags |= WINHTTP_AUTOPROXY_CONFIG_URL;
  687. options.lpszAutoConfigUrl = autoconfig_url16.c_str();
  688. result = MyWinHttpGetProxyForUrl(
  689. pWHGPFU, hWinHttp, ToUtf16(url).c_str(), &options, &info);
  690. }
  691. if (result) {
  692. // Either the given auto config url was valid or auto
  693. // detection found a proxy on this network.
  694. if (info.lpszProxy) {
  695. // TODO: Does this bypass list differ from the list
  696. // retreived from GetWinHttpProxySettings earlier?
  697. if (info.lpszProxyBypass) {
  698. proxy->bypass_list = ToUtf8(info.lpszProxyBypass);
  699. GlobalFree(info.lpszProxyBypass);
  700. } else {
  701. proxy->bypass_list.clear();
  702. }
  703. if (!ProxyListMatch(purl, proxy->bypass_list, ';')) {
  704. // Found proxy for this URL. If parsing the address turns
  705. // out ok then we are successful.
  706. success = ParseProxy(ToUtf8(info.lpszProxy), proxy);
  707. }
  708. GlobalFree(info.lpszProxy);
  709. }
  710. } else {
  711. // We could not find any proxy for this url.
  712. LOG(LS_INFO) << "No proxy detected for " << url;
  713. }
  714. pWHCH(hWinHttp);
  715. }
  716. } else {
  717. LOG(LS_ERROR) << "Failed loading WinHTTP functions.";
  718. success = false;
  719. }
  720. FreeLibrary(winhttp_handle);
  721. return success;
  722. }
  723. #if 0 // Below functions currently not used.
  724. bool GetJsProxySettings(const char* url, ProxyInfo* proxy) {
  725. Url<char> purl(url);
  726. bool success = false;
  727. if (HMODULE hModJS = LoadLibrary(_T("jsproxy.dll"))) {
  728. pfnInternetGetProxyInfo pIGPI =
  729. reinterpret_cast<pfnInternetGetProxyInfo>(
  730. GetProcAddress(hModJS, "InternetGetProxyInfo"));
  731. if (pIGPI) {
  732. char proxy[256], host[256];
  733. memset(proxy, 0, sizeof(proxy));
  734. char * ptr = proxy;
  735. DWORD proxylen = sizeof(proxy);
  736. std::string surl = Utf8String(url);
  737. DWORD hostlen = _snprintf(host, sizeof(host), "http%s://%S",
  738. purl.secure() ? "s" : "", purl.server());
  739. if (pIGPI(surl.data(), surl.size(), host, hostlen, &ptr, &proxylen)) {
  740. LOG(INFO) << "Proxy: " << proxy;
  741. } else {
  742. LOG_GLE(INFO) << "InternetGetProxyInfo";
  743. }
  744. }
  745. FreeLibrary(hModJS);
  746. }
  747. return success;
  748. }
  749. bool GetWmProxySettings(const char* url, ProxyInfo* proxy) {
  750. Url<char> purl(url);
  751. bool success = false;
  752. INSNetSourceCreator * nsc = 0;
  753. HRESULT hr = CoCreateInstance(CLSID_ClientNetManager, 0, CLSCTX_ALL,
  754. IID_INSNetSourceCreator, (LPVOID *) &nsc);
  755. if (SUCCEEDED(hr)) {
  756. if (SUCCEEDED(hr = nsc->Initialize())) {
  757. VARIANT dispatch;
  758. VariantInit(&dispatch);
  759. if (SUCCEEDED(hr = nsc->GetNetSourceAdminInterface(L"http", &dispatch))) {
  760. IWMSInternalAdminNetSource * ians = 0;
  761. if (SUCCEEDED(hr = dispatch.pdispVal->QueryInterface(
  762. IID_IWMSInternalAdminNetSource, (LPVOID *) &ians))) {
  763. _bstr_t host(purl.server());
  764. BSTR proxy = 0;
  765. BOOL bProxyEnabled = FALSE;
  766. DWORD port, context = 0;
  767. if (SUCCEEDED(hr = ians->FindProxyForURL(
  768. L"http", host, &bProxyEnabled, &proxy, &port, &context))) {
  769. success = true;
  770. if (bProxyEnabled) {
  771. _bstr_t sproxy = proxy;
  772. proxy->ptype = PT_HTTPS;
  773. proxy->host = sproxy;
  774. proxy->port = port;
  775. }
  776. }
  777. SysFreeString(proxy);
  778. if (FAILED(hr = ians->ShutdownProxyContext(context))) {
  779. LOG(LS_INFO) << "IWMSInternalAdminNetSource::ShutdownProxyContext"
  780. << "failed: " << hr;
  781. }
  782. ians->Release();
  783. }
  784. }
  785. VariantClear(&dispatch);
  786. if (FAILED(hr = nsc->Shutdown())) {
  787. LOG(LS_INFO) << "INSNetSourceCreator::Shutdown failed: " << hr;
  788. }
  789. }
  790. nsc->Release();
  791. }
  792. return success;
  793. }
  794. bool GetIePerConnectionProxySettings(const char* url, ProxyInfo* proxy) {
  795. Url<char> purl(url);
  796. bool success = false;
  797. INTERNET_PER_CONN_OPTION_LIST list;
  798. INTERNET_PER_CONN_OPTION options[3];
  799. memset(&list, 0, sizeof(list));
  800. memset(&options, 0, sizeof(options));
  801. list.dwSize = sizeof(list);
  802. list.dwOptionCount = 3;
  803. list.pOptions = options;
  804. options[0].dwOption = INTERNET_PER_CONN_FLAGS;
  805. options[1].dwOption = INTERNET_PER_CONN_PROXY_SERVER;
  806. options[2].dwOption = INTERNET_PER_CONN_PROXY_BYPASS;
  807. DWORD dwSize = sizeof(list);
  808. if (!InternetQueryOption(0, INTERNET_OPTION_PER_CONNECTION_OPTION, &list,
  809. &dwSize)) {
  810. LOG(LS_INFO) << "InternetQueryOption failed: " << GetLastError();
  811. } else if ((options[0].Value.dwValue & PROXY_TYPE_PROXY) != 0) {
  812. success = true;
  813. if (!ProxyListMatch(purl, nonnull(options[2].Value.pszValue), _T(';'))) {
  814. ParseProxy(nonnull(options[1].Value.pszValue), proxy);
  815. }
  816. } else if ((options[0].Value.dwValue & PROXY_TYPE_DIRECT) != 0) {
  817. success = true;
  818. } else {
  819. LOG(LS_INFO) << "unknown internet access type: "
  820. << options[0].Value.dwValue;
  821. }
  822. if (options[1].Value.pszValue) {
  823. GlobalFree(options[1].Value.pszValue);
  824. }
  825. if (options[2].Value.pszValue) {
  826. GlobalFree(options[2].Value.pszValue);
  827. }
  828. return success;
  829. }
  830. #endif // 0
  831. // Uses the InternetQueryOption function to retrieve proxy settings
  832. // from the registry. This will only give us the 'static' settings,
  833. // ie, not any information about auto config etc.
  834. bool GetIeLanProxySettings(const char* url, ProxyInfo* proxy) {
  835. Url<char> purl(url);
  836. bool success = false;
  837. wchar_t buffer[1024];
  838. memset(buffer, 0, sizeof(buffer));
  839. INTERNET_PROXY_INFO * info = reinterpret_cast<INTERNET_PROXY_INFO *>(buffer);
  840. DWORD dwSize = sizeof(buffer);
  841. if (!InternetQueryOption(0, INTERNET_OPTION_PROXY, info, &dwSize)) {
  842. LOG(LS_INFO) << "InternetQueryOption failed: " << GetLastError();
  843. } else if (info->dwAccessType == INTERNET_OPEN_TYPE_DIRECT) {
  844. success = true;
  845. } else if (info->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
  846. success = true;
  847. if (!ProxyListMatch(purl, nonnull(reinterpret_cast<const char*>(
  848. info->lpszProxyBypass)), ' ')) {
  849. ParseProxy(nonnull(reinterpret_cast<const char*>(info->lpszProxy)),
  850. proxy);
  851. }
  852. } else {
  853. LOG(LS_INFO) << "unknown internet access type: " << info->dwAccessType;
  854. }
  855. return success;
  856. }
  857. bool GetIeProxySettings(const char* agent, const char* url, ProxyInfo* proxy) {
  858. bool success = GetWinHttpProxySettings(url, proxy);
  859. if (!success) {
  860. // TODO: Should always call this if no proxy were detected by
  861. // GetWinHttpProxySettings?
  862. // WinHttp failed. Try using the InternetOptionQuery method instead.
  863. return GetIeLanProxySettings(url, proxy);
  864. }
  865. return true;
  866. }
  867. #endif // WIN32
  868. #ifdef OSX // OSX specific implementation for reading system wide
  869. // proxy settings.
  870. bool p_getProxyInfoForTypeFromDictWithKeys(ProxyInfo* proxy,
  871. ProxyType type,
  872. const CFDictionaryRef proxyDict,
  873. const CFStringRef enabledKey,
  874. const CFStringRef hostKey,
  875. const CFStringRef portKey) {
  876. // whether or not we set up the proxy info.
  877. bool result = false;
  878. // we use this as a scratch variable for determining if operations
  879. // succeeded.
  880. bool converted = false;
  881. // the data we need to construct the SocketAddress for the proxy.
  882. std::string hostname;
  883. int port;
  884. if ((proxyDict != NULL) &&
  885. (CFGetTypeID(proxyDict) == CFDictionaryGetTypeID())) {
  886. // CoreFoundation stuff that we'll have to get from
  887. // the dictionaries and interpret or convert into more usable formats.
  888. CFNumberRef enabledCFNum;
  889. CFNumberRef portCFNum;
  890. CFStringRef hostCFStr;
  891. enabledCFNum = (CFNumberRef)CFDictionaryGetValue(proxyDict, enabledKey);
  892. if (p_isCFNumberTrue(enabledCFNum)) {
  893. // let's see if we can get the address and port.
  894. hostCFStr = (CFStringRef)CFDictionaryGetValue(proxyDict, hostKey);
  895. converted = p_convertHostCFStringRefToCPPString(hostCFStr, hostname);
  896. if (converted) {
  897. portCFNum = (CFNumberRef)CFDictionaryGetValue(proxyDict, portKey);
  898. converted = p_convertCFNumberToInt(portCFNum, &port);
  899. if (converted) {
  900. // we have something enabled, with a hostname and a port.
  901. // That's sufficient to set up the proxy info.
  902. proxy->type = type;
  903. proxy->address.SetIP(hostname);
  904. proxy->address.SetPort(port);
  905. result = true;
  906. }
  907. }
  908. }
  909. }
  910. return result;
  911. }
  912. // Looks for proxy information in the given dictionary,
  913. // return true if it found sufficient information to define one,
  914. // false otherwise. This is guaranteed to not change the values in proxy
  915. // unless a full-fledged proxy description was discovered in the dictionary.
  916. // However, at the present time this does not support username or password.
  917. // Checks first for a SOCKS proxy, then for HTTPS, then HTTP.
  918. bool GetMacProxySettingsFromDictionary(ProxyInfo* proxy,
  919. const CFDictionaryRef proxyDict) {
  920. // the function result.
  921. bool gotProxy = false;
  922. // first we see if there's a SOCKS proxy in place.
  923. gotProxy = p_getProxyInfoForTypeFromDictWithKeys(proxy,
  924. PROXY_SOCKS5,
  925. proxyDict,
  926. kSCPropNetProxiesSOCKSEnable,
  927. kSCPropNetProxiesSOCKSProxy,
  928. kSCPropNetProxiesSOCKSPort);
  929. if (!gotProxy) {
  930. // okay, no SOCKS proxy, let's look for https.
  931. gotProxy = p_getProxyInfoForTypeFromDictWithKeys(proxy,
  932. PROXY_HTTPS,
  933. proxyDict,
  934. kSCPropNetProxiesHTTPSEnable,
  935. kSCPropNetProxiesHTTPSProxy,
  936. kSCPropNetProxiesHTTPSPort);
  937. if (!gotProxy) {
  938. // Finally, try HTTP proxy. Note that flute doesn't
  939. // differentiate between HTTPS and HTTP, hence we are using the
  940. // same flute type here, ie. PROXY_HTTPS.
  941. gotProxy = p_getProxyInfoForTypeFromDictWithKeys(
  942. proxy, PROXY_HTTPS, proxyDict, kSCPropNetProxiesHTTPEnable,
  943. kSCPropNetProxiesHTTPProxy, kSCPropNetProxiesHTTPPort);
  944. }
  945. }
  946. return gotProxy;
  947. }
  948. // TODO(hughv) Update keychain functions. They work on 10.8, but are depricated.
  949. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  950. bool p_putPasswordInProxyInfo(ProxyInfo* proxy) {
  951. bool result = true; // by default we assume we're good.
  952. // for all we know there isn't any password. We'll set to false
  953. // if we find a problem.
  954. // Ask the keychain for an internet password search for the given protocol.
  955. OSStatus oss = 0;
  956. SecKeychainAttributeList attrList;
  957. attrList.count = 3;
  958. SecKeychainAttribute attributes[3];
  959. attrList.attr = attributes;
  960. attributes[0].tag = kSecProtocolItemAttr;
  961. attributes[0].length = sizeof(SecProtocolType);
  962. SecProtocolType protocol;
  963. switch (proxy->type) {
  964. case PROXY_HTTPS :
  965. protocol = kSecProtocolTypeHTTPS;
  966. break;
  967. case PROXY_SOCKS5 :
  968. protocol = kSecProtocolTypeSOCKS;
  969. break;
  970. default :
  971. LOG(LS_ERROR) << "asked for proxy password for unknown proxy type.";
  972. result = false;
  973. break;
  974. }
  975. attributes[0].data = &protocol;
  976. UInt32 port = proxy->address.port();
  977. attributes[1].tag = kSecPortItemAttr;
  978. attributes[1].length = sizeof(UInt32);
  979. attributes[1].data = &port;
  980. std::string ip = proxy->address.ipaddr().ToString();
  981. attributes[2].tag = kSecServerItemAttr;
  982. attributes[2].length = ip.length();
  983. attributes[2].data = const_cast<char*>(ip.c_str());
  984. if (result) {
  985. LOG(LS_INFO) << "trying to get proxy username/password";
  986. SecKeychainSearchRef sref;
  987. oss = SecKeychainSearchCreateFromAttributes(NULL,
  988. kSecInternetPasswordItemClass,
  989. &attrList, &sref);
  990. if (0 == oss) {
  991. LOG(LS_INFO) << "SecKeychainSearchCreateFromAttributes was good";
  992. // Get the first item, if there is one.
  993. SecKeychainItemRef iref;
  994. oss = SecKeychainSearchCopyNext(sref, &iref);
  995. if (0 == oss) {
  996. LOG(LS_INFO) << "...looks like we have the username/password data";
  997. // If there is, get the username and the password.
  998. SecKeychainAttributeInfo attribsToGet;
  999. attribsToGet.count = 1;
  1000. UInt32 tag = kSecAccountItemAttr;
  1001. UInt32 format = CSSM_DB_ATTRIBUTE_FORMAT_STRING;
  1002. void *data;
  1003. UInt32 length;
  1004. SecKeychainAttributeList *localList;
  1005. attribsToGet.tag = &tag;
  1006. attribsToGet.format = &format;
  1007. OSStatus copyres = SecKeychainItemCopyAttributesAndData(iref,
  1008. &attribsToGet,
  1009. NULL,
  1010. &localList,
  1011. &length,
  1012. &data);
  1013. if (0 == copyres) {
  1014. LOG(LS_INFO) << "...and we can pull it out.";
  1015. // now, we know from experimentation (sadly not from docs)
  1016. // that the username is in the local attribute list,
  1017. // and the password in the data,
  1018. // both without null termination but with info on their length.
  1019. // grab the password from the data.
  1020. std::string password;
  1021. password.append(static_cast<const char*>(data), length);
  1022. // make the password into a CryptString
  1023. // huh, at the time of writing, you can't.
  1024. // so we'll skip that for now and come back to it later.
  1025. // now put the username in the proxy.
  1026. if (1 <= localList->attr->length) {
  1027. proxy->username.append(
  1028. static_cast<const char*>(localList->attr->data),
  1029. localList->attr->length);
  1030. LOG(LS_INFO) << "username is " << proxy->username;
  1031. } else {
  1032. LOG(LS_ERROR) << "got keychain entry with no username";
  1033. result = false;
  1034. }
  1035. } else {
  1036. LOG(LS_ERROR) << "couldn't copy info from keychain.";
  1037. result = false;
  1038. }
  1039. SecKeychainItemFreeAttributesAndData(localList, data);
  1040. } else if (errSecItemNotFound == oss) {
  1041. LOG(LS_INFO) << "...username/password info not found";
  1042. } else {
  1043. // oooh, neither 0 nor itemNotFound.
  1044. LOG(LS_ERROR) << "Couldn't get keychain information, error code" << oss;
  1045. result = false;
  1046. }
  1047. } else if (errSecItemNotFound == oss) { // noop
  1048. } else {
  1049. // oooh, neither 0 nor itemNotFound.
  1050. LOG(LS_ERROR) << "Couldn't get keychain information, error code" << oss;
  1051. result = false;
  1052. }
  1053. }
  1054. return result;
  1055. }
  1056. bool GetMacProxySettings(ProxyInfo* proxy) {
  1057. // based on the Apple Technical Q&A QA1234
  1058. // http://developer.apple.com/qa/qa2001/qa1234.html
  1059. CFDictionaryRef proxyDict = SCDynamicStoreCopyProxies(NULL);
  1060. bool result = false;
  1061. if (proxyDict != NULL) {
  1062. // sending it off to another function makes it easier to unit test
  1063. // since we can make our own dictionary to hand to that function.
  1064. result = GetMacProxySettingsFromDictionary(proxy, proxyDict);
  1065. if (result) {
  1066. result = p_putPasswordInProxyInfo(proxy);
  1067. }
  1068. // We created the dictionary with something that had the
  1069. // word 'copy' in it, so we have to release it, according
  1070. // to the Carbon memory management standards.
  1071. CFRelease(proxyDict);
  1072. } else {
  1073. LOG(LS_ERROR) << "SCDynamicStoreCopyProxies failed";
  1074. }
  1075. return result;
  1076. }
  1077. #endif // OSX
  1078. bool AutoDetectProxySettings(const char* agent, const char* url,
  1079. ProxyInfo* proxy) {
  1080. #ifdef WIN32
  1081. return WinHttpAutoDetectProxyForUrl(agent, url, proxy);
  1082. #else
  1083. LOG(LS_WARNING) << "Proxy auto-detection not implemented for this platform";
  1084. return false;
  1085. #endif
  1086. }
  1087. bool GetSystemDefaultProxySettings(const char* agent, const char* url,
  1088. ProxyInfo* proxy) {
  1089. #ifdef WIN32
  1090. return GetIeProxySettings(agent, url, proxy);
  1091. #elif OSX
  1092. return GetMacProxySettings(proxy);
  1093. #else
  1094. // TODO: Get System settings if browser is not firefox.
  1095. return GetFirefoxProxySettings(url, proxy);
  1096. #endif
  1097. }
  1098. bool GetProxySettingsForUrl(const char* agent, const char* url,
  1099. ProxyInfo& proxy, bool long_operation) {
  1100. UserAgent a = GetAgent(agent);
  1101. bool result;
  1102. switch (a) {
  1103. case UA_FIREFOX: {
  1104. result = GetFirefoxProxySettings(url, &proxy);
  1105. break;
  1106. }
  1107. #ifdef WIN32
  1108. case UA_INTERNETEXPLORER:
  1109. result = GetIeProxySettings(agent, url, &proxy);
  1110. break;
  1111. case UA_UNKNOWN:
  1112. // Agent not defined, check default browser.
  1113. if (IsDefaultBrowserFirefox()) {
  1114. result = GetFirefoxProxySettings(url, &proxy);
  1115. } else {
  1116. result = GetIeProxySettings(agent, url, &proxy);
  1117. }
  1118. break;
  1119. #endif // WIN32
  1120. default:
  1121. result = GetSystemDefaultProxySettings(agent, url, &proxy);
  1122. break;
  1123. }
  1124. // TODO: Consider using the 'long_operation' parameter to
  1125. // decide whether to do the auto detection.
  1126. if (result && (proxy.autodetect ||
  1127. !proxy.autoconfig_url.empty())) {
  1128. // Use WinHTTP to auto detect proxy for us.
  1129. result = AutoDetectProxySettings(agent, url, &proxy);
  1130. if (!result) {
  1131. // Either auto detection is not supported or we simply didn't
  1132. // find any proxy, reset type.
  1133. proxy.type = talk_base::PROXY_NONE;
  1134. }
  1135. }
  1136. return result;
  1137. }
  1138. } // namespace talk_base