HTTPClientSession.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. //
  2. // HTTPClientSession.cpp
  3. //
  4. // $Id: //poco/1.4/Net/src/HTTPClientSession.cpp#6 $
  5. //
  6. // Library: Net
  7. // Package: HTTPClient
  8. // Module: HTTPClientSession
  9. //
  10. // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // Permission is hereby granted, free of charge, to any person or organization
  14. // obtaining a copy of the software and accompanying documentation covered by
  15. // this license (the "Software") to use, reproduce, display, distribute,
  16. // execute, and transmit the Software, and to prepare derivative works of the
  17. // Software, and to permit third-parties to whom the Software is furnished to
  18. // do so, all subject to the following:
  19. //
  20. // The copyright notices in the Software and this entire statement, including
  21. // the above license grant, this restriction and the following disclaimer,
  22. // must be included in all copies of the Software, in whole or in part, and
  23. // all derivative works of the Software, unless such copies or derivative
  24. // works are solely in the form of machine-executable object code generated by
  25. // a source language processor.
  26. //
  27. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  28. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29. // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  30. // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  31. // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  32. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  33. // DEALINGS IN THE SOFTWARE.
  34. //
  35. #include "Poco/Net/HTTPClientSession.h"
  36. #include "Poco/Net/HTTPRequest.h"
  37. #include "Poco/Net/HTTPResponse.h"
  38. #include "Poco/Net/HTTPHeaderStream.h"
  39. #include "Poco/Net/HTTPStream.h"
  40. #include "Poco/Net/HTTPFixedLengthStream.h"
  41. #include "Poco/Net/HTTPChunkedStream.h"
  42. #include "Poco/Net/HTTPBasicCredentials.h"
  43. #include "Poco/Net/NetException.h"
  44. #include "Poco/NumberFormatter.h"
  45. #include "Poco/CountingStream.h"
  46. #include "Poco/Base64Encoder.h"
  47. #include <sstream>
  48. using Poco::NumberFormatter;
  49. using Poco::IllegalStateException;
  50. namespace Poco {
  51. namespace Net {
  52. HTTPClientSession::HTTPClientSession():
  53. _port(HTTPSession::HTTP_PORT),
  54. _proxyPort(HTTPSession::HTTP_PORT),
  55. _keepAliveTimeout(DEFAULT_KEEP_ALIVE_TIMEOUT, 0),
  56. _reconnect(false),
  57. _mustReconnect(false),
  58. _expectResponseBody(false),
  59. _pRequestStream(0),
  60. _pResponseStream(0)
  61. {
  62. }
  63. HTTPClientSession::HTTPClientSession(const StreamSocket& socket):
  64. HTTPSession(socket),
  65. _port(HTTPSession::HTTP_PORT),
  66. _proxyPort(HTTPSession::HTTP_PORT),
  67. _keepAliveTimeout(DEFAULT_KEEP_ALIVE_TIMEOUT, 0),
  68. _reconnect(false),
  69. _mustReconnect(false),
  70. _expectResponseBody(false),
  71. _pRequestStream(0),
  72. _pResponseStream(0)
  73. {
  74. }
  75. HTTPClientSession::HTTPClientSession(const SocketAddress& address):
  76. _host(address.host().toString()),
  77. _port(address.port()),
  78. _proxyPort(HTTPSession::HTTP_PORT),
  79. _keepAliveTimeout(DEFAULT_KEEP_ALIVE_TIMEOUT, 0),
  80. _reconnect(false),
  81. _mustReconnect(false),
  82. _expectResponseBody(false),
  83. _pRequestStream(0),
  84. _pResponseStream(0)
  85. {
  86. }
  87. HTTPClientSession::HTTPClientSession(const std::string& host, Poco::UInt16 port):
  88. _host(host),
  89. _port(port),
  90. _proxyPort(HTTPSession::HTTP_PORT),
  91. _keepAliveTimeout(DEFAULT_KEEP_ALIVE_TIMEOUT, 0),
  92. _reconnect(false),
  93. _mustReconnect(false),
  94. _expectResponseBody(false),
  95. _pRequestStream(0),
  96. _pResponseStream(0)
  97. {
  98. }
  99. HTTPClientSession::~HTTPClientSession()
  100. {
  101. delete _pRequestStream;
  102. delete _pResponseStream;
  103. }
  104. void HTTPClientSession::setHost(const std::string& host)
  105. {
  106. if (!connected())
  107. _host = host;
  108. else
  109. throw IllegalStateException("Cannot set the host for an already connected session");
  110. }
  111. void HTTPClientSession::setPort(Poco::UInt16 port)
  112. {
  113. if (!connected())
  114. _port = port;
  115. else
  116. throw IllegalStateException("Cannot set the port number for an already connected session");
  117. }
  118. void HTTPClientSession::setProxy(const std::string& host, Poco::UInt16 port)
  119. {
  120. if (!connected())
  121. {
  122. _proxyHost = host;
  123. _proxyPort = port;
  124. }
  125. else throw IllegalStateException("Cannot set the proxy host and port for an already connected session");
  126. }
  127. void HTTPClientSession::setProxyHost(const std::string& host)
  128. {
  129. if (!connected())
  130. _proxyHost = host;
  131. else
  132. throw IllegalStateException("Cannot set the proxy host for an already connected session");
  133. }
  134. void HTTPClientSession::setProxyPort(Poco::UInt16 port)
  135. {
  136. if (!connected())
  137. _proxyPort = port;
  138. else
  139. throw IllegalStateException("Cannot set the proxy port number for an already connected session");
  140. }
  141. void HTTPClientSession::setProxyCredentials(const std::string& username, const std::string& password)
  142. {
  143. _proxyUsername = username;
  144. _proxyPassword = password;
  145. }
  146. void HTTPClientSession::setProxyUsername(const std::string& username)
  147. {
  148. _proxyUsername = username;
  149. }
  150. void HTTPClientSession::setProxyPassword(const std::string& password)
  151. {
  152. _proxyPassword = password;
  153. }
  154. void HTTPClientSession::setKeepAliveTimeout(const Poco::Timespan& timeout)
  155. {
  156. _keepAliveTimeout = timeout;
  157. }
  158. std::ostream& HTTPClientSession::sendRequest(HTTPRequest& request)
  159. {
  160. delete _pResponseStream;
  161. _pResponseStream = 0;
  162. bool keepAlive = getKeepAlive();
  163. if ((connected() && !keepAlive) || mustReconnect())
  164. {
  165. close();
  166. _mustReconnect = false;
  167. }
  168. try
  169. {
  170. if (!connected())
  171. reconnect();
  172. if (!keepAlive)
  173. request.setKeepAlive(false);
  174. if (!request.has(HTTPRequest::HOST))
  175. request.setHost(_host, _port);
  176. if (!_proxyHost.empty())
  177. {
  178. request.setURI(proxyRequestPrefix() + request.getURI());
  179. proxyAuthenticate(request);
  180. }
  181. _reconnect = keepAlive;
  182. _expectResponseBody = request.getMethod() != HTTPRequest::HTTP_HEAD;
  183. if (request.getChunkedTransferEncoding())
  184. {
  185. HTTPHeaderOutputStream hos(*this);
  186. request.write(hos);
  187. _pRequestStream = new HTTPChunkedOutputStream(*this);
  188. }
  189. else if (request.hasContentLength())
  190. {
  191. Poco::CountingOutputStream cs;
  192. request.write(cs);
  193. #if POCO_HAVE_INT64
  194. _pRequestStream = new HTTPFixedLengthOutputStream(*this, request.getContentLength64() + cs.chars());
  195. #else
  196. _pRequestStream = new HTTPFixedLengthOutputStream(*this, request.getContentLength() + cs.chars());
  197. #endif
  198. request.write(*_pRequestStream);
  199. }
  200. else if (request.getMethod() != HTTPRequest::HTTP_PUT && request.getMethod() != HTTPRequest::HTTP_POST)
  201. {
  202. Poco::CountingOutputStream cs;
  203. request.write(cs);
  204. _pRequestStream = new HTTPFixedLengthOutputStream(*this, cs.chars());
  205. request.write(*_pRequestStream);
  206. }
  207. else
  208. {
  209. _pRequestStream = new HTTPOutputStream(*this);
  210. request.write(*_pRequestStream);
  211. }
  212. _lastRequest.update();
  213. return *_pRequestStream;
  214. }
  215. catch (Exception&)
  216. {
  217. close();
  218. throw;
  219. }
  220. }
  221. std::istream& HTTPClientSession::receiveResponse(HTTPResponse& response)
  222. {
  223. delete _pRequestStream;
  224. _pRequestStream = 0;
  225. do
  226. {
  227. response.clear();
  228. HTTPHeaderInputStream his(*this);
  229. try
  230. {
  231. response.read(his);
  232. }
  233. catch (MessageException&)
  234. {
  235. close();
  236. if (networkException())
  237. networkException()->rethrow();
  238. else
  239. throw;
  240. }
  241. catch (Exception&)
  242. {
  243. close();
  244. throw;
  245. }
  246. }
  247. while (response.getStatus() == HTTPResponse::HTTP_CONTINUE);
  248. _mustReconnect = getKeepAlive() && !response.getKeepAlive();
  249. if (!_expectResponseBody || response.getStatus() < 200 || response.getStatus() == HTTPResponse::HTTP_NO_CONTENT || response.getStatus() == HTTPResponse::HTTP_NOT_MODIFIED)
  250. _pResponseStream = new HTTPFixedLengthInputStream(*this, 0);
  251. else if (response.getChunkedTransferEncoding())
  252. _pResponseStream = new HTTPChunkedInputStream(*this);
  253. else if (response.hasContentLength())
  254. #if defined(POCO_HAVE_INT64)
  255. _pResponseStream = new HTTPFixedLengthInputStream(*this, response.getContentLength64());
  256. #else
  257. _pResponseStream = new HTTPFixedLengthInputStream(*this, response.getContentLength());
  258. #endif
  259. else
  260. _pResponseStream = new HTTPInputStream(*this);
  261. return *_pResponseStream;
  262. }
  263. void HTTPClientSession::reset()
  264. {
  265. close();
  266. }
  267. bool HTTPClientSession::secure() const
  268. {
  269. return false;
  270. }
  271. int HTTPClientSession::write(const char* buffer, std::streamsize length)
  272. {
  273. try
  274. {
  275. int rc = HTTPSession::write(buffer, length);
  276. _reconnect = false;
  277. return rc;
  278. }
  279. catch (NetException&)
  280. {
  281. if (_reconnect)
  282. {
  283. close();
  284. reconnect();
  285. int rc = HTTPSession::write(buffer, length);
  286. _reconnect = false;
  287. return rc;
  288. }
  289. else throw;
  290. }
  291. }
  292. void HTTPClientSession::reconnect()
  293. {
  294. if (_proxyHost.empty())
  295. {
  296. SocketAddress addr(_host, _port);
  297. connect(addr);
  298. }
  299. else
  300. {
  301. SocketAddress addr(_proxyHost, _proxyPort);
  302. connect(addr);
  303. }
  304. }
  305. std::string HTTPClientSession::proxyRequestPrefix() const
  306. {
  307. std::string result("http://");
  308. result.append(_host);
  309. result.append(":");
  310. NumberFormatter::append(result, _port);
  311. return result;
  312. }
  313. void HTTPClientSession::deleteResponseStream()
  314. {
  315. delete _pResponseStream;
  316. _pResponseStream = 0;
  317. }
  318. void HTTPClientSession::deleteRequestStream()
  319. {
  320. delete _pRequestStream;
  321. _pRequestStream = 0;
  322. }
  323. void HTTPClientSession::setResponseStream(std::istream* pRespStream)
  324. {
  325. poco_assert (!_pResponseStream);
  326. _pResponseStream = pRespStream;
  327. }
  328. void HTTPClientSession::setRequestStream(std::ostream* pRequestStream)
  329. {
  330. poco_assert (!_pRequestStream);
  331. _pRequestStream = pRequestStream;
  332. }
  333. bool HTTPClientSession::mustReconnect() const
  334. {
  335. if (!_mustReconnect)
  336. {
  337. Poco::Timestamp now;
  338. return _keepAliveTimeout <= now - _lastRequest;
  339. }
  340. else return true;
  341. }
  342. void HTTPClientSession::proxyAuthenticate(HTTPRequest& request)
  343. {
  344. proxyAuthenticateImpl(request);
  345. }
  346. void HTTPClientSession::proxyAuthenticateImpl(HTTPRequest& request)
  347. {
  348. if (!_proxyUsername.empty())
  349. {
  350. HTTPBasicCredentials creds(_proxyUsername, _proxyPassword);
  351. creds.proxyAuthenticate(request);
  352. }
  353. }
  354. StreamSocket HTTPClientSession::proxyConnect()
  355. {
  356. HTTPClientSession proxySession(getProxyHost(), getProxyPort());
  357. proxySession.setTimeout(getTimeout());
  358. SocketAddress targetAddress(getHost(), getPort());
  359. HTTPRequest proxyRequest(HTTPRequest::HTTP_CONNECT, targetAddress.toString(), HTTPMessage::HTTP_1_1);
  360. HTTPResponse proxyResponse;
  361. proxyRequest.set("Proxy-Connection", "keep-alive");
  362. proxyRequest.set("Host", getHost());
  363. proxyAuthenticateImpl(proxyRequest);
  364. proxySession.setKeepAlive(true);
  365. proxySession.sendRequest(proxyRequest);
  366. proxySession.receiveResponse(proxyResponse);
  367. if (proxyResponse.getStatus() != HTTPResponse::HTTP_OK)
  368. throw HTTPException("Cannot establish proxy connection", proxyResponse.getReason());
  369. return proxySession.detachSocket();
  370. }
  371. void HTTPClientSession::proxyTunnel()
  372. {
  373. StreamSocket ss = proxyConnect();
  374. attachSocket(ss);
  375. }
  376. } } // namespace Poco::Net