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
|
/**
* 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/shell/shell_options.h"
#include <boost/filesystem/operations.hpp>
#include <iostream>
#include "mongo/base/status.h"
#include "mongo/bson/util/builder.h"
#include "mongo/client/mongo_uri.h"
#include "mongo/client/sasl_client_authenticate.h"
#include "mongo/config.h"
#include "mongo/db/server_options.h"
#include "mongo/rpc/protocol.h"
#include "mongo/shell/shell_utils.h"
#include "mongo/transport/message_compressor_registry.h"
#include "mongo/util/log.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/net/sock.h"
#include "mongo/util/net/ssl_options.h"
#include "mongo/util/options_parser/startup_options.h"
#include "mongo/util/version.h"
namespace mongo {
using std::cout;
using std::endl;
using std::string;
using std::vector;
ShellGlobalParams shellGlobalParams;
Status addMongoShellOptions(moe::OptionSection* options) {
options->addOptionChaining(
"shell", "shell", moe::Switch, "run the shell after executing files");
options->addOptionChaining("nodb",
"nodb",
moe::Switch,
"don't connect to mongod on startup - no 'db address' arg expected");
options->addOptionChaining(
"norc", "norc", moe::Switch, "will not run the \".mongorc.js\" file on start up");
options->addOptionChaining("quiet", "quiet", moe::Switch, "be less chatty");
options->addOptionChaining("port", "port", moe::String, "port to connect to");
options->addOptionChaining("host", "host", moe::String, "server to connect to");
options->addOptionChaining("eval", "eval", moe::String, "evaluate javascript");
options
->addOptionChaining(
"objcheck", "objcheck", moe::Switch, "inspect client data for validity on receipt")
.hidden()
.setSources(moe::SourceAllLegacy)
.incompatibleWith("noobjcheck");
options
->addOptionChaining("noobjcheck",
"noobjcheck",
moe::Switch,
"do NOT inspect client data for validity on receipt (DEFAULT)")
.hidden()
.setSources(moe::SourceAllLegacy)
.incompatibleWith("objcheck");
moe::OptionSection authenticationOptions("Authentication Options");
authenticationOptions.addOptionChaining(
"username", "username,u", moe::String, "username for authentication");
authenticationOptions
.addOptionChaining("password", "password,p", moe::String, "password for authentication")
.setImplicit(moe::Value(std::string("")));
authenticationOptions
.addOptionChaining("authenticationDatabase",
"authenticationDatabase",
moe::String,
"user source (defaults to dbname)")
.setDefault(moe::Value(std::string("")));
authenticationOptions.addOptionChaining("authenticationMechanism",
"authenticationMechanism",
moe::String,
"authentication mechanism");
authenticationOptions
.addOptionChaining("gssapiServiceName",
"gssapiServiceName",
moe::String,
"Service name to use when authenticating using GSSAPI/Kerberos")
.setDefault(moe::Value(std::string(saslDefaultServiceName)));
authenticationOptions.addOptionChaining(
"gssapiHostName",
"gssapiHostName",
moe::String,
"Remote host name to use for purpose of GSSAPI/Kerberos authentication");
options->addSection(authenticationOptions).transitional_ignore();
options->addOptionChaining("help", "help,h", moe::Switch, "show this usage information");
options->addOptionChaining("version", "version", moe::Switch, "show version information");
options->addOptionChaining("verbose", "verbose", moe::Switch, "increase verbosity");
options->addOptionChaining(
"ipv6", "ipv6", moe::Switch, "enable IPv6 support (disabled by default)");
options->addOptionChaining("disableJavaScriptJIT",
"disableJavaScriptJIT",
moe::Switch,
"disable the Javascript Just In Time compiler");
options
->addOptionChaining("disableJavaScriptProtection",
"disableJavaScriptProtection",
moe::Switch,
"allow automatic JavaScript function marshalling")
.incompatibleWith("enableJavaScriptProtection");
Status ret = Status::OK();
#ifdef MONGO_CONFIG_SSL
ret = addSSLClientOptions(options);
if (!ret.isOK()) {
return ret;
}
#endif
options
->addOptionChaining("enableJavaScriptProtection",
"enableJavaScriptProtection",
moe::Switch,
"disable automatic JavaScript function marshalling (defaults to true)")
.hidden()
.incompatibleWith("disableJavaScriptProtection");
options->addOptionChaining("dbaddress", "dbaddress", moe::String, "dbaddress")
.hidden()
.positional(1, 1);
options->addOptionChaining("files", "files", moe::StringVector, "files")
.hidden()
.positional(2, -1);
// for testing, kill op will also be disabled automatically if the tests starts a mongo
// program
options->addOptionChaining("nokillop", "nokillop", moe::Switch, "nokillop").hidden();
// for testing, will kill op without prompting
options->addOptionChaining("autokillop", "autokillop", moe::Switch, "autokillop").hidden();
options
->addOptionChaining("useLegacyWriteOps",
"useLegacyWriteOps",
moe::Switch,
"use legacy write ops instead of write commands")
.hidden();
options
->addOptionChaining("writeMode",
"writeMode",
moe::String,
"mode to determine how writes are done:"
" commands, compatibility, legacy")
.hidden();
options
->addOptionChaining("readMode",
"readMode",
moe::String,
"mode to determine how .find() queries are done:"
" commands, compatibility, legacy")
.hidden();
options->addOptionChaining(
"retryWrites",
"retryWrites",
moe::Switch,
"automatically retry write operations upon transient network errors");
options->addOptionChaining("disableImplicitSessions",
"disableImplicitSessions",
moe::Switch,
"do not automatically create and use implicit sessions");
options
->addOptionChaining(
"rpcProtocols", "rpcProtocols", moe::String, " none, opQueryOnly, opCommandOnly, all")
.hidden();
ret = addMessageCompressionOptions(options, true);
if (!ret.isOK())
return ret;
options->addOptionChaining(
"jsHeapLimitMB", "jsHeapLimitMB", moe::Int, "set the js scope's heap size limit");
return Status::OK();
}
std::string getMongoShellHelp(StringData name, const moe::OptionSection& options) {
StringBuilder sb;
sb << "usage: " << name << " [options] [db address] [file names (ending in .js)]\n"
<< "db address can be:\n"
<< " foo foo database on local machine\n"
<< " 192.168.0.5/foo foo database on 192.168.0.5 machine\n"
<< " 192.168.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999\n"
<< options.helpString() << "\n"
<< "file names: a list of files to run. files have to end in .js and will exit after "
<< "unless --shell is specified";
return sb.str();
}
bool handlePreValidationMongoShellOptions(const moe::Environment& params,
const std::vector<std::string>& args) {
auto&& vii = VersionInfoInterface::instance();
if (params.count("version") || params.count("help")) {
setPlainConsoleLogger();
log() << mongoShellVersion(vii);
if (params.count("help")) {
log() << getMongoShellHelp(args[0], moe::startupOptions);
} else {
vii.logBuildInfo();
}
return false;
}
return true;
}
Status storeMongoShellOptions(const moe::Environment& params,
const std::vector<std::string>& args) {
Status ret = Status::OK();
if (params.count("quiet")) {
mongo::serverGlobalParams.quiet.store(true);
}
#ifdef MONGO_CONFIG_SSL
ret = storeSSLClientOptions(params);
if (!ret.isOK()) {
return ret;
}
#endif
if (params.count("ipv6")) {
mongo::enableIPv6();
}
if (params.count("verbose")) {
logger::globalLogDomain()->setMinimumLoggedSeverity(logger::LogSeverity::Debug(1));
}
// `objcheck` option is part of `serverGlobalParams` to avoid making common parts depend upon
// the client options. The option is set to false in clients by default.
if (params.count("objcheck")) {
serverGlobalParams.objcheck = true;
} else if (params.count("noobjcheck")) {
serverGlobalParams.objcheck = false;
} else {
serverGlobalParams.objcheck = false;
}
if (params.count("port")) {
shellGlobalParams.port = params["port"].as<string>();
}
if (params.count("host")) {
shellGlobalParams.dbhost = params["host"].as<string>();
}
if (params.count("eval")) {
shellGlobalParams.script = params["eval"].as<string>();
}
if (params.count("username")) {
shellGlobalParams.username = params["username"].as<string>();
}
if (params.count("password")) {
shellGlobalParams.password = params["password"].as<string>();
}
if (params.count("authenticationDatabase")) {
shellGlobalParams.authenticationDatabase = params["authenticationDatabase"].as<string>();
}
if (params.count("authenticationMechanism")) {
shellGlobalParams.authenticationMechanism = params["authenticationMechanism"].as<string>();
}
if (params.count("gssapiServiceName")) {
shellGlobalParams.gssapiServiceName = params["gssapiServiceName"].as<string>();
}
if (params.count("gssapiHostName")) {
shellGlobalParams.gssapiHostName = params["gssapiHostName"].as<string>();
}
if (params.count("net.compression.compressors")) {
auto compressors = params["net.compression.compressors"].as<string>();
if (compressors != "disabled") {
shellGlobalParams.networkMessageCompressors = std::move(compressors);
}
}
if (params.count("shell")) {
shellGlobalParams.runShell = true;
}
if (params.count("nodb")) {
shellGlobalParams.nodb = true;
}
if (params.count("disableJavaScriptProtection")) {
shellGlobalParams.javascriptProtection = false;
}
if (params.count("norc")) {
shellGlobalParams.norc = true;
}
if (params.count("disableJavaScriptJIT")) {
shellGlobalParams.nojit = true;
}
if (params.count("files")) {
shellGlobalParams.files = params["files"].as<vector<string>>();
}
if (params.count("nokillop")) {
mongo::shell_utils::_nokillop = true;
}
if (params.count("autokillop")) {
shellGlobalParams.autoKillOp = true;
}
if (params.count("useLegacyWriteOps")) {
shellGlobalParams.writeMode = "legacy";
}
if (params.count("writeMode")) {
std::string mode = params["writeMode"].as<string>();
if (mode != "commands" && mode != "legacy" && mode != "compatibility") {
uasserted(17396, mongoutils::str::stream() << "Unknown writeMode option: " << mode);
}
shellGlobalParams.writeMode = mode;
}
if (params.count("readMode")) {
std::string mode = params["readMode"].as<string>();
if (mode != "commands" && mode != "compatibility" && mode != "legacy") {
uasserted(17397,
mongoutils::str::stream()
<< "Unknown readMode option: '"
<< mode
<< "'. Valid modes are: {commands, compatibility, legacy}");
}
shellGlobalParams.readMode = mode;
}
if (params.count("retryWrites")) {
shellGlobalParams.shouldRetryWrites = true;
}
if (params.count("disableImplicitSessions")) {
shellGlobalParams.shouldUseImplicitSessions = false;
}
if (params.count("rpcProtocols")) {
std::string protos = params["rpcProtocols"].as<string>();
auto parsedRPCProtos = rpc::parseProtocolSet(protos);
if (!parsedRPCProtos.isOK()) {
uasserted(28653,
str::stream() << "Unknown RPC Protocols: '" << protos
<< "'. Valid values are {none, opQueryOnly, "
<< "opCommandOnly, all}");
}
shellGlobalParams.rpcProtocols = parsedRPCProtos.getValue();
}
/* This is a bit confusing, here are the rules:
*
* if nodb is set then all positional parameters are files
* otherwise the first positional parameter might be a dbaddress, but
* only if one of these conditions is met:
* - it contains no '.' after the last appearance of '\' or '/'
* - it doesn't end in '.js' and it doesn't specify a path to an existing file */
if (params.count("dbaddress")) {
string dbaddress = params["dbaddress"].as<string>();
if (shellGlobalParams.nodb) {
shellGlobalParams.files.insert(shellGlobalParams.files.begin(), dbaddress);
} else {
string basename = dbaddress.substr(dbaddress.find_last_of("/\\") + 1);
if (basename.find_first_of('.') == string::npos ||
(basename.find(".js", basename.size() - 3) == string::npos &&
!::mongo::shell_utils::fileExists(dbaddress))) {
shellGlobalParams.url = dbaddress;
} else {
shellGlobalParams.files.insert(shellGlobalParams.files.begin(), dbaddress);
}
}
}
if (params.count("jsHeapLimitMB")) {
int jsHeapLimitMB = params["jsHeapLimitMB"].as<int>();
if (jsHeapLimitMB <= 0) {
StringBuilder sb;
sb << "ERROR: \"jsHeapLimitMB\" needs to be greater than 0";
return Status(ErrorCodes::BadValue, sb.str());
}
shellGlobalParams.jsHeapLimitMB = jsHeapLimitMB;
}
if (shellGlobalParams.url == "*") {
StringBuilder sb;
sb << "ERROR: "
<< "\"*\" is an invalid db address";
sb << getMongoShellHelp(args[0], moe::startupOptions);
return Status(ErrorCodes::BadValue, sb.str());
}
if ((shellGlobalParams.url.find("mongodb://") == 0) ||
(shellGlobalParams.url.find("mongodb+srv://") == 0)) {
auto cs_status = MongoURI::parse(shellGlobalParams.url);
if (!cs_status.isOK()) {
return cs_status.getStatus();
}
auto cs = cs_status.getValue();
auto uriOptions = cs.getOptions();
auto handleURIOptions = [&] {
StringBuilder sb;
sb << "ERROR: Cannot specify ";
if (!shellGlobalParams.username.empty() && !cs.getUser().empty() &&
shellGlobalParams.username != cs.getUser()) {
sb << "different usernames";
} else if (!shellGlobalParams.password.empty() && !cs.getPassword().empty() &&
shellGlobalParams.password != cs.getPassword()) {
sb << "different passwords";
} else if (!shellGlobalParams.authenticationMechanism.empty() &&
uriOptions.count("authMechanism") &&
uriOptions["authMechanism"] != shellGlobalParams.authenticationMechanism) {
sb << "different authentication mechanisms";
} else if (!shellGlobalParams.authenticationDatabase.empty() &&
uriOptions.count("authSource") &&
uriOptions["authSource"] != shellGlobalParams.authenticationDatabase) {
sb << "different authentication databases";
} else if (shellGlobalParams.gssapiServiceName != saslDefaultServiceName &&
uriOptions.count("gssapiServiceName")) {
sb << "the GSSAPI service name";
} else if (!shellGlobalParams.networkMessageCompressors.empty() &&
uriOptions.count("compressors") &&
uriOptions["compressors"] != shellGlobalParams.networkMessageCompressors) {
sb << "different network message compressors";
} else {
return Status::OK();
}
sb << " in connection URI and as a command-line option";
return Status(ErrorCodes::InvalidOptions, sb.str());
};
auto uriStatus = handleURIOptions();
if (!uriStatus.isOK())
return uriStatus;
if (uriOptions.count("compressors"))
shellGlobalParams.networkMessageCompressors = uriOptions["compressors"];
}
if (!shellGlobalParams.networkMessageCompressors.empty()) {
const auto ret =
storeMessageCompressionOptions(shellGlobalParams.networkMessageCompressors);
if (!ret.isOK()) {
return ret;
}
}
return Status::OK();
}
void redactPasswordOptions(int argc, char** argv) {
constexpr auto kLongPasswordOption = "--password"_sd;
constexpr auto kShortPasswordOption = "-p"_sd;
for (int i = 0; i < argc; ++i) {
StringData arg(argv[i]);
if (arg.startsWith(kShortPasswordOption)) {
char* toRedact = nullptr;
// Handle -p password
if ((arg == kShortPasswordOption) && (i + 1 < argc)) {
toRedact = argv[++i];
// Handle -ppassword
} else {
toRedact = argv[i] + kShortPasswordOption.size();
}
invariant(toRedact);
// The arg should be null-terminated, replace everything up to \0 to 'x'
while (*toRedact) {
*toRedact++ = 'x';
}
}
if (arg.startsWith(kLongPasswordOption)) {
char* toRedact = nullptr;
// Handle --password password
if ((arg == kLongPasswordOption) && (i + 1 < argc)) {
toRedact = argv[++i];
// Handle --password=password
} else if (arg.size() != kLongPasswordOption.size()) {
toRedact = argv[i] + kLongPasswordOption.size();
// It's not valid to do --passwordpassword, make sure there's an = separator
invariant(*(toRedact++) == '=');
}
// If there's nothing to redact, just exit
if (!toRedact) {
continue;
}
// The arg should be null-terminated, replace everything up to \0 to 'x'
while (*toRedact) {
*toRedact++ = 'x';
}
} else if (MongoURI::isMongoURI(arg)) {
auto reformedURI = MongoURI::redact(arg);
auto length = arg.size();
::strncpy(argv[i], reformedURI.data(), length);
}
}
}
} // namespace mongo
|