Repository navigation
Expand file tree
/
Copy pathrpc-request-handler.cpp
More file actions
454 lines (411 loc) · 14.7 KB
/
Copy pathrpc-request-handler.cpp
File metadata and controls
454 lines (411 loc) · 14.7 KB
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/server/rpc-request-handler.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/comparisons.h"
#include "hphp/runtime/base/init-fini-node.h"
#include "hphp/runtime/base/memory-manager.h"
#include "hphp/runtime/base/php-globals.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/ext/json/ext_json.h"
#include "hphp/runtime/ext/std/ext_std_output.h"
#include "hphp/runtime/server/access-log.h"
#include "hphp/runtime/server/http-protocol.h"
#include "hphp/runtime/server/http-request-handler.h"
#include "hphp/runtime/server/request-uri.h"
#include "hphp/runtime/server/satellite-server.h"
#include "hphp/runtime/server/server-stats.h"
#include "hphp/runtime/server/source-root-info.h"
#include "hphp/runtime/vm/debugger-hook.h"
#include "hphp/runtime/vm/vm-regs.h"
#include "hphp/util/process.h"
#include "hphp/util/stack-trace.h"
#include <folly/ScopeGuard.h>
using std::set;
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
IMPLEMENT_THREAD_LOCAL(AccessLog::ThreadData,
RPCRequestHandler::s_accessLogThreadData);
AccessLog RPCRequestHandler::s_accessLog(
&(RPCRequestHandler::getAccessLogThreadData));
RPCRequestHandler::RPCRequestHandler(int timeout, bool info)
: RequestHandler(timeout),
m_requestsSinceReset(0),
m_reset(false),
m_logResets(info),
m_returnEncodeType(ReturnEncodeType::Json) {
}
RPCRequestHandler::~RPCRequestHandler() {
if (vmStack().isAllocated()) cleanupState();
}
void RPCRequestHandler::initState() {
hphp_session_init();
bool isServer = RuntimeOption::ServerExecutionMode();
m_context = g_context.getNoCheck();
if (isServer) {
m_context->obStart(uninit_null(),
0,
OBFlags::Default | OBFlags::OutputDisabled);
m_context->obProtect(true);
} else {
// In command line mode, we want the xbox workers to
// output to STDOUT
m_context->obSetImplicitFlush(true);
m_context->obStart(uninit_null(),
0,
OBFlags::Default | OBFlags::WriteToStdout);
m_context->obProtect(true);
}
m_lastReset = time(0);
Logger::ResetRequestCount();
if (m_logResets) {
Logger::Info("initializing RPC request handler");
}
m_reset = false;
m_requestsSinceReset = 0;
}
void RPCRequestHandler::cleanupState() {
hphp_context_exit();
hphp_session_exit();
}
bool RPCRequestHandler::needReset() const {
return (m_reset ||
!vmStack().isAllocated() ||
m_serverInfo->alwaysReset() ||
((time(0) - m_lastReset) > m_serverInfo->getMaxDuration()) ||
(m_requestsSinceReset >= m_serverInfo->getMaxRequest()));
}
void RPCRequestHandler::handleRequest(Transport *transport) {
if (needReset()) {
if (vmStack().isAllocated()) cleanupState();
initState();
}
++m_requestsSinceReset;
ExecutionProfiler ep(ThreadInfo::RuntimeFunctions);
Logger::OnNewRequest();
GetAccessLog().onNewRequest();
m_context->setTransport(transport);
transport->enableCompression();
InitFiniNode::RequestStart();
ServerStatsHelper ssh("all", ServerStatsHelper::TRACK_MEMORY);
Logger::Verbose("receiving %s", transport->getCommand().c_str());
// will clear all extra logging when this function goes out of scope
StackTraceNoHeap::ExtraLoggingClearer clearer;
StackTraceNoHeap::AddExtraLogging("RPC-URL", transport->getUrl());
// Checking functions whitelist
const std::set<std::string> &functions = m_serverInfo->getFunctions();
if (!functions.empty()) {
auto iter = functions.find(transport->getCommand());
if (iter == functions.end()) {
transport->sendString("Forbidden", 403);
transport->onSendEnd();
GetAccessLog().log(transport, nullptr);
/*
* HPHP logs may need to access data in ServerStats, so we have to
* clear the hashtable after writing the log entry.
*/
ServerStats::Reset();
return;
}
}
// authentication
const std::set<std::string> &passwords = m_serverInfo->getPasswords();
if (!passwords.empty()) {
auto iter = passwords.find(
transport->getParam("auth", m_serverInfo->getMethod())
);
if (iter == passwords.end()) {
transport->sendString("Unauthorized", 401);
transport->onSendEnd();
GetAccessLog().log(transport, nullptr);
/*
* HPHP logs may need to access data in ServerStats, so we have to
* clear the hashtable after writing the log entry.
*/
ServerStats::Reset();
return;
}
} else {
const std::string &password = m_serverInfo->getPassword();
if (!password.empty() &&
password != transport->getParam("auth", m_serverInfo->getMethod())
) {
transport->sendString("Unauthorized", 401);
transport->onSendEnd();
GetAccessLog().log(transport, nullptr);
/*
* HPHP logs may need to access data in ServerStats, so we have to
* clear the hashtable after writing the log entry.
*/
ServerStats::Reset();
return;
}
}
// return encoding type
ReturnEncodeType returnEncodeType = m_returnEncodeType;
if (transport->getParam("return", m_serverInfo->getMethod()) == "serialize") {
returnEncodeType = ReturnEncodeType::Serialize;
}
// resolve virtual host
const VirtualHost *vhost = HttpProtocol::GetVirtualHost(transport);
assert(vhost);
if (vhost->disabled()) {
transport->sendString("Virtual host disabled.", 404);
transport->onSendEnd();
GetAccessLog().log(transport, vhost);
return;
}
auto& reqData = ThreadInfo::s_threadInfo->m_reqInjectionData;
reqData.setTimeout(vhost->getRequestTimeoutSeconds(getDefaultTimeout()));
SCOPE_EXIT {
reqData.setTimeout(0); // can't throw when you pass zero
reqData.setCPUTimeout(0);
reqData.reset();
};
// resolve source root
SourceRootInfo sourceRootInfo(transport);
// set thread type
switch (m_serverInfo->getType()) {
case SatelliteServer::Type::KindOfRPCServer:
transport->setThreadType(Transport::ThreadType::RpcThread);
break;
case SatelliteServer::Type::KindOfXboxServer:
transport->setThreadType(Transport::ThreadType::XboxThread);
break;
default:
break;
}
// record request for debugging purpose
std::string tmpfile = HttpProtocol::RecordRequest(transport);
bool ret = executePHPFunction(transport, sourceRootInfo, returnEncodeType);
GetAccessLog().log(transport, vhost);
/*
* HPHP logs may need to access data in ServerStats, so we have to
* clear the hashtable after writing the log entry.
*/
ServerStats::Reset();
HttpProtocol::ClearRecord(ret, tmpfile);
}
void RPCRequestHandler::abortRequest(Transport *transport) {
g_context.getCheck();
GetAccessLog().onNewRequest();
const VirtualHost *vhost = HttpProtocol::GetVirtualHost(transport);
assert(vhost);
transport->sendString("Service Unavailable", 503);
GetAccessLog().log(transport, vhost);
if (!vmStack().isAllocated()) {
hphp_memory_cleanup();
}
m_reset = true;
}
const StaticString
s_output("output"),
s_return("return"),
s_HPHP_RPC("HPHP_RPC"),
s__ENV("_ENV");
bool RPCRequestHandler::executePHPFunction(Transport *transport,
SourceRootInfo &sourceRootInfo,
ReturnEncodeType returnEncodeType) {
std::string rpcFunc = transport->getCommand();
{
ServerStatsHelper ssh("input");
RequestURI reqURI(rpcFunc);
HttpProtocol::PrepareSystemVariables(transport, reqURI, sourceRootInfo);
auto env = php_global(s__ENV);
env.toArrRef().set(s_HPHP_RPC, 1);
php_global_set(s__ENV, std::move(env));
InitFiniNode::GlobalsInit();
}
bool isFile = rpcFunc.rfind('.') != std::string::npos;
std::string rpcFile;
bool error = false;
Array params;
Transport::Method requestMethod = m_serverInfo->getMethod();
std::string sparams = transport->getParam("params", requestMethod);
if (!sparams.empty()) {
auto jparams = Variant::attach(
HHVM_FN(json_decode)(String(sparams), true)
);
if (jparams.isArray()) {
params = jparams.toArray();
} else {
error = true;
}
} else {
std::vector<std::string> sparams;
transport->getArrayParam("p", sparams, requestMethod);
if (!sparams.empty()) {
for (unsigned int i = 0; i < sparams.size(); i++) {
auto jparams = Variant::attach(
HHVM_FN(json_decode)(String(sparams[i]), true)
);
if (same(jparams, false)) {
error = true;
break;
}
params.append(jparams);
}
} else {
// single string parameter, used by xbox to avoid any en/decoding
size_t size;
const void *data = transport->getPostData(size);
if (data && size) {
params.append(String((char*)data, size, CopyString));
}
}
}
if (transport->getIntParam("reset", requestMethod) == 1) {
m_reset = true;
}
int output = transport->getIntParam("output", requestMethod);
// We don't debug RPC requests, so we need to detach XDebugHook if xdebug was
// enabled.
DEBUGGER_ATTACHED_ONLY(DebuggerHook::detach());
int code;
if (!error) {
Variant funcRet;
std::string errorMsg = "Internal Server Error";
std::string reqInitFunc, reqInitDoc;
reqInitDoc = transport->getHeader("ReqInitDoc");
if (reqInitDoc.empty() && m_serverInfo) {
reqInitFunc = m_serverInfo->getReqInitFunc();
reqInitDoc = m_serverInfo->getReqInitDoc();
}
if (!reqInitDoc.empty()) {
reqInitDoc = (std::string)canonicalize_path(reqInitDoc, "", 0);
}
if (!reqInitDoc.empty()) {
reqInitDoc = getSourceFilename(reqInitDoc, sourceRootInfo);
}
bool runOnce = false;
bool ret = true;
if (isFile) {
rpcFile = rpcFunc;
rpcFunc.clear();
} else {
rpcFile = transport->getParam("include", requestMethod);
if (rpcFile.empty()) {
rpcFile = transport->getParam("include_once", requestMethod);
runOnce = true;
}
}
if (!rpcFile.empty()) {
// invoking a file through rpc
bool forbidden = false;
if (!RuntimeOption::ForbiddenFileExtensions.empty()) {
const char *ext = rpcFile.c_str() + rpcFile.rfind('.') + 1;
if (RuntimeOption::ForbiddenFileExtensions.find(ext) !=
RuntimeOption::ForbiddenFileExtensions.end()) {
forbidden = true;
}
}
if (!forbidden) {
rpcFile = (std::string) canonicalize_path(rpcFile, "", 0);
rpcFile = getSourceFilename(rpcFile, sourceRootInfo);
ret = hphp_invoke(m_context, rpcFile, false, Array(), uninit_null(),
reqInitFunc, reqInitDoc, error, errorMsg, runOnce,
false /* warmupOnly */,
false /* richErrorMessage */);
}
// no need to do the initialization for a second time
reqInitFunc.clear();
reqInitDoc.clear();
}
if (ret && !rpcFunc.empty()) {
ret = hphp_invoke(m_context, rpcFunc, true, params, ref(funcRet),
reqInitFunc, reqInitDoc, error, errorMsg,
true /* once */,
false /* warmupOnly */,
false /* richErrorMessage */);
}
if (ret) {
bool serializeFailed = false;
String response;
switch (output) {
case 0: {
assert(returnEncodeType == ReturnEncodeType::Json ||
returnEncodeType == ReturnEncodeType::Serialize);
try {
response = (returnEncodeType == ReturnEncodeType::Json)
? Variant::attach(HHVM_FN(json_encode)(funcRet)).toString()
: f_serialize(funcRet);
} catch (...) {
serializeFailed = true;
}
break;
}
case 1: response = m_context->obDetachContents(); break;
case 2:
response = Variant::attach(HHVM_FN(json_encode)(
make_map_array(
s_output,
m_context->obDetachContents(),
s_return,
Variant::attach(HHVM_FN(json_encode)(funcRet))
)
)).toString();
break;
case 3: response = f_serialize(funcRet); break;
}
if (serializeFailed) {
code = 500;
transport->sendString(
"Serialization of the return value failed", 500);
m_reset = true;
} else {
transport->sendRaw((void*)response.data(), response.size());
code = transport->getResponseCode();
}
} else if (error) {
code = 500;
transport->sendString(errorMsg, 500);
m_reset = true;
} else {
code = 404;
transport->sendString("Not Found", 404);
}
} else {
code = 400;
transport->sendString("Bad Request", 400);
}
params.reset();
sourceRootInfo.clear();
transport->onSendEnd();
ServerStats::LogPage(isFile ? rpcFile : rpcFunc, code);
m_context->onShutdownPostSend();
// in case postsend/cleanup output something
// PHP5 always provides _START.
m_context->obClean(k_PHP_OUTPUT_HANDLER_START |
k_PHP_OUTPUT_HANDLER_CLEAN |
k_PHP_OUTPUT_HANDLER_END);
m_context->restoreSession();
return !error;
}
std::string RPCRequestHandler::getSourceFilename(const std::string &path,
SourceRootInfo &sourceRootInfo) {
if (path.empty() || path[0] == '/') return path;
// If it is not a sandbox, sourceRoot will be the same as
// RuntimeOption::SourceRoot.
std::string sourceRoot = sourceRootInfo.path();
if (sourceRoot.empty()) {
return Process::GetCurrentDirectory() + "/" + path;
}
return sourceRoot + path;
}
///////////////////////////////////////////////////////////////////////////////
}