HttpServerCommand.cc 8.9 KB

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