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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
|
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* 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 program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. 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 in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault
#include "mongo/platform/basic.h"
#include "mongo/scripting/engine.h"
#include <boost/filesystem/operations.hpp>
#include <cctype>
#include "mongo/client/dbclient_base.h"
#include "mongo/client/dbclient_cursor.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/service_context.h"
#include "mongo/logv2/log.h"
#include "mongo/scripting/dbdirectclient_factory.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/file.h"
#include "mongo/util/text.h"
namespace mongo {
using std::set;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
AtomicWord<long long> Scope::_lastVersion(1);
namespace {
MONGO_FAIL_POINT_DEFINE(mr_killop_test_fp);
// 2 GB is the largest support Javascript file size.
const fileofs kMaxJsFileLength = fileofs(2) * 1024 * 1024 * 1024;
const ServiceContext::Decoration<std::unique_ptr<ScriptEngine>> forService =
ServiceContext::declareDecoration<std::unique_ptr<ScriptEngine>>();
static std::unique_ptr<ScriptEngine> globalScriptEngine;
} // namespace
ScriptEngine::ScriptEngine(bool disableLoadStored)
: _disableLoadStored(disableLoadStored), _scopeInitCallback() {}
ScriptEngine::~ScriptEngine() {}
Scope::Scope()
: _localDBName(""),
_loadedVersion(0),
_createTime(Date_t::now()),
_lastRetIsNativeCode(false) {}
Scope::~Scope() {}
void Scope::append(BSONObjBuilder& builder, const char* fieldName, const char* scopeName) {
int t = type(scopeName);
switch (t) {
case Object:
builder.append(fieldName, getObject(scopeName));
break;
case Array:
builder.appendArray(fieldName, getObject(scopeName));
break;
case NumberDouble:
builder.append(fieldName, getNumber(scopeName));
break;
case NumberInt:
builder.append(fieldName, getNumberInt(scopeName));
break;
case NumberLong:
builder.append(fieldName, getNumberLongLong(scopeName));
break;
case NumberDecimal:
builder.append(fieldName, getNumberDecimal(scopeName));
break;
case String:
builder.append(fieldName, getString(scopeName));
break;
case Bool:
builder.appendBool(fieldName, getBoolean(scopeName));
break;
case jstNULL:
case Undefined:
builder.appendNull(fieldName);
break;
case Date:
builder.appendDate(fieldName,
Date_t::fromMillisSinceEpoch(getNumberLongLong(scopeName)));
break;
case Code:
builder.appendCode(fieldName, getString(scopeName));
break;
default:
uassert(10206, str::stream() << "can't append type from: " << t, 0);
}
}
int Scope::invoke(const char* code, const BSONObj* args, const BSONObj* recv, int timeoutMs) {
ScriptingFunction func = createFunction(code);
uassert(10207, "compile failed", func);
return invoke(func, args, recv, timeoutMs);
}
bool Scope::execFile(const string& filename, bool printResult, bool reportError, int timeoutMs) {
#ifdef _WIN32
boost::filesystem::path p(toWideString(filename.c_str()));
#else
boost::filesystem::path p(filename);
#endif
if (!exists(p)) {
LOGV2_ERROR(22779, "file [{filename}] doesn't exist", "filename"_attr = filename);
return false;
}
// iterate directories and recurse using all *.js files in the directory
if (boost::filesystem::is_directory(p)) {
boost::filesystem::directory_iterator end;
bool empty = true;
for (boost::filesystem::directory_iterator it(p); it != end; it++) {
empty = false;
boost::filesystem::path sub(*it);
if (!str::endsWith(sub.string().c_str(), ".js"))
continue;
if (!execFile(sub.string(), printResult, reportError, timeoutMs))
return false;
}
if (empty) {
LOGV2_ERROR(22780,
"directory [{filename}] doesn't have any *.js files",
"filename"_attr = filename);
return false;
}
return true;
}
File f;
f.open(filename.c_str(), true);
if (!f.is_open() || f.bad())
return false;
fileofs fo = f.len();
if (fo > kMaxJsFileLength) {
LOGV2_WARNING(22778, "attempted to execute javascript file larger than 2GB");
return false;
}
unsigned len = static_cast<unsigned>(fo);
std::unique_ptr<char[]> data(new char[len + 1]);
data[len] = 0;
f.read(0, data.get(), len);
int offset = 0;
if (data[0] == '#' && data[1] == '!') {
const char* newline = strchr(data.get(), '\n');
if (!newline)
return true; // file of just shebang treated same as empty file
offset = newline - data.get();
}
StringData code(data.get() + offset, len - offset);
return exec(code, filename, printResult, reportError, false, timeoutMs);
}
class Scope::StoredFuncModLogOpHandler : public RecoveryUnit::Change {
public:
void commit(boost::optional<Timestamp>) {
_lastVersion.fetchAndAdd(1);
}
void rollback() {}
};
void Scope::storedFuncMod(OperationContext* opCtx) {
opCtx->recoveryUnit()->registerChange(std::make_unique<StoredFuncModLogOpHandler>());
}
void Scope::validateObjectIdString(const string& str) {
uassert(10448, "invalid object id: length", str.size() == 24);
for (size_t i = 0; i < str.size(); i++)
uassert(10430, "invalid object id: not hex", std::isxdigit(str.at(i)));
}
void Scope::loadStored(OperationContext* opCtx, bool ignoreNotConnected) {
if (!getGlobalScriptEngine()->_disableLoadStored)
return;
if (_localDBName.size() == 0) {
if (ignoreNotConnected)
return;
uassert(10208, "need to have locallyConnected already", _localDBName.size());
}
int64_t lastVersion = _lastVersion.load();
if (_loadedVersion == lastVersion)
return;
NamespaceString coll(_localDBName, "system.js");
auto directDBClient = DBDirectClientFactory::get(opCtx).create(opCtx);
unique_ptr<DBClientCursor> c =
directDBClient->query(coll, Query(), 0, 0, nullptr, QueryOption_SlaveOk, 0);
massert(16669, "unable to get db client cursor from query", c.get());
set<string> thisTime;
while (c->more()) {
BSONObj o = c->nextSafe().getOwned();
BSONElement n = o["_id"];
BSONElement v = o["value"];
uassert(
10209, str::stream() << "name has to be a string: " << n, n.type() == BSONType::String);
uassert(10210, "value has to be set", v.type() != BSONType::EOO);
uassert(4546000,
str::stream() << "BSON type 'CodeWithScope' not supported in system.js scripts. As "
"an alternative use 'Code'. Script _id value: '"
<< n.String() << "'",
v.type() != BSONType::CodeWScope);
if (MONGO_unlikely(mr_killop_test_fp.shouldFail())) {
/* This thread sleep makes the interrupts in the test come in at a time
* where the js misses the interrupt and throw an exception instead of
* being interrupted
*/
stdx::this_thread::sleep_for(stdx::chrono::seconds(1));
}
try {
setElement(n.valuestr(), v, o);
thisTime.insert(n.valuestr());
_storedNames.insert(n.valuestr());
} catch (const DBException& setElemEx) {
if (setElemEx.code() == ErrorCodes::Interrupted) {
throw;
}
LOGV2_ERROR(22781,
"unable to load stored JavaScript function {n_valuestr}(): {setElemEx}",
"n_valuestr"_attr = n.valuestr(),
"setElemEx"_attr = redact(setElemEx));
}
}
// remove things from scope that were removed from the system.js collection
for (set<string>::iterator i = _storedNames.begin(); i != _storedNames.end();) {
if (thisTime.count(*i) == 0) {
string toDelete = str::stream() << "delete " << *i;
_storedNames.erase(i++);
execSetup(toDelete, "clean up scope");
} else {
++i;
}
}
// Only update _loadedVersion if loading system.js completed successfully.
// If any one operation failed or was interrupted we will start over next time.
_loadedVersion = lastVersion;
}
ScriptingFunction Scope::createFunction(const char* code) {
if (code[0] == '/' && code[1] == '*') {
code += 2;
while (code[0] && code[1]) {
if (code[0] == '*' && code[1] == '/') {
code += 2;
break;
}
code++;
}
}
FunctionCacheMap::iterator i = _cachedFunctions.find(code);
if (i != _cachedFunctions.end())
return i->second;
// Get a function number, so the cache can be utilized to lookup the source on an exception
ScriptingFunction functionNumber = _createFunction(code);
_cachedFunctions[code] = functionNumber;
return functionNumber;
}
namespace JSFiles {
extern const JSFile collection;
extern const JSFile check_log;
extern const JSFile crud_api;
extern const JSFile db;
extern const JSFile explain_query;
extern const JSFile explainable;
extern const JSFile mongo;
extern const JSFile session;
extern const JSFile query;
extern const JSFile utils;
extern const JSFile utils_sh;
extern const JSFile utils_auth;
extern const JSFile bulk_api;
extern const JSFile error_codes;
} // namespace JSFiles
void Scope::execCoreFiles() {
execSetup(JSFiles::utils);
execSetup(JSFiles::utils_sh);
execSetup(JSFiles::utils_auth);
execSetup(JSFiles::db);
execSetup(JSFiles::mongo);
execSetup(JSFiles::session);
execSetup(JSFiles::query);
execSetup(JSFiles::bulk_api);
execSetup(JSFiles::error_codes);
execSetup(JSFiles::check_log);
execSetup(JSFiles::collection);
execSetup(JSFiles::crud_api);
execSetup(JSFiles::explain_query);
execSetup(JSFiles::explainable);
}
namespace {
class ScopeCache {
public:
void release(const string& poolName, const std::shared_ptr<Scope>& scope) {
stdx::lock_guard<Latch> lk(_mutex);
if (scope->hasOutOfMemoryException()) {
// make some room
LOGV2(22777, "Clearing all idle JS contexts due to out of memory");
_pools.clear();
return;
}
if (Date_t::now() - scope->getCreateTime() > kMaxScopeReuseTime)
return; // too old to save
if (!scope->getError().empty())
return; // not saving errored scopes
if (_pools.size() >= kMaxPoolSize) {
// prefer to keep recently-used scopes
_pools.pop_back();
}
scope->reset();
ScopeAndPool toStore = {scope, poolName};
_pools.push_front(toStore);
}
std::shared_ptr<Scope> tryAcquire(OperationContext* opCtx, const string& poolName) {
stdx::lock_guard<Latch> lk(_mutex);
for (Pools::iterator it = _pools.begin(); it != _pools.end(); ++it) {
if (it->poolName == poolName) {
std::shared_ptr<Scope> scope = it->scope;
_pools.erase(it);
scope->reset();
scope->registerOperation(opCtx);
return scope;
}
}
return std::shared_ptr<Scope>();
}
void clear() {
stdx::lock_guard<Latch> lk(_mutex);
_pools.clear();
}
private:
struct ScopeAndPool {
std::shared_ptr<Scope> scope;
string poolName;
};
// Note: if these numbers change, reconsider choice of datastructure for _pools
static const unsigned kMaxPoolSize = 10;
constexpr static inline Seconds kMaxScopeReuseTime = Seconds(10);
typedef std::deque<ScopeAndPool> Pools; // More-recently used Scopes are kept at the front.
Pools _pools; // protected by _mutex
Mutex _mutex = MONGO_MAKE_LATCH("ScopeCache::_mutex");
};
ScopeCache scopeCache;
} // anonymous namespace
void ScriptEngine::dropScopeCache() {
scopeCache.clear();
}
class PooledScope : public Scope {
public:
PooledScope(const std::string& pool, const std::shared_ptr<Scope>& real)
: _pool(pool), _real(real) {}
virtual ~PooledScope() {
scopeCache.release(_pool, _real);
}
// wrappers for the derived (_real) scope
void reset() {
_real->reset();
}
void registerOperation(OperationContext* opCtx) {
_real->registerOperation(opCtx);
}
void unregisterOperation() {
_real->unregisterOperation();
}
void init(const BSONObj* data) {
_real->init(data);
}
void setLocalDB(StringData dbName) {
_real->setLocalDB(dbName);
}
void loadStored(OperationContext* opCtx, bool ignoreNotConnected = false) {
_real->loadStored(opCtx, ignoreNotConnected);
}
void externalSetup() {
_real->externalSetup();
}
void gc() {
_real->gc();
}
void advanceGeneration() {
_real->advanceGeneration();
}
void requireOwnedObjects() override {
_real->requireOwnedObjects();
}
void kill() {
_real->kill();
}
bool isKillPending() const {
return _real->isKillPending();
}
int type(const char* field) {
return _real->type(field);
}
string getError() {
return _real->getError();
}
bool hasOutOfMemoryException() {
return _real->hasOutOfMemoryException();
}
void rename(const char* from, const char* to) {
_real->rename(from, to);
}
double getNumber(const char* field) {
return _real->getNumber(field);
}
int getNumberInt(const char* field) {
return _real->getNumberInt(field);
}
long long getNumberLongLong(const char* field) {
return _real->getNumberLongLong(field);
}
Decimal128 getNumberDecimal(const char* field) {
return _real->getNumberDecimal(field);
}
string getString(const char* field) {
return _real->getString(field);
}
bool getBoolean(const char* field) {
return _real->getBoolean(field);
}
BSONObj getObject(const char* field) {
return _real->getObject(field);
}
void setNumber(const char* field, double val) {
_real->setNumber(field, val);
}
void setString(const char* field, StringData val) {
_real->setString(field, val);
}
void setElement(const char* field, const BSONElement& val, const BSONObj& parent) {
_real->setElement(field, val, parent);
}
void setObject(const char* field, const BSONObj& obj, bool readOnly = true) {
_real->setObject(field, obj, readOnly);
}
bool isLastRetNativeCode() {
return _real->isLastRetNativeCode();
}
void setBoolean(const char* field, bool val) {
_real->setBoolean(field, val);
}
void setFunction(const char* field, const char* code) {
_real->setFunction(field, code);
}
ScriptingFunction createFunction(const char* code) {
return _real->createFunction(code);
}
int invoke(ScriptingFunction func,
const BSONObj* args,
const BSONObj* recv,
int timeoutMs,
bool ignoreReturn,
bool readOnlyArgs,
bool readOnlyRecv) {
return _real->invoke(func, args, recv, timeoutMs, ignoreReturn, readOnlyArgs, readOnlyRecv);
}
bool exec(StringData code,
const string& name,
bool printResult,
bool reportError,
bool assertOnError,
int timeoutMs = 0) {
return _real->exec(code, name, printResult, reportError, assertOnError, timeoutMs);
}
bool execFile(const string& filename, bool printResult, bool reportError, int timeoutMs = 0) {
return _real->execFile(filename, printResult, reportError, timeoutMs);
}
void injectNative(const char* field, NativeFunction func, void* data) {
_real->injectNative(field, func, data);
}
void append(BSONObjBuilder& builder, const char* fieldName, const char* scopeName) {
_real->append(builder, fieldName, scopeName);
}
protected:
ScriptingFunction _createFunction(const char* code) {
return _real->_createFunction(code);
}
private:
string _pool;
std::shared_ptr<Scope> _real;
};
/** Get a scope from the pool of scopes matching the supplied pool name */
unique_ptr<Scope> ScriptEngine::getPooledScope(OperationContext* opCtx,
const string& db,
const string& scopeType) {
const string fullPoolName = db + scopeType;
std::shared_ptr<Scope> s = scopeCache.tryAcquire(opCtx, fullPoolName);
if (!s) {
s.reset(newScope());
s->registerOperation(opCtx);
}
unique_ptr<Scope> p;
p.reset(new PooledScope(fullPoolName, s));
p->setLocalDB(db);
p->loadStored(opCtx, true);
return p;
}
void (*ScriptEngine::_connectCallback)(DBClientBase&) = nullptr;
ScriptEngine* getGlobalScriptEngine() {
if (hasGlobalServiceContext())
return forService(getGlobalServiceContext()).get();
else
return globalScriptEngine.get();
}
void setGlobalScriptEngine(ScriptEngine* impl) {
if (hasGlobalServiceContext())
forService(getGlobalServiceContext()).reset(impl);
else
globalScriptEngine.reset(impl);
}
bool hasJSReturn(const string& code) {
size_t x = code.find("return");
if (x == string::npos)
return false;
int quoteCount = 0;
int singleQuoteCount = 0;
for (size_t i = 0; i < x; i++) {
if (code[i] == '"') {
quoteCount++;
} else if (code[i] == '\'') {
singleQuoteCount++;
}
}
// if we are in either single quotes or double quotes return false
if (quoteCount % 2 != 0 || singleQuoteCount % 2 != 0) {
return false;
}
// return is at start OR preceded by space
// AND return is not followed by digit or letter
return (x == 0 || isspace(code[x - 1])) && !(isalpha(code[x + 6]) || isdigit(code[x + 6]));
}
const char* jsSkipWhiteSpace(const char* raw) {
while (raw[0]) {
while (isspace(*raw)) {
++raw;
}
if (raw[0] != '/' || raw[1] != '/')
break;
while (raw[0] && raw[0] != '\n')
raw++;
}
return raw;
}
} // namespace mongo
|