HttpServerCommand.cc 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. #ifdef ENABLE_MESSAGE_DIGEST
  55. # include "MessageDigest.h"
  56. # include "message_digest_helper.h"
  57. #endif // ENABLE_MESSAGE_DIGEST
  58. #ifdef ENABLE_WEBSOCKET
  59. # include "WebSocketResponseCommand.h"
  60. #endif // ENABLE_WEBSOCKET
  61. namespace aria2 {
  62. HttpServerCommand::HttpServerCommand
  63. (cuid_t cuid,
  64. DownloadEngine* e,
  65. const SharedHandle<SocketCore>& socket)
  66. : Command(cuid),
  67. e_(e),
  68. socket_(socket),
  69. httpServer_(new HttpServer(socket, e))
  70. {
  71. setStatus(Command::STATUS_ONESHOT_REALTIME);
  72. e_->addSocketForReadCheck(socket_, this);
  73. httpServer_->setUsernamePassword(e_->getOption()->get(PREF_RPC_USER),
  74. e_->getOption()->get(PREF_RPC_PASSWD));
  75. if(e_->getOption()->getAsBool(PREF_RPC_ALLOW_ORIGIN_ALL)) {
  76. httpServer_->setAllowOrigin("*");
  77. }
  78. #ifdef HAVE_ZLIB
  79. httpServer_->enableGZip();
  80. #else // !HAVE_ZLIB
  81. httpServer_->disableGZip();
  82. #endif // !HAVE_ZLIB
  83. checkSocketRecvBuffer();
  84. }
  85. HttpServerCommand::HttpServerCommand
  86. (cuid_t cuid,
  87. const SharedHandle<HttpServer>& httpServer,
  88. DownloadEngine* e,
  89. const SharedHandle<SocketCore>& socket)
  90. : Command(cuid),
  91. e_(e),
  92. socket_(socket),
  93. httpServer_(httpServer)
  94. {
  95. e_->addSocketForReadCheck(socket_, this);
  96. checkSocketRecvBuffer();
  97. }
  98. HttpServerCommand::~HttpServerCommand()
  99. {
  100. e_->deleteSocketForReadCheck(socket_, this);
  101. }
  102. void HttpServerCommand::checkSocketRecvBuffer()
  103. {
  104. if(!httpServer_->getSocketRecvBuffer()->bufferEmpty()) {
  105. setStatus(Command::STATUS_ONESHOT_REALTIME);
  106. e_->setNoWait(true);
  107. }
  108. }
  109. #ifdef ENABLE_WEBSOCKET
  110. namespace {
  111. // Creates server's WebSocket accept key which will be sent in
  112. // Sec-WebSocket-Accept header field. The |clientKey| is the value
  113. // found in Sec-WebSocket-Key header field in the request.
  114. std::string createWebSocketServerKey(const std::string& clientKey)
  115. {
  116. std::string src = clientKey;
  117. src += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  118. unsigned char digest[20];
  119. message_digest::digest(digest, sizeof(digest), MessageDigest::sha1(),
  120. src.c_str(), src.size());
  121. return base64::encode(&digest[0], &digest[sizeof(digest)]);
  122. }
  123. } // namespace
  124. namespace {
  125. int websocketHandshake(const SharedHandle<HttpHeader>& header)
  126. {
  127. if(header->getMethod() != "GET" ||
  128. header->find(HttpHeader::SEC_WEBSOCKET_KEY).empty()) {
  129. return 400;
  130. } else if(header->find(HttpHeader::SEC_WEBSOCKET_VERSION) != "13") {
  131. return 426;
  132. } else if(header->getRequestPath() != "/jsonrpc") {
  133. return 404;
  134. } else {
  135. return 101;
  136. }
  137. }
  138. } // namespace
  139. #endif // ENABLE_WEBSOCKET
  140. bool HttpServerCommand::execute()
  141. {
  142. if(e_->getRequestGroupMan()->downloadFinished() || e_->isHaltRequested()) {
  143. return true;
  144. }
  145. try {
  146. if(socket_->isReadable(0) ||
  147. !httpServer_->getSocketRecvBuffer()->bufferEmpty()) {
  148. timeoutTimer_ = global::wallclock();
  149. SharedHandle<HttpHeader> header;
  150. header = httpServer_->receiveRequest();
  151. if(!header) {
  152. e_->addCommand(this);
  153. return false;
  154. }
  155. // CORS preflight request uses OPTIONS method. It is not
  156. // restricted by authentication.
  157. if(!httpServer_->authenticate() &&
  158. httpServer_->getMethod() != "OPTIONS") {
  159. httpServer_->disableKeepAlive();
  160. httpServer_->feedResponse
  161. (401, "WWW-Authenticate: Basic realm=\"aria2\"\r\n");
  162. Command* command =
  163. new HttpServerResponseCommand(getCuid(), httpServer_, e_, socket_);
  164. e_->addCommand(command);
  165. e_->setNoWait(true);
  166. return true;
  167. }
  168. if(header->fieldContains(HttpHeader::UPGRADE, "websocket") &&
  169. header->fieldContains(HttpHeader::CONNECTION, "upgrade")) {
  170. #ifdef ENABLE_WEBSOCKET
  171. int status = websocketHandshake(header);
  172. Command* command;
  173. if(status == 101) {
  174. std::string serverKey =
  175. createWebSocketServerKey
  176. (header->find(HttpHeader::SEC_WEBSOCKET_KEY));
  177. httpServer_->feedUpgradeResponse("websocket",
  178. fmt("Sec-WebSocket-Accept: %s\r\n",
  179. serverKey.c_str()));
  180. httpServer_->getSocket()->setTcpNodelay(true);
  181. command = new rpc::WebSocketResponseCommand(getCuid(), httpServer_,
  182. e_, socket_);
  183. } else {
  184. if(status == 426) {
  185. httpServer_->feedResponse(426, "Sec-WebSocket-Version: 13\r\n");
  186. } else {
  187. httpServer_->feedResponse(status);
  188. }
  189. command = new HttpServerResponseCommand(getCuid(), httpServer_, e_,
  190. socket_);
  191. }
  192. e_->addCommand(command);
  193. e_->setNoWait(true);
  194. return true;
  195. #else // !ENABLE_WEBSOCKET
  196. httpServer_->feedResponse(400);
  197. Command* command = new HttpServerResponseCommand(getCuid(),
  198. httpServer_, e_,
  199. socket_);
  200. e_->addCommand(command);
  201. e_->setNoWait(true);
  202. return true;
  203. #endif // !ENABLE_WEBSOCKET
  204. } else {
  205. if(e_->getOption()->getAsInt(PREF_RPC_MAX_REQUEST_SIZE) <
  206. httpServer_->getContentLength()) {
  207. A2_LOG_INFO
  208. (fmt("Request too long. ContentLength=%" PRId64 "."
  209. " See --rpc-max-request-size option to loose"
  210. " this limitation.",
  211. httpServer_->getContentLength()));
  212. return true;
  213. }
  214. Command* command = new HttpServerBodyCommand(getCuid(), httpServer_, e_,
  215. socket_);
  216. e_->addCommand(command);
  217. e_->setNoWait(true);
  218. return true;
  219. }
  220. } else {
  221. if(timeoutTimer_.difference(global::wallclock()) >= 30) {
  222. A2_LOG_INFO("HTTP request timeout.");
  223. return true;
  224. } else {
  225. e_->addCommand(this);
  226. return false;
  227. }
  228. }
  229. } catch(RecoverableException& e) {
  230. A2_LOG_INFO_EX(fmt("CUID#%" PRId64 " - Error occurred while reading HTTP request",
  231. getCuid()),
  232. e);
  233. return true;
  234. }
  235. }
  236. } // namespace aria2