1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
|
/* <!-- copyright */
/*
* aria2 - The high speed download utility
*
* Copyright (C) 2009 Tatsuhiro Tsujikawa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
/* copyright --> */
#include "HttpServerBodyCommand.h"
#include "SocketCore.h"
#include "DownloadEngine.h"
#include "HttpServer.h"
#include "HttpHeader.h"
#include "Logger.h"
#include "LogFactory.h"
#include "RequestGroup.h"
#include "RequestGroupMan.h"
#include "RecoverableException.h"
#include "HttpServerResponseCommand.h"
#include "OptionParser.h"
#include "OptionHandler.h"
#include "wallclock.h"
#include "util.h"
#include "fmt.h"
#include "SocketRecvBuffer.h"
#include "json.h"
#include "DlAbortEx.h"
#include "message.h"
#include "RpcMethod.h"
#include "RpcMethodFactory.h"
#include "RpcRequest.h"
#include "RpcResponse.h"
#include "rpc_helper.h"
#include "JsonDiskWriter.h"
#include "ValueBaseJsonParser.h"
#ifdef ENABLE_XML_RPC
# include "XmlRpcRequestParserStateMachine.h"
# include "XmlRpcDiskWriter.h"
#endif // ENABLE_XML_RPC
namespace aria2 {
HttpServerBodyCommand::HttpServerBodyCommand
(cuid_t cuid,
const SharedHandle<HttpServer>& httpServer,
DownloadEngine* e,
const SharedHandle<SocketCore>& socket)
: Command(cuid),
e_(e),
socket_(socket),
httpServer_(httpServer),
writeCheck_(false)
{
// To handle Content-Length == 0 case
setStatus(Command::STATUS_ONESHOT_REALTIME);
e_->addSocketForReadCheck(socket_, this);
if(!httpServer_->getSocketRecvBuffer()->bufferEmpty()) {
e_->setNoWait(true);
}
}
HttpServerBodyCommand::~HttpServerBodyCommand()
{
e_->deleteSocketForReadCheck(socket_, this);
if(writeCheck_) {
e_->deleteSocketForWriteCheck(socket_, this);
}
}
namespace {
std::string getJsonRpcContentType(bool script)
{
return script ? "text/javascript" : "application/json-rpc";
}
} // namespace
void HttpServerBodyCommand::sendJsonRpcResponse
(const rpc::RpcResponse& res,
const std::string& callback)
{
bool gzip = httpServer_->supportsGZip();
std::string responseData = rpc::toJson(res, callback, gzip);
if(res.code == 0) {
httpServer_->feedResponse(responseData,
getJsonRpcContentType(!callback.empty()));
} else {
httpServer_->disableKeepAlive();
int httpCode;
switch(res.code) {
case -32600:
httpCode = 400;
break;
case -32601:
httpCode = 404;
break;
default:
httpCode = 500;
};
httpServer_->feedResponse(httpCode, A2STR::NIL,
responseData,
getJsonRpcContentType(!callback.empty()));
}
addHttpServerResponseCommand();
}
void HttpServerBodyCommand::sendJsonRpcBatchResponse
(const std::vector<rpc::RpcResponse>& results,
const std::string& callback)
{
bool gzip = httpServer_->supportsGZip();
std::string responseData = rpc::toJsonBatch(results, callback, gzip);
httpServer_->feedResponse(responseData,
getJsonRpcContentType(!callback.empty()));
addHttpServerResponseCommand();
}
void HttpServerBodyCommand::addHttpServerResponseCommand()
{
Command* command =
new HttpServerResponseCommand(getCuid(), httpServer_, e_, socket_);
e_->addCommand(command);
e_->setNoWait(true);
}
void HttpServerBodyCommand::updateWriteCheck()
{
if(httpServer_->wantWrite()) {
if(!writeCheck_) {
writeCheck_ = true;
e_->addSocketForWriteCheck(socket_, this);
}
} else if(writeCheck_) {
writeCheck_ = false;
e_->deleteSocketForWriteCheck(socket_, this);
}
}
bool HttpServerBodyCommand::execute()
{
if(e_->getRequestGroupMan()->downloadFinished() || e_->isHaltRequested()) {
return true;
}
try {
if(socket_->isReadable(0) ||
(writeCheck_ && socket_->isWritable(0)) ||
!httpServer_->getSocketRecvBuffer()->bufferEmpty() ||
httpServer_->getContentLength() == 0) {
timeoutTimer_ = global::wallclock();
if(httpServer_->receiveBody()) {
std::string reqPath = httpServer_->getRequestPath();
reqPath.erase(std::find(reqPath.begin(), reqPath.end(), '#'),
reqPath.end());
std::string query(std::find(reqPath.begin(), reqPath.end(), '?'),
reqPath.end());
reqPath.erase(reqPath.size()-query.size(), query.size());
if(httpServer_->getMethod() == "OPTIONS") {
// Response to Preflight Request.
// See http://www.w3.org/TR/cors/
const SharedHandle<HttpHeader>& header =
httpServer_->getRequestHeader();
std::string accessControlHeaders;
if(!header->find(HttpHeader::ORIGIN).empty() &&
!header->find(HttpHeader::ACCESS_CONTROL_REQUEST_METHOD).empty()
&& !httpServer_->getAllowOrigin().empty()) {
accessControlHeaders +=
"Access-Control-Allow-Methods: POST, GET, OPTIONS\r\n"
"Access-Control-Max-Age: 1728000\r\n";
const std::string& accReqHeaders =
header->find(HttpHeader::ACCESS_CONTROL_REQUEST_HEADERS);
if(!accReqHeaders.empty()) {
// We allow all headers requested.
accessControlHeaders += "Access-Control-Allow-Headers: ";
accessControlHeaders += accReqHeaders;
accessControlHeaders += "\r\n";
}
}
httpServer_->feedResponse(200, accessControlHeaders);
addHttpServerResponseCommand();
return true;
}
// Do something for requestpath and body
switch(httpServer_->getRequestType()) {
case RPC_TYPE_XML: {
#ifdef ENABLE_XML_RPC
SharedHandle<rpc::XmlRpcDiskWriter> dw =
static_pointer_cast<rpc::XmlRpcDiskWriter>(httpServer_->getBody());
int error;
error = dw->finalize();
rpc::RpcRequest req;
if(error == 0) {
req = dw->getResult();
}
dw->reset();
if(error < 0) {
A2_LOG_INFO
(fmt("CUID#%" PRId64 " - Failed to parse XML-RPC request",
getCuid()));
httpServer_->feedResponse(400);
addHttpServerResponseCommand();
return true;
}
SharedHandle<rpc::RpcMethod> method =
rpc::RpcMethodFactory::create(req.methodName);
A2_LOG_INFO(fmt("Executing RPC method %s", req.methodName.c_str()));
rpc::RpcResponse res = method->execute(req, e_);
bool gzip = httpServer_->supportsGZip();
std::string responseData = rpc::toXml(res, gzip);
httpServer_->feedResponse(responseData, "text/xml");
addHttpServerResponseCommand();
#else // !ENABLE_XML_RPC
httpServer_->feedResponse(404);
addHttpServerResponseCommand();
#endif // !ENABLE_XML_RPC
return true;
}
case RPC_TYPE_JSON:
case RPC_TYPE_JSONP: {
std::string callback;
SharedHandle<ValueBase> json;
ssize_t error = 0;
if(httpServer_->getRequestType() == RPC_TYPE_JSONP) {
json::JsonGetParam param = json::decodeGetParams(query);
callback = param.callback;
ssize_t error = 0;
json = json::ValueBaseJsonParser().parseFinal
(param.request.c_str(),
param.request.size(),
error);
} else {
SharedHandle<json::JsonDiskWriter> dw =
static_pointer_cast<json::JsonDiskWriter>(httpServer_->getBody());
error = dw->finalize();
if(error == 0) {
json = dw->getResult();
}
dw->reset();
}
if(error < 0) {
A2_LOG_INFO
(fmt("CUID#%" PRId64 " - Failed to parse JSON-RPC request",
getCuid()));
rpc::RpcResponse res
(rpc::createJsonRpcErrorResponse(-32700, "Parse error.",
Null::g()));
sendJsonRpcResponse(res, callback);
return true;
}
const Dict* jsondict = downcast<Dict>(json);
if(jsondict) {
rpc::RpcResponse res = rpc::processJsonRpcRequest(jsondict, e_);
sendJsonRpcResponse(res, callback);
} else {
const List* jsonlist = downcast<List>(json);
if(jsonlist) {
// This is batch call
std::vector<rpc::RpcResponse> results;
for(List::ValueType::const_iterator i = jsonlist->begin(),
eoi = jsonlist->end(); i != eoi; ++i) {
const Dict* jsondict = downcast<Dict>(*i);
if(jsondict) {
rpc::RpcResponse r =
rpc::processJsonRpcRequest(jsondict, e_);
results.push_back(r);
}
}
sendJsonRpcBatchResponse(results, callback);
} else {
rpc::RpcResponse res
(rpc::createJsonRpcErrorResponse
(-32600, "Invalid Request.", Null::g()));
sendJsonRpcResponse(res, callback);
}
}
return true;
}
default:
httpServer_->feedResponse(404);
addHttpServerResponseCommand();
return true;
}
} else {
updateWriteCheck();
e_->addCommand(this);
return false;
}
} else {
if(timeoutTimer_.difference(global::wallclock()) >= 30) {
A2_LOG_INFO("HTTP request body timeout.");
return true;
} else {
e_->addCommand(this);
return false;
}
}
} catch(RecoverableException& e) {
A2_LOG_INFO_EX
(fmt("CUID#%" PRId64 " - Error occurred while reading HTTP request body",
getCuid()),
e);
return true;
}
}
} // namespace aria2
|