HttpServerCommand.cc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. socket_->getRecvBufferedLength() == 0) {
  107. return;
  108. }
  109. setStatus(Command::STATUS_ONESHOT_REALTIME);
  110. e_->setNoWait(true);
  111. }
  112. #ifdef ENABLE_WEBSOCKET
  113. namespace {
  114. // Creates server's WebSocket accept key which will be sent in
  115. // Sec-WebSocket-Accept header field. The |clientKey| is the value
  116. // found in Sec-WebSocket-Key header field in the request.
  117. std::string createWebSocketServerKey(const std::string& clientKey)
  118. {
  119. std::string src = clientKey;
  120. src += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  121. unsigned char digest[20];
  122. message_digest::digest(digest, sizeof(digest), MessageDigest::sha1().get(),
  123. src.c_str(), src.size());
  124. return base64::encode(&digest[0], &digest[sizeof(digest)]);
  125. }
  126. } // namespace
  127. namespace {
  128. int websocketHandshake(const HttpHeader* header)
  129. {
  130. if (header->getMethod() != "GET" ||
  131. header->find(HttpHeader::SEC_WEBSOCKET_KEY).empty()) {
  132. return 400;
  133. }
  134. else if (header->find(HttpHeader::SEC_WEBSOCKET_VERSION) != "13") {
  135. return 426;
  136. }
  137. else if (header->getRequestPath() != "/jsonrpc") {
  138. return 404;
  139. }
  140. else {
  141. return 101;
  142. }
  143. }
  144. } // namespace
  145. #endif // ENABLE_WEBSOCKET
  146. void HttpServerCommand::updateWriteCheck()
  147. {
  148. if (httpServer_->wantWrite()) {
  149. if (!writeCheck_) {
  150. writeCheck_ = true;
  151. e_->addSocketForWriteCheck(socket_, this);
  152. }
  153. }
  154. else if (writeCheck_) {
  155. writeCheck_ = false;
  156. e_->deleteSocketForWriteCheck(socket_, this);
  157. }
  158. }
  159. bool HttpServerCommand::execute()
  160. {
  161. if (e_->getRequestGroupMan()->downloadFinished() || e_->isHaltRequested()) {
  162. return true;
  163. }
  164. try {
  165. if (socket_->isReadable(0) || (writeCheck_ && socket_->isWritable(0)) ||
  166. socket_->getRecvBufferedLength() ||
  167. !httpServer_->getSocketRecvBuffer()->bufferEmpty()) {
  168. timeoutTimer_ = global::wallclock();
  169. #ifdef ENABLE_SSL
  170. if (httpServer_->getSecure()) {
  171. // tlsAccept() just returns true if handshake has already
  172. // finished.
  173. if (!socket_->tlsAccept()) {
  174. updateWriteCheck();
  175. e_->addCommand(std::unique_ptr<Command>(this));
  176. return false;
  177. }
  178. }
  179. #endif // ENABLE_SSL
  180. if (!httpServer_->receiveRequest()) {
  181. updateWriteCheck();
  182. e_->addCommand(std::unique_ptr<Command>(this));
  183. return false;
  184. }
  185. // CORS preflight request uses OPTIONS method. It is not
  186. // restricted by authentication.
  187. if (!httpServer_->authenticate() &&
  188. httpServer_->getMethod() != "OPTIONS") {
  189. httpServer_->disableKeepAlive();
  190. httpServer_->feedResponse(
  191. 401, "WWW-Authenticate: Basic realm=\"aria2\"\r\n");
  192. e_->addCommand(make_unique<HttpServerResponseCommand>(
  193. getCuid(), httpServer_, e_, socket_));
  194. e_->setNoWait(true);
  195. return true;
  196. }
  197. auto& header = httpServer_->getRequestHeader();
  198. if (header->fieldContains(HttpHeader::UPGRADE, "websocket") &&
  199. header->fieldContains(HttpHeader::CONNECTION, "upgrade")) {
  200. #ifdef ENABLE_WEBSOCKET
  201. int status = websocketHandshake(header.get());
  202. if (status == 101) {
  203. std::string serverKey = createWebSocketServerKey(
  204. header->find(HttpHeader::SEC_WEBSOCKET_KEY));
  205. httpServer_->feedUpgradeResponse(
  206. "websocket",
  207. fmt("Sec-WebSocket-Accept: %s\r\n", serverKey.c_str()));
  208. e_->addCommand(make_unique<rpc::WebSocketResponseCommand>(
  209. getCuid(), httpServer_, e_, socket_));
  210. }
  211. else {
  212. if (status == 426) {
  213. httpServer_->feedResponse(426, "Sec-WebSocket-Version: 13\r\n");
  214. }
  215. else {
  216. httpServer_->feedResponse(status);
  217. }
  218. e_->addCommand(make_unique<HttpServerResponseCommand>(
  219. getCuid(), httpServer_, e_, socket_));
  220. }
  221. e_->setNoWait(true);
  222. return true;
  223. #else // !ENABLE_WEBSOCKET
  224. httpServer_->feedResponse(400);
  225. e_->addCommand(make_unique<HttpServerResponseCommand>(
  226. getCuid(), httpServer_, e_, socket_));
  227. e_->setNoWait(true);
  228. return true;
  229. #endif // !ENABLE_WEBSOCKET
  230. }
  231. else {
  232. if (e_->getOption()->getAsInt(PREF_RPC_MAX_REQUEST_SIZE) <
  233. httpServer_->getContentLength()) {
  234. A2_LOG_INFO(fmt("Request too long. ContentLength=%" PRId64 "."
  235. " See --rpc-max-request-size option to loose"
  236. " this limitation.",
  237. httpServer_->getContentLength()));
  238. return true;
  239. }
  240. e_->addCommand(make_unique<HttpServerBodyCommand>(
  241. getCuid(), httpServer_, e_, socket_));
  242. e_->setNoWait(true);
  243. return true;
  244. }
  245. }
  246. else {
  247. if (timeoutTimer_.difference(global::wallclock()) >= 30_s) {
  248. A2_LOG_INFO("HTTP request timeout.");
  249. return true;
  250. }
  251. else {
  252. e_->addCommand(std::unique_ptr<Command>(this));
  253. return false;
  254. }
  255. }
  256. }
  257. catch (RecoverableException& e) {
  258. A2_LOG_INFO_EX(fmt("CUID#%" PRId64
  259. " - Error occurred while reading HTTP request",
  260. getCuid()),
  261. e);
  262. return true;
  263. }
  264. }
  265. } // namespace aria2