HttpServerCommand.cc 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2009 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "HttpServerCommand.h"
  36. #include "SocketCore.h"
  37. #include "DownloadEngine.h"
  38. #include "HttpServer.h"
  39. #include "HttpHeader.h"
  40. #include "Logger.h"
  41. #include "LogFactory.h"
  42. #include "RequestGroup.h"
  43. #include "RequestGroupMan.h"
  44. #include "HttpServerBodyCommand.h"
  45. #include "HttpServerResponseCommand.h"
  46. #include "RecoverableException.h"
  47. #include "prefs.h"
  48. #include "Option.h"
  49. #include "util.h"
  50. #include "wallclock.h"
  51. #include "fmt.h"
  52. #include "SocketRecvBuffer.h"
  53. #include "base64.h"
  54. #include "MessageDigest.h"
  55. #include "message_digest_helper.h"
  56. #ifdef ENABLE_WEBSOCKET
  57. #include "WebSocketResponseCommand.h"
  58. #endif // ENABLE_WEBSOCKET
  59. namespace aria2 {
  60. HttpServerCommand::HttpServerCommand(cuid_t cuid, DownloadEngine* e,
  61. const std::shared_ptr<SocketCore>& socket,
  62. bool secure)
  63. : Command(cuid),
  64. e_(e),
  65. socket_(socket),
  66. httpServer_(std::make_shared<HttpServer>(socket)),
  67. writeCheck_(false)
  68. {
  69. setStatus(Command::STATUS_ONESHOT_REALTIME);
  70. e_->addSocketForReadCheck(socket_, this);
  71. httpServer_->setSecure(secure);
  72. httpServer_->setUsernamePassword(e_->getOption()->get(PREF_RPC_USER),
  73. e_->getOption()->get(PREF_RPC_PASSWD));
  74. if (e_->getOption()->getAsBool(PREF_RPC_ALLOW_ORIGIN_ALL)) {
  75. httpServer_->setAllowOrigin("*");
  76. }
  77. #ifdef HAVE_ZLIB
  78. httpServer_->enableGZip();
  79. #else // !HAVE_ZLIB
  80. httpServer_->disableGZip();
  81. #endif // !HAVE_ZLIB
  82. checkSocketRecvBuffer();
  83. }
  84. HttpServerCommand::HttpServerCommand(
  85. cuid_t cuid, const std::shared_ptr<HttpServer>& httpServer,
  86. DownloadEngine* e, const std::shared_ptr<SocketCore>& socket)
  87. : Command(cuid),
  88. e_(e),
  89. socket_(socket),
  90. httpServer_(httpServer),
  91. writeCheck_(false)
  92. {
  93. e_->addSocketForReadCheck(socket_, this);
  94. checkSocketRecvBuffer();
  95. }
  96. HttpServerCommand::~HttpServerCommand()
  97. {
  98. e_->deleteSocketForReadCheck(socket_, this);
  99. if (writeCheck_) {
  100. e_->deleteSocketForWriteCheck(socket_, this);
  101. }
  102. }
  103. void HttpServerCommand::checkSocketRecvBuffer()
  104. {
  105. if (!httpServer_->getSocketRecvBuffer()->bufferEmpty()) {
  106. setStatus(Command::STATUS_ONESHOT_REALTIME);
  107. e_->setNoWait(true);
  108. }
  109. }
  110. #ifdef ENABLE_WEBSOCKET
  111. namespace {
  112. // Creates server's WebSocket accept key which will be sent in
  113. // Sec-WebSocket-Accept header field. The |clientKey| is the value
  114. // found in Sec-WebSocket-Key header field in the request.
  115. std::string createWebSocketServerKey(const std::string& clientKey)
  116. {
  117. std::string src = clientKey;
  118. src += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  119. unsigned char digest[20];
  120. message_digest::digest(digest, sizeof(digest), MessageDigest::sha1().get(),
  121. src.c_str(), src.size());
  122. return base64::encode(&digest[0], &digest[sizeof(digest)]);
  123. }
  124. } // namespace
  125. namespace {
  126. int websocketHandshake(const HttpHeader* header)
  127. {
  128. if (header->getMethod() != "GET" ||
  129. header->find(HttpHeader::SEC_WEBSOCKET_KEY).empty()) {
  130. return 400;
  131. }
  132. else if (header->find(HttpHeader::SEC_WEBSOCKET_VERSION) != "13") {
  133. return 426;
  134. }
  135. else if (header->getRequestPath() != "/jsonrpc") {
  136. return 404;
  137. }
  138. else {
  139. return 101;
  140. }
  141. }
  142. } // namespace
  143. #endif // ENABLE_WEBSOCKET
  144. void HttpServerCommand::updateWriteCheck()
  145. {
  146. if (httpServer_->wantWrite()) {
  147. if (!writeCheck_) {
  148. writeCheck_ = true;
  149. e_->addSocketForWriteCheck(socket_, this);
  150. }
  151. }
  152. else if (writeCheck_) {
  153. writeCheck_ = false;
  154. e_->deleteSocketForWriteCheck(socket_, this);
  155. }
  156. }
  157. bool HttpServerCommand::execute()
  158. {
  159. if (e_->getRequestGroupMan()->downloadFinished() || e_->isHaltRequested()) {
  160. return true;
  161. }
  162. try {
  163. if (socket_->isReadable(0) || (writeCheck_ && socket_->isWritable(0)) ||
  164. !httpServer_->getSocketRecvBuffer()->bufferEmpty()) {
  165. timeoutTimer_ = global::wallclock();
  166. #ifdef ENABLE_SSL
  167. if (httpServer_->getSecure()) {
  168. // tlsAccept() just returns true if handshake has already
  169. // finished.
  170. if (!socket_->tlsAccept()) {
  171. updateWriteCheck();
  172. e_->addCommand(std::unique_ptr<Command>(this));
  173. return false;
  174. }
  175. }
  176. #endif // ENABLE_SSL
  177. if (!httpServer_->receiveRequest()) {
  178. updateWriteCheck();
  179. e_->addCommand(std::unique_ptr<Command>(this));
  180. return false;
  181. }
  182. // CORS preflight request uses OPTIONS method. It is not
  183. // restricted by authentication.
  184. if (!httpServer_->authenticate() &&
  185. httpServer_->getMethod() != "OPTIONS") {
  186. httpServer_->disableKeepAlive();
  187. httpServer_->feedResponse(
  188. 401, "WWW-Authenticate: Basic realm=\"aria2\"\r\n");
  189. e_->addCommand(make_unique<HttpServerResponseCommand>(
  190. getCuid(), httpServer_, e_, socket_));
  191. e_->setNoWait(true);
  192. return true;
  193. }
  194. auto& header = httpServer_->getRequestHeader();
  195. if (header->fieldContains(HttpHeader::UPGRADE, "websocket") &&
  196. header->fieldContains(HttpHeader::CONNECTION, "upgrade")) {
  197. #ifdef ENABLE_WEBSOCKET
  198. int status = websocketHandshake(header.get());
  199. if (status == 101) {
  200. std::string serverKey = createWebSocketServerKey(
  201. header->find(HttpHeader::SEC_WEBSOCKET_KEY));
  202. httpServer_->feedUpgradeResponse(
  203. "websocket",
  204. fmt("Sec-WebSocket-Accept: %s\r\n", serverKey.c_str()));
  205. e_->addCommand(make_unique<rpc::WebSocketResponseCommand>(
  206. getCuid(), httpServer_, e_, socket_));
  207. }
  208. else {
  209. if (status == 426) {
  210. httpServer_->feedResponse(426, "Sec-WebSocket-Version: 13\r\n");
  211. }
  212. else {
  213. httpServer_->feedResponse(status);
  214. }
  215. e_->addCommand(make_unique<HttpServerResponseCommand>(
  216. getCuid(), httpServer_, e_, socket_));
  217. }
  218. e_->setNoWait(true);
  219. return true;
  220. #else // !ENABLE_WEBSOCKET
  221. httpServer_->feedResponse(400);
  222. e_->addCommand(make_unique<HttpServerResponseCommand>(
  223. getCuid(), httpServer_, e_, socket_));
  224. e_->setNoWait(true);
  225. return true;
  226. #endif // !ENABLE_WEBSOCKET
  227. }
  228. else {
  229. if (e_->getOption()->getAsInt(PREF_RPC_MAX_REQUEST_SIZE) <
  230. httpServer_->getContentLength()) {
  231. A2_LOG_INFO(fmt("Request too long. ContentLength=%" PRId64 "."
  232. " See --rpc-max-request-size option to loose"
  233. " this limitation.",
  234. httpServer_->getContentLength()));
  235. return true;
  236. }
  237. e_->addCommand(make_unique<HttpServerBodyCommand>(
  238. getCuid(), httpServer_, e_, socket_));
  239. e_->setNoWait(true);
  240. return true;
  241. }
  242. }
  243. else {
  244. if (timeoutTimer_.difference(global::wallclock()) >= 30_s) {
  245. A2_LOG_INFO("HTTP request timeout.");
  246. return true;
  247. }
  248. else {
  249. e_->addCommand(std::unique_ptr<Command>(this));
  250. return false;
  251. }
  252. }
  253. }
  254. catch (RecoverableException& e) {
  255. A2_LOG_INFO_EX(fmt("CUID#%" PRId64
  256. " - Error occurred while reading HTTP request",
  257. getCuid()),
  258. e);
  259. return true;
  260. }
  261. }
  262. } // namespace aria2