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.

1055 lines
31 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 <time.h>
  28. #ifdef WIN32
  29. #define WIN32_LEAN_AND_MEAN
  30. #include <windows.h>
  31. #include <winsock2.h>
  32. #include <ws2tcpip.h>
  33. #define SECURITY_WIN32
  34. #include <security.h>
  35. #endif
  36. #include "talk/base/httpcommon-inl.h"
  37. #include "talk/base/base64.h"
  38. #include "talk/base/common.h"
  39. #include "talk/base/cryptstring.h"
  40. #include "talk/base/httpcommon.h"
  41. #include "talk/base/socketaddress.h"
  42. #include "talk/base/stringdigest.h"
  43. #include "talk/base/stringencode.h"
  44. #include "talk/base/stringutils.h"
  45. namespace talk_base {
  46. #ifdef WIN32
  47. extern const ConstantLabel SECURITY_ERRORS[];
  48. #endif
  49. //////////////////////////////////////////////////////////////////////
  50. // Enum - TODO: expose globally later?
  51. //////////////////////////////////////////////////////////////////////
  52. bool find_string(size_t& index, const std::string& needle,
  53. const char* const haystack[], size_t max_index) {
  54. for (index=0; index<max_index; ++index) {
  55. if (_stricmp(needle.c_str(), haystack[index]) == 0) {
  56. return true;
  57. }
  58. }
  59. return false;
  60. }
  61. template<class E>
  62. struct Enum {
  63. static const char** Names;
  64. static size_t Size;
  65. static inline const char* Name(E val) { return Names[val]; }
  66. static inline bool Parse(E& val, const std::string& name) {
  67. size_t index;
  68. if (!find_string(index, name, Names, Size))
  69. return false;
  70. val = static_cast<E>(index);
  71. return true;
  72. }
  73. E val;
  74. inline operator E&() { return val; }
  75. inline Enum& operator=(E rhs) { val = rhs; return *this; }
  76. inline const char* name() const { return Name(val); }
  77. inline bool assign(const std::string& name) { return Parse(val, name); }
  78. inline Enum& operator=(const std::string& rhs) { assign(rhs); return *this; }
  79. };
  80. #define ENUM(e,n) \
  81. template<> const char** Enum<e>::Names = n; \
  82. template<> size_t Enum<e>::Size = sizeof(n)/sizeof(n[0])
  83. //////////////////////////////////////////////////////////////////////
  84. // HttpCommon
  85. //////////////////////////////////////////////////////////////////////
  86. static const char* kHttpVersions[HVER_LAST+1] = {
  87. "1.0", "1.1", "Unknown"
  88. };
  89. ENUM(HttpVersion, kHttpVersions);
  90. static const char* kHttpVerbs[HV_LAST+1] = {
  91. "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD"
  92. };
  93. ENUM(HttpVerb, kHttpVerbs);
  94. static const char* kHttpHeaders[HH_LAST+1] = {
  95. "Age",
  96. "Cache-Control",
  97. "Connection",
  98. "Content-Disposition",
  99. "Content-Length",
  100. "Content-Range",
  101. "Content-Type",
  102. "Cookie",
  103. "Date",
  104. "ETag",
  105. "Expires",
  106. "Host",
  107. "If-Modified-Since",
  108. "If-None-Match",
  109. "Keep-Alive",
  110. "Last-Modified",
  111. "Location",
  112. "Proxy-Authenticate",
  113. "Proxy-Authorization",
  114. "Proxy-Connection",
  115. "Range",
  116. "Set-Cookie",
  117. "TE",
  118. "Trailers",
  119. "Transfer-Encoding",
  120. "Upgrade",
  121. "User-Agent",
  122. "WWW-Authenticate",
  123. };
  124. ENUM(HttpHeader, kHttpHeaders);
  125. const char* ToString(HttpVersion version) {
  126. return Enum<HttpVersion>::Name(version);
  127. }
  128. bool FromString(HttpVersion& version, const std::string& str) {
  129. return Enum<HttpVersion>::Parse(version, str);
  130. }
  131. const char* ToString(HttpVerb verb) {
  132. return Enum<HttpVerb>::Name(verb);
  133. }
  134. bool FromString(HttpVerb& verb, const std::string& str) {
  135. return Enum<HttpVerb>::Parse(verb, str);
  136. }
  137. const char* ToString(HttpHeader header) {
  138. return Enum<HttpHeader>::Name(header);
  139. }
  140. bool FromString(HttpHeader& header, const std::string& str) {
  141. return Enum<HttpHeader>::Parse(header, str);
  142. }
  143. bool HttpCodeHasBody(uint32 code) {
  144. return !HttpCodeIsInformational(code)
  145. && (code != HC_NO_CONTENT) && (code != HC_NOT_MODIFIED);
  146. }
  147. bool HttpCodeIsCacheable(uint32 code) {
  148. switch (code) {
  149. case HC_OK:
  150. case HC_NON_AUTHORITATIVE:
  151. case HC_PARTIAL_CONTENT:
  152. case HC_MULTIPLE_CHOICES:
  153. case HC_MOVED_PERMANENTLY:
  154. case HC_GONE:
  155. return true;
  156. default:
  157. return false;
  158. }
  159. }
  160. bool HttpHeaderIsEndToEnd(HttpHeader header) {
  161. switch (header) {
  162. case HH_CONNECTION:
  163. case HH_KEEP_ALIVE:
  164. case HH_PROXY_AUTHENTICATE:
  165. case HH_PROXY_AUTHORIZATION:
  166. case HH_PROXY_CONNECTION: // Note part of RFC... this is non-standard header
  167. case HH_TE:
  168. case HH_TRAILERS:
  169. case HH_TRANSFER_ENCODING:
  170. case HH_UPGRADE:
  171. return false;
  172. default:
  173. return true;
  174. }
  175. }
  176. bool HttpHeaderIsCollapsible(HttpHeader header) {
  177. switch (header) {
  178. case HH_SET_COOKIE:
  179. case HH_PROXY_AUTHENTICATE:
  180. case HH_WWW_AUTHENTICATE:
  181. return false;
  182. default:
  183. return true;
  184. }
  185. }
  186. bool HttpShouldKeepAlive(const HttpData& data) {
  187. std::string connection;
  188. if ((data.hasHeader(HH_PROXY_CONNECTION, &connection)
  189. || data.hasHeader(HH_CONNECTION, &connection))) {
  190. return (_stricmp(connection.c_str(), "Keep-Alive") == 0);
  191. }
  192. return (data.version >= HVER_1_1);
  193. }
  194. namespace {
  195. inline bool IsEndOfAttributeName(size_t pos, size_t len, const char * data) {
  196. if (pos >= len)
  197. return true;
  198. if (isspace(static_cast<unsigned char>(data[pos])))
  199. return true;
  200. // The reason for this complexity is that some attributes may contain trailing
  201. // equal signs (like base64 tokens in Negotiate auth headers)
  202. if ((pos+1 < len) && (data[pos] == '=') &&
  203. !isspace(static_cast<unsigned char>(data[pos+1])) &&
  204. (data[pos+1] != '=')) {
  205. return true;
  206. }
  207. return false;
  208. }
  209. // TODO: unittest for EscapeAttribute and HttpComposeAttributes.
  210. std::string EscapeAttribute(const std::string& attribute) {
  211. const size_t kMaxLength = attribute.length() * 2 + 1;
  212. char* buffer = STACK_ARRAY(char, kMaxLength);
  213. size_t len = escape(buffer, kMaxLength, attribute.data(), attribute.length(),
  214. "\"", '\\');
  215. return std::string(buffer, len);
  216. }
  217. } // anonymous namespace
  218. void HttpComposeAttributes(const HttpAttributeList& attributes, char separator,
  219. std::string* composed) {
  220. std::stringstream ss;
  221. for (size_t i=0; i<attributes.size(); ++i) {
  222. if (i > 0) {
  223. ss << separator << " ";
  224. }
  225. ss << attributes[i].first;
  226. if (!attributes[i].second.empty()) {
  227. ss << "=\"" << EscapeAttribute(attributes[i].second) << "\"";
  228. }
  229. }
  230. *composed = ss.str();
  231. }
  232. void HttpParseAttributes(const char * data, size_t len,
  233. HttpAttributeList& attributes) {
  234. size_t pos = 0;
  235. while (true) {
  236. // Skip leading whitespace
  237. while ((pos < len) && isspace(static_cast<unsigned char>(data[pos]))) {
  238. ++pos;
  239. }
  240. // End of attributes?
  241. if (pos >= len)
  242. return;
  243. // Find end of attribute name
  244. size_t start = pos;
  245. while (!IsEndOfAttributeName(pos, len, data)) {
  246. ++pos;
  247. }
  248. HttpAttribute attribute;
  249. attribute.first.assign(data + start, data + pos);
  250. // Attribute has value?
  251. if ((pos < len) && (data[pos] == '=')) {
  252. ++pos; // Skip '='
  253. // Check if quoted value
  254. if ((pos < len) && (data[pos] == '"')) {
  255. while (++pos < len) {
  256. if (data[pos] == '"') {
  257. ++pos;
  258. break;
  259. }
  260. if ((data[pos] == '\\') && (pos + 1 < len))
  261. ++pos;
  262. attribute.second.append(1, data[pos]);
  263. }
  264. } else {
  265. while ((pos < len) &&
  266. !isspace(static_cast<unsigned char>(data[pos])) &&
  267. (data[pos] != ',')) {
  268. attribute.second.append(1, data[pos++]);
  269. }
  270. }
  271. }
  272. attributes.push_back(attribute);
  273. if ((pos < len) && (data[pos] == ',')) ++pos; // Skip ','
  274. }
  275. }
  276. bool HttpHasAttribute(const HttpAttributeList& attributes,
  277. const std::string& name,
  278. std::string* value) {
  279. for (HttpAttributeList::const_iterator it = attributes.begin();
  280. it != attributes.end(); ++it) {
  281. if (it->first == name) {
  282. if (value) {
  283. *value = it->second;
  284. }
  285. return true;
  286. }
  287. }
  288. return false;
  289. }
  290. bool HttpHasNthAttribute(HttpAttributeList& attributes,
  291. size_t index,
  292. std::string* name,
  293. std::string* value) {
  294. if (index >= attributes.size())
  295. return false;
  296. if (name)
  297. *name = attributes[index].first;
  298. if (value)
  299. *value = attributes[index].second;
  300. return true;
  301. }
  302. bool HttpDateToSeconds(const std::string& date, time_t* seconds) {
  303. const char* const kTimeZones[] = {
  304. "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT",
  305. "A", "B", "C", "D", "E", "F", "G", "H", "I", "K", "L", "M",
  306. "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"
  307. };
  308. const int kTimeZoneOffsets[] = {
  309. 0, 0, -5, -4, -6, -5, -7, -6, -8, -7,
  310. -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12,
  311. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
  312. };
  313. ASSERT(NULL != seconds);
  314. struct tm tval;
  315. memset(&tval, 0, sizeof(tval));
  316. char month[4], zone[6];
  317. memset(month, 0, sizeof(month));
  318. memset(zone, 0, sizeof(zone));
  319. if (7 != sscanf(date.c_str(), "%*3s, %d %3s %d %d:%d:%d %5c",
  320. &tval.tm_mday, month, &tval.tm_year,
  321. &tval.tm_hour, &tval.tm_min, &tval.tm_sec, zone)) {
  322. return false;
  323. }
  324. switch (toupper(month[2])) {
  325. case 'N': tval.tm_mon = (month[1] == 'A') ? 0 : 5; break;
  326. case 'B': tval.tm_mon = 1; break;
  327. case 'R': tval.tm_mon = (month[0] == 'M') ? 2 : 3; break;
  328. case 'Y': tval.tm_mon = 4; break;
  329. case 'L': tval.tm_mon = 6; break;
  330. case 'G': tval.tm_mon = 7; break;
  331. case 'P': tval.tm_mon = 8; break;
  332. case 'T': tval.tm_mon = 9; break;
  333. case 'V': tval.tm_mon = 10; break;
  334. case 'C': tval.tm_mon = 11; break;
  335. }
  336. tval.tm_year -= 1900;
  337. size_t gmt, non_gmt = mktime(&tval);
  338. if ((zone[0] == '+') || (zone[0] == '-')) {
  339. if (!isdigit(zone[1]) || !isdigit(zone[2])
  340. || !isdigit(zone[3]) || !isdigit(zone[4])) {
  341. return false;
  342. }
  343. int hours = (zone[1] - '0') * 10 + (zone[2] - '0');
  344. int minutes = (zone[3] - '0') * 10 + (zone[4] - '0');
  345. int offset = (hours * 60 + minutes) * 60;
  346. gmt = non_gmt + ((zone[0] == '+') ? offset : -offset);
  347. } else {
  348. size_t zindex;
  349. if (!find_string(zindex, zone, kTimeZones, ARRAY_SIZE(kTimeZones))) {
  350. return false;
  351. }
  352. gmt = non_gmt + kTimeZoneOffsets[zindex] * 60 * 60;
  353. }
  354. // TODO: Android should support timezone, see b/2441195
  355. #if defined(OSX) || defined(ANDROID) || defined(BSD)
  356. tm *tm_for_timezone = localtime((time_t *)&gmt);
  357. *seconds = gmt + tm_for_timezone->tm_gmtoff;
  358. #else
  359. *seconds = gmt - timezone;
  360. #endif
  361. return true;
  362. }
  363. std::string HttpAddress(const SocketAddress& address, bool secure) {
  364. return (address.port() == HttpDefaultPort(secure))
  365. ? address.hostname() : address.ToString();
  366. }
  367. //////////////////////////////////////////////////////////////////////
  368. // HttpData
  369. //////////////////////////////////////////////////////////////////////
  370. void
  371. HttpData::clear(bool release_document) {
  372. // Clear headers first, since releasing a document may have far-reaching
  373. // effects.
  374. headers_.clear();
  375. if (release_document) {
  376. document.reset();
  377. }
  378. }
  379. void
  380. HttpData::copy(const HttpData& src) {
  381. headers_ = src.headers_;
  382. }
  383. void
  384. HttpData::changeHeader(const std::string& name, const std::string& value,
  385. HeaderCombine combine) {
  386. if (combine == HC_AUTO) {
  387. HttpHeader header;
  388. // Unrecognized headers are collapsible
  389. combine = !FromString(header, name) || HttpHeaderIsCollapsible(header)
  390. ? HC_YES : HC_NO;
  391. } else if (combine == HC_REPLACE) {
  392. headers_.erase(name);
  393. combine = HC_NO;
  394. }
  395. // At this point, combine is one of (YES, NO, NEW)
  396. if (combine != HC_NO) {
  397. HeaderMap::iterator it = headers_.find(name);
  398. if (it != headers_.end()) {
  399. if (combine == HC_YES) {
  400. it->second.append(",");
  401. it->second.append(value);
  402. }
  403. return;
  404. }
  405. }
  406. headers_.insert(HeaderMap::value_type(name, value));
  407. }
  408. size_t HttpData::clearHeader(const std::string& name) {
  409. return headers_.erase(name);
  410. }
  411. HttpData::iterator HttpData::clearHeader(iterator header) {
  412. iterator deprecated = header++;
  413. headers_.erase(deprecated);
  414. return header;
  415. }
  416. bool
  417. HttpData::hasHeader(const std::string& name, std::string* value) const {
  418. HeaderMap::const_iterator it = headers_.find(name);
  419. if (it == headers_.end()) {
  420. return false;
  421. } else if (value) {
  422. *value = it->second;
  423. }
  424. return true;
  425. }
  426. void HttpData::setContent(const std::string& content_type,
  427. StreamInterface* document) {
  428. setHeader(HH_CONTENT_TYPE, content_type);
  429. setDocumentAndLength(document);
  430. }
  431. void HttpData::setDocumentAndLength(StreamInterface* document) {
  432. // TODO: Consider calling Rewind() here?
  433. ASSERT(!hasHeader(HH_CONTENT_LENGTH, NULL));
  434. ASSERT(!hasHeader(HH_TRANSFER_ENCODING, NULL));
  435. ASSERT(document != NULL);
  436. this->document.reset(document);
  437. size_t content_length = 0;
  438. if (this->document->GetAvailable(&content_length)) {
  439. char buffer[32];
  440. sprintfn(buffer, sizeof(buffer), "%d", content_length);
  441. setHeader(HH_CONTENT_LENGTH, buffer);
  442. } else {
  443. setHeader(HH_TRANSFER_ENCODING, "chunked");
  444. }
  445. }
  446. //
  447. // HttpRequestData
  448. //
  449. void
  450. HttpRequestData::clear(bool release_document) {
  451. verb = HV_GET;
  452. path.clear();
  453. HttpData::clear(release_document);
  454. }
  455. void
  456. HttpRequestData::copy(const HttpRequestData& src) {
  457. verb = src.verb;
  458. path = src.path;
  459. HttpData::copy(src);
  460. }
  461. size_t
  462. HttpRequestData::formatLeader(char* buffer, size_t size) const {
  463. ASSERT(path.find(' ') == std::string::npos);
  464. return sprintfn(buffer, size, "%s %.*s HTTP/%s", ToString(verb), path.size(),
  465. path.data(), ToString(version));
  466. }
  467. HttpError
  468. HttpRequestData::parseLeader(const char* line, size_t len) {
  469. UNUSED(len);
  470. unsigned int vmajor, vminor;
  471. int vend, dstart, dend;
  472. if ((sscanf(line, "%*s%n %n%*s%n HTTP/%u.%u", &vend, &dstart, &dend,
  473. &vmajor, &vminor) != 2)
  474. || (vmajor != 1)) {
  475. return HE_PROTOCOL;
  476. }
  477. if (vminor == 0) {
  478. version = HVER_1_0;
  479. } else if (vminor == 1) {
  480. version = HVER_1_1;
  481. } else {
  482. return HE_PROTOCOL;
  483. }
  484. std::string sverb(line, vend);
  485. if (!FromString(verb, sverb.c_str())) {
  486. return HE_PROTOCOL; // !?! HC_METHOD_NOT_SUPPORTED?
  487. }
  488. path.assign(line + dstart, line + dend);
  489. return HE_NONE;
  490. }
  491. bool HttpRequestData::getAbsoluteUri(std::string* uri) const {
  492. if (HV_CONNECT == verb)
  493. return false;
  494. Url<char> url(path);
  495. if (url.valid()) {
  496. uri->assign(path);
  497. return true;
  498. }
  499. std::string host;
  500. if (!hasHeader(HH_HOST, &host))
  501. return false;
  502. url.set_address(host);
  503. url.set_full_path(path);
  504. uri->assign(url.url());
  505. return url.valid();
  506. }
  507. bool HttpRequestData::getRelativeUri(std::string* host,
  508. std::string* path) const
  509. {
  510. if (HV_CONNECT == verb)
  511. return false;
  512. Url<char> url(this->path);
  513. if (url.valid()) {
  514. host->assign(url.address());
  515. path->assign(url.full_path());
  516. return true;
  517. }
  518. if (!hasHeader(HH_HOST, host))
  519. return false;
  520. path->assign(this->path);
  521. return true;
  522. }
  523. //
  524. // HttpResponseData
  525. //
  526. void
  527. HttpResponseData::clear(bool release_document) {
  528. scode = HC_INTERNAL_SERVER_ERROR;
  529. message.clear();
  530. HttpData::clear(release_document);
  531. }
  532. void
  533. HttpResponseData::copy(const HttpResponseData& src) {
  534. scode = src.scode;
  535. message = src.message;
  536. HttpData::copy(src);
  537. }
  538. void
  539. HttpResponseData::set_success(uint32 scode) {
  540. this->scode = scode;
  541. message.clear();
  542. setHeader(HH_CONTENT_LENGTH, "0", false);
  543. }
  544. void
  545. HttpResponseData::set_success(const std::string& content_type,
  546. StreamInterface* document,
  547. uint32 scode) {
  548. this->scode = scode;
  549. message.erase(message.begin(), message.end());
  550. setContent(content_type, document);
  551. }
  552. void
  553. HttpResponseData::set_redirect(const std::string& location, uint32 scode) {
  554. this->scode = scode;
  555. message.clear();
  556. setHeader(HH_LOCATION, location);
  557. setHeader(HH_CONTENT_LENGTH, "0", false);
  558. }
  559. void
  560. HttpResponseData::set_error(uint32 scode) {
  561. this->scode = scode;
  562. message.clear();
  563. setHeader(HH_CONTENT_LENGTH, "0", false);
  564. }
  565. size_t
  566. HttpResponseData::formatLeader(char* buffer, size_t size) const {
  567. size_t len = sprintfn(buffer, size, "HTTP/%s %lu", ToString(version), scode);
  568. if (!message.empty()) {
  569. len += sprintfn(buffer + len, size - len, " %.*s",
  570. message.size(), message.data());
  571. }
  572. return len;
  573. }
  574. HttpError
  575. HttpResponseData::parseLeader(const char* line, size_t len) {
  576. size_t pos = 0;
  577. unsigned int vmajor, vminor, temp_scode;
  578. int temp_pos;
  579. if (sscanf(line, "HTTP %u%n",
  580. &temp_scode, &temp_pos) == 1) {
  581. // This server's response has no version. :( NOTE: This happens for every
  582. // response to requests made from Chrome plugins, regardless of the server's
  583. // behaviour.
  584. LOG(LS_VERBOSE) << "HTTP version missing from response";
  585. version = HVER_UNKNOWN;
  586. } else if ((sscanf(line, "HTTP/%u.%u %u%n",
  587. &vmajor, &vminor, &temp_scode, &temp_pos) == 3)
  588. && (vmajor == 1)) {
  589. // This server's response does have a version.
  590. if (vminor == 0) {
  591. version = HVER_1_0;
  592. } else if (vminor == 1) {
  593. version = HVER_1_1;
  594. } else {
  595. return HE_PROTOCOL;
  596. }
  597. } else {
  598. return HE_PROTOCOL;
  599. }
  600. scode = temp_scode;
  601. pos = static_cast<size_t>(temp_pos);
  602. while ((pos < len) && isspace(static_cast<unsigned char>(line[pos]))) ++pos;
  603. message.assign(line + pos, len - pos);
  604. return HE_NONE;
  605. }
  606. //////////////////////////////////////////////////////////////////////
  607. // Http Authentication
  608. //////////////////////////////////////////////////////////////////////
  609. #define TEST_DIGEST 0
  610. #if TEST_DIGEST
  611. /*
  612. const char * const DIGEST_CHALLENGE =
  613. "Digest realm=\"testrealm@host.com\","
  614. " qop=\"auth,auth-int\","
  615. " nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\","
  616. " opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"";
  617. const char * const DIGEST_METHOD = "GET";
  618. const char * const DIGEST_URI =
  619. "/dir/index.html";;
  620. const char * const DIGEST_CNONCE =
  621. "0a4f113b";
  622. const char * const DIGEST_RESPONSE =
  623. "6629fae49393a05397450978507c4ef1";
  624. //user_ = "Mufasa";
  625. //pass_ = "Circle Of Life";
  626. */
  627. const char * const DIGEST_CHALLENGE =
  628. "Digest realm=\"Squid proxy-caching web server\","
  629. " nonce=\"Nny4QuC5PwiSDixJ\","
  630. " qop=\"auth\","
  631. " stale=false";
  632. const char * const DIGEST_URI =
  633. "/";
  634. const char * const DIGEST_CNONCE =
  635. "6501d58e9a21cee1e7b5fec894ded024";
  636. const char * const DIGEST_RESPONSE =
  637. "edffcb0829e755838b073a4a42de06bc";
  638. #endif
  639. std::string quote(const std::string& str) {
  640. std::string result;
  641. result.push_back('"');
  642. for (size_t i=0; i<str.size(); ++i) {
  643. if ((str[i] == '"') || (str[i] == '\\'))
  644. result.push_back('\\');
  645. result.push_back(str[i]);
  646. }
  647. result.push_back('"');
  648. return result;
  649. }
  650. #ifdef WIN32
  651. struct NegotiateAuthContext : public HttpAuthContext {
  652. CredHandle cred;
  653. CtxtHandle ctx;
  654. size_t steps;
  655. bool specified_credentials;
  656. NegotiateAuthContext(const std::string& auth, CredHandle c1, CtxtHandle c2)
  657. : HttpAuthContext(auth), cred(c1), ctx(c2), steps(0),
  658. specified_credentials(false)
  659. { }
  660. virtual ~NegotiateAuthContext() {
  661. DeleteSecurityContext(&ctx);
  662. FreeCredentialsHandle(&cred);
  663. }
  664. };
  665. #endif // WIN32
  666. HttpAuthResult HttpAuthenticate(
  667. const char * challenge, size_t len,
  668. const SocketAddress& server,
  669. const std::string& method, const std::string& uri,
  670. const std::string& username, const CryptString& password,
  671. HttpAuthContext *& context, std::string& response, std::string& auth_method)
  672. {
  673. #if TEST_DIGEST
  674. challenge = DIGEST_CHALLENGE;
  675. len = strlen(challenge);
  676. #endif
  677. HttpAttributeList args;
  678. HttpParseAttributes(challenge, len, args);
  679. HttpHasNthAttribute(args, 0, &auth_method, NULL);
  680. if (context && (context->auth_method != auth_method))
  681. return HAR_IGNORE;
  682. // BASIC
  683. if (_stricmp(auth_method.c_str(), "basic") == 0) {
  684. if (context)
  685. return HAR_CREDENTIALS; // Bad credentials
  686. if (username.empty())
  687. return HAR_CREDENTIALS; // Missing credentials
  688. context = new HttpAuthContext(auth_method);
  689. // TODO: convert sensitive to a secure buffer that gets securely deleted
  690. //std::string decoded = username + ":" + password;
  691. size_t len = username.size() + password.GetLength() + 2;
  692. char * sensitive = new char[len];
  693. size_t pos = strcpyn(sensitive, len, username.data(), username.size());
  694. pos += strcpyn(sensitive + pos, len - pos, ":");
  695. password.CopyTo(sensitive + pos, true);
  696. response = auth_method;
  697. response.append(" ");
  698. // TODO: create a sensitive-source version of Base64::encode
  699. response.append(Base64::Encode(sensitive));
  700. memset(sensitive, 0, len);
  701. delete [] sensitive;
  702. return HAR_RESPONSE;
  703. }
  704. // DIGEST
  705. if (_stricmp(auth_method.c_str(), "digest") == 0) {
  706. if (context)
  707. return HAR_CREDENTIALS; // Bad credentials
  708. if (username.empty())
  709. return HAR_CREDENTIALS; // Missing credentials
  710. context = new HttpAuthContext(auth_method);
  711. std::string cnonce, ncount;
  712. #if TEST_DIGEST
  713. method = DIGEST_METHOD;
  714. uri = DIGEST_URI;
  715. cnonce = DIGEST_CNONCE;
  716. #else
  717. char buffer[256];
  718. sprintf(buffer, "%d", static_cast<int>(time(0)));
  719. cnonce = MD5(buffer);
  720. #endif
  721. ncount = "00000001";
  722. std::string realm, nonce, qop, opaque;
  723. HttpHasAttribute(args, "realm", &realm);
  724. HttpHasAttribute(args, "nonce", &nonce);
  725. bool has_qop = HttpHasAttribute(args, "qop", &qop);
  726. bool has_opaque = HttpHasAttribute(args, "opaque", &opaque);
  727. // TODO: convert sensitive to be secure buffer
  728. //std::string A1 = username + ":" + realm + ":" + password;
  729. size_t len = username.size() + realm.size() + password.GetLength() + 3;
  730. char * sensitive = new char[len]; // A1
  731. size_t pos = strcpyn(sensitive, len, username.data(), username.size());
  732. pos += strcpyn(sensitive + pos, len - pos, ":");
  733. pos += strcpyn(sensitive + pos, len - pos, realm.c_str());
  734. pos += strcpyn(sensitive + pos, len - pos, ":");
  735. password.CopyTo(sensitive + pos, true);
  736. std::string A2 = method + ":" + uri;
  737. std::string middle;
  738. if (has_qop) {
  739. qop = "auth";
  740. middle = nonce + ":" + ncount + ":" + cnonce + ":" + qop;
  741. } else {
  742. middle = nonce;
  743. }
  744. std::string HA1 = MD5(sensitive);
  745. memset(sensitive, 0, len);
  746. delete [] sensitive;
  747. std::string HA2 = MD5(A2);
  748. std::string dig_response = MD5(HA1 + ":" + middle + ":" + HA2);
  749. #if TEST_DIGEST
  750. ASSERT(strcmp(dig_response.c_str(), DIGEST_RESPONSE) == 0);
  751. #endif
  752. std::stringstream ss;
  753. ss << auth_method;
  754. ss << " username=" << quote(username);
  755. ss << ", realm=" << quote(realm);
  756. ss << ", nonce=" << quote(nonce);
  757. ss << ", uri=" << quote(uri);
  758. if (has_qop) {
  759. ss << ", qop=" << qop;
  760. ss << ", nc=" << ncount;
  761. ss << ", cnonce=" << quote(cnonce);
  762. }
  763. ss << ", response=\"" << dig_response << "\"";
  764. if (has_opaque) {
  765. ss << ", opaque=" << quote(opaque);
  766. }
  767. response = ss.str();
  768. return HAR_RESPONSE;
  769. }
  770. #ifdef WIN32
  771. #if 1
  772. bool want_negotiate = (_stricmp(auth_method.c_str(), "negotiate") == 0);
  773. bool want_ntlm = (_stricmp(auth_method.c_str(), "ntlm") == 0);
  774. // SPNEGO & NTLM
  775. if (want_negotiate || want_ntlm) {
  776. const size_t MAX_MESSAGE = 12000, MAX_SPN = 256;
  777. char out_buf[MAX_MESSAGE], spn[MAX_SPN];
  778. #if 0 // Requires funky windows versions
  779. DWORD len = MAX_SPN;
  780. if (DsMakeSpn("HTTP", server.HostAsURIString().c_str(), NULL,
  781. server.port(),
  782. 0, &len, spn) != ERROR_SUCCESS) {
  783. LOG_F(WARNING) << "(Negotiate) - DsMakeSpn failed";
  784. return HAR_IGNORE;
  785. }
  786. #else
  787. sprintfn(spn, MAX_SPN, "HTTP/%s", server.ToString().c_str());
  788. #endif
  789. SecBuffer out_sec;
  790. out_sec.pvBuffer = out_buf;
  791. out_sec.cbBuffer = sizeof(out_buf);
  792. out_sec.BufferType = SECBUFFER_TOKEN;
  793. SecBufferDesc out_buf_desc;
  794. out_buf_desc.ulVersion = 0;
  795. out_buf_desc.cBuffers = 1;
  796. out_buf_desc.pBuffers = &out_sec;
  797. const ULONG NEG_FLAGS_DEFAULT =
  798. //ISC_REQ_ALLOCATE_MEMORY
  799. ISC_REQ_CONFIDENTIALITY
  800. //| ISC_REQ_EXTENDED_ERROR
  801. //| ISC_REQ_INTEGRITY
  802. | ISC_REQ_REPLAY_DETECT
  803. | ISC_REQ_SEQUENCE_DETECT
  804. //| ISC_REQ_STREAM
  805. //| ISC_REQ_USE_SUPPLIED_CREDS
  806. ;
  807. ::TimeStamp lifetime;
  808. SECURITY_STATUS ret = S_OK;
  809. ULONG ret_flags = 0, flags = NEG_FLAGS_DEFAULT;
  810. bool specify_credentials = !username.empty();
  811. size_t steps = 0;
  812. //uint32 now = Time();
  813. NegotiateAuthContext * neg = static_cast<NegotiateAuthContext *>(context);
  814. if (neg) {
  815. const size_t max_steps = 10;
  816. if (++neg->steps >= max_steps) {
  817. LOG(WARNING) << "AsyncHttpsProxySocket::Authenticate(Negotiate) too many retries";
  818. return HAR_ERROR;
  819. }
  820. steps = neg->steps;
  821. std::string challenge, decoded_challenge;
  822. if (HttpHasNthAttribute(args, 1, &challenge, NULL)
  823. && Base64::Decode(challenge, Base64::DO_STRICT,
  824. &decoded_challenge, NULL)) {
  825. SecBuffer in_sec;
  826. in_sec.pvBuffer = const_cast<char *>(decoded_challenge.data());
  827. in_sec.cbBuffer = static_cast<unsigned long>(decoded_challenge.size());
  828. in_sec.BufferType = SECBUFFER_TOKEN;
  829. SecBufferDesc in_buf_desc;
  830. in_buf_desc.ulVersion = 0;
  831. in_buf_desc.cBuffers = 1;
  832. in_buf_desc.pBuffers = &in_sec;
  833. ret = InitializeSecurityContextA(&neg->cred, &neg->ctx, spn, flags, 0, SECURITY_NATIVE_DREP, &in_buf_desc, 0, &neg->ctx, &out_buf_desc, &ret_flags, &lifetime);
  834. //LOG(INFO) << "$$$ InitializeSecurityContext @ " << TimeSince(now);
  835. if (FAILED(ret)) {
  836. LOG(LS_ERROR) << "InitializeSecurityContext returned: "
  837. << ErrorName(ret, SECURITY_ERRORS);
  838. return HAR_ERROR;
  839. }
  840. } else if (neg->specified_credentials) {
  841. // Try again with default credentials
  842. specify_credentials = false;
  843. delete context;
  844. context = neg = 0;
  845. } else {
  846. return HAR_CREDENTIALS;
  847. }
  848. }
  849. if (!neg) {
  850. unsigned char userbuf[256], passbuf[256], domainbuf[16];
  851. SEC_WINNT_AUTH_IDENTITY_A auth_id, * pauth_id = 0;
  852. if (specify_credentials) {
  853. memset(&auth_id, 0, sizeof(auth_id));
  854. size_t len = password.GetLength()+1;
  855. char * sensitive = new char[len];
  856. password.CopyTo(sensitive, true);
  857. std::string::size_type pos = username.find('\\');
  858. if (pos == std::string::npos) {
  859. auth_id.UserLength = static_cast<unsigned long>(
  860. _min(sizeof(userbuf) - 1, username.size()));
  861. memcpy(userbuf, username.c_str(), auth_id.UserLength);
  862. userbuf[auth_id.UserLength] = 0;
  863. auth_id.DomainLength = 0;
  864. domainbuf[auth_id.DomainLength] = 0;
  865. auth_id.PasswordLength = static_cast<unsigned long>(
  866. _min(sizeof(passbuf) - 1, password.GetLength()));
  867. memcpy(passbuf, sensitive, auth_id.PasswordLength);
  868. passbuf[auth_id.PasswordLength] = 0;
  869. } else {
  870. auth_id.UserLength = static_cast<unsigned long>(
  871. _min(sizeof(userbuf) - 1, username.size() - pos - 1));
  872. memcpy(userbuf, username.c_str() + pos + 1, auth_id.UserLength);
  873. userbuf[auth_id.UserLength] = 0;
  874. auth_id.DomainLength = static_cast<unsigned long>(
  875. _min(sizeof(domainbuf) - 1, pos));
  876. memcpy(domainbuf, username.c_str(), auth_id.DomainLength);
  877. domainbuf[auth_id.DomainLength] = 0;
  878. auth_id.PasswordLength = static_cast<unsigned long>(
  879. _min(sizeof(passbuf) - 1, password.GetLength()));
  880. memcpy(passbuf, sensitive, auth_id.PasswordLength);
  881. passbuf[auth_id.PasswordLength] = 0;
  882. }
  883. memset(sensitive, 0, len);
  884. delete [] sensitive;
  885. auth_id.User = userbuf;
  886. auth_id.Domain = domainbuf;
  887. auth_id.Password = passbuf;
  888. auth_id.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
  889. pauth_id = &auth_id;
  890. LOG(LS_VERBOSE) << "Negotiate protocol: Using specified credentials";
  891. } else {
  892. LOG(LS_VERBOSE) << "Negotiate protocol: Using default credentials";
  893. }
  894. CredHandle cred;
  895. ret = AcquireCredentialsHandleA(0, want_negotiate ? NEGOSSP_NAME_A : NTLMSP_NAME_A, SECPKG_CRED_OUTBOUND, 0, pauth_id, 0, 0, &cred, &lifetime);
  896. //LOG(INFO) << "$$$ AcquireCredentialsHandle @ " << TimeSince(now);
  897. if (ret != SEC_E_OK) {
  898. LOG(LS_ERROR) << "AcquireCredentialsHandle error: "
  899. << ErrorName(ret, SECURITY_ERRORS);
  900. return HAR_IGNORE;
  901. }
  902. //CSecBufferBundle<5, CSecBufferBase::FreeSSPI> sb_out;
  903. CtxtHandle ctx;
  904. ret = InitializeSecurityContextA(&cred, 0, spn, flags, 0, SECURITY_NATIVE_DREP, 0, 0, &ctx, &out_buf_desc, &ret_flags, &lifetime);
  905. //LOG(INFO) << "$$$ InitializeSecurityContext @ " << TimeSince(now);
  906. if (FAILED(ret)) {
  907. LOG(LS_ERROR) << "InitializeSecurityContext returned: "
  908. << ErrorName(ret, SECURITY_ERRORS);
  909. FreeCredentialsHandle(&cred);
  910. return HAR_IGNORE;
  911. }
  912. ASSERT(!context);
  913. context = neg = new NegotiateAuthContext(auth_method, cred, ctx);
  914. neg->specified_credentials = specify_credentials;
  915. neg->steps = steps;
  916. }
  917. if ((ret == SEC_I_COMPLETE_NEEDED) || (ret == SEC_I_COMPLETE_AND_CONTINUE)) {
  918. ret = CompleteAuthToken(&neg->ctx, &out_buf_desc);
  919. //LOG(INFO) << "$$$ CompleteAuthToken @ " << TimeSince(now);
  920. LOG(LS_VERBOSE) << "CompleteAuthToken returned: "
  921. << ErrorName(ret, SECURITY_ERRORS);
  922. if (FAILED(ret)) {
  923. return HAR_ERROR;
  924. }
  925. }
  926. //LOG(INFO) << "$$$ NEGOTIATE took " << TimeSince(now) << "ms";
  927. std::string decoded(out_buf, out_buf + out_sec.cbBuffer);
  928. response = auth_method;
  929. response.append(" ");
  930. response.append(Base64::Encode(decoded));
  931. return HAR_RESPONSE;
  932. }
  933. #endif
  934. #endif // WIN32
  935. return HAR_IGNORE;
  936. }
  937. //////////////////////////////////////////////////////////////////////
  938. } // namespace talk_base