/
MongoConnection.cs
463 lines (415 loc) · 19.1 KB
/
MongoConnection.cs
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
/* Copyright 2010-2011 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
namespace MongoDB.Driver.Internal {
internal enum MongoConnectionState {
Initial,
Open,
Damaged,
Closed
}
internal class MongoConnection {
#region private fields
private object connectionLock = new object();
private MongoServerInstance serverInstance;
private MongoConnectionPool connectionPool;
private MongoConnectionState state;
private TcpClient tcpClient;
private DateTime createdAt;
private DateTime lastUsedAt; // set every time the connection is Released
private int messageCounter;
private Dictionary<string, Authentication> authentications = new Dictionary<string, Authentication>();
#endregion
#region constructors
internal MongoConnection(
MongoConnectionPool connectionPool
) {
this.serverInstance = connectionPool.ServerInstance;
this.connectionPool = connectionPool;
this.createdAt = DateTime.UtcNow;
this.state = MongoConnectionState.Initial;
}
#endregion
#region internal properties
internal MongoConnectionPool ConnectionPool {
get { return connectionPool; }
}
internal DateTime CreatedAt {
get { return createdAt; }
}
internal DateTime LastUsedAt {
get { return lastUsedAt; }
set { lastUsedAt = value; }
}
internal int MessageCounter {
get { return messageCounter; }
}
internal MongoServerInstance ServerInstance {
get { return serverInstance; }
}
internal MongoConnectionState State {
get { return state; }
}
#endregion
#region internal methods
internal void Authenticate(
string databaseName,
MongoCredentials credentials
) {
if (state == MongoConnectionState.Closed) { throw new InvalidOperationException("Connection is closed"); }
lock (connectionLock) {
var nonceCommand = new CommandDocument("getnonce", 1);
var commandCollectionName = string.Format("{0}.$cmd", databaseName);
string nonce;
try {
var nonceResult = RunCommand(commandCollectionName, QueryFlags.None, nonceCommand);
nonce = nonceResult.Response["nonce"].AsString;
} catch (MongoCommandException ex) {
throw new MongoAuthenticationException("Error getting nonce for authentication", ex);
}
var passwordDigest = MongoUtils.Hash(credentials.Username + ":mongo:" + credentials.Password);
var digest = MongoUtils.Hash(nonce + credentials.Username + passwordDigest);
var authenticateCommand = new CommandDocument {
{ "authenticate", 1 },
{ "user", credentials.Username },
{ "nonce", nonce },
{ "key", digest }
};
try {
RunCommand(commandCollectionName, QueryFlags.None, authenticateCommand);
} catch (MongoCommandException ex) {
var message = string.Format("Invalid credentials for database: {0}", databaseName);
throw new MongoAuthenticationException(message, ex);
}
var authentication = new Authentication(credentials);
authentications.Add(databaseName, authentication);
}
}
// check whether the connection can be used with the given database (and credentials)
// the following are the only valid authentication states for a connection:
// 1. the connection is not authenticated against any database
// 2. the connection has a single authentication against the admin database (with a particular set of credentials)
// 3. the connection has one or more authentications against any databases other than admin
// (with the restriction that a particular database can only be authenticated against once and therefore with only one set of credentials)
// assume that IsAuthenticated was called first and returned false
internal bool CanAuthenticate(
MongoDatabase database
) {
if (state == MongoConnectionState.Closed) { throw new InvalidOperationException("Connection is closed"); }
if (database == null) {
return true;
}
if (authentications.Count == 0) {
// a connection with no existing authentications can authenticate anything
return true;
} else {
// a connection with existing authentications can't be used without credentials
if (database.Credentials == null) {
return false;
}
// a connection with existing authentications can't be used with new admin credentials
if (database.Credentials.Admin) {
return false;
}
// a connection with an existing authentication to the admin database can't be used with any other credentials
if (authentications.ContainsKey("admin")) {
return false;
}
// a connection with an existing authentication to a database can't authenticate for the same database again
if (authentications.ContainsKey(database.Name)) {
return false;
}
return true;
}
}
internal void CheckAuthentication(
MongoDatabase database
) {
if (state == MongoConnectionState.Closed) { throw new InvalidOperationException("Connection is closed"); }
if (database.Credentials == null) {
if (authentications.Count != 0) {
throw new InvalidOperationException("Connection requires credentials");
}
} else {
var credentials = database.Credentials;
var authenticationDatabaseName = credentials.Admin ? "admin" : database.Name;
Authentication authentication;
if (authentications.TryGetValue(authenticationDatabaseName, out authentication)) {
if (authentication.Credentials != database.Credentials) {
// this shouldn't happen because a connection would have been chosen from the connection pool only if it was viable
if (authenticationDatabaseName == "admin") {
throw new MongoInternalException("Connection already authenticated to the admin database with different credentials");
} else {
throw new MongoInternalException("Connection already authenticated to the database with different credentials");
}
}
authentication.LastUsed = DateTime.UtcNow;
} else {
if (authenticationDatabaseName == "admin" && authentications.Count != 0) {
// this shouldn't happen because a connection would have been chosen from the connection pool only if it was viable
throw new MongoInternalException("The connection cannot be authenticated against the admin database because it is already authenticated against other databases");
}
Authenticate(authenticationDatabaseName, database.Credentials);
}
}
}
internal void Close() {
lock (connectionLock) {
if (state != MongoConnectionState.Closed) {
if (tcpClient != null) {
if (tcpClient.Connected) {
// even though MSDN says TcpClient.Close doesn't close the underlying socket
// it actually does (as proven by disassembling TcpClient and by experimentation)
tcpClient.Close();
}
tcpClient = null;
}
state = MongoConnectionState.Closed;
}
}
}
internal bool IsAuthenticated(
MongoDatabase database
) {
if (state == MongoConnectionState.Closed) { throw new InvalidOperationException("Connection is closed"); }
if (database == null) {
return true;
}
lock (connectionLock) {
if (database.Credentials == null) {
return authentications.Count == 0;
} else {
var authenticationDatabaseName = database.Credentials.Admin ? "admin" : database.Name;
Authentication authentication;
if (authentications.TryGetValue(authenticationDatabaseName, out authentication)) {
return database.Credentials == authentication.Credentials;
} else {
return false;
}
}
}
}
internal void Logout(
string databaseName
) {
if (state == MongoConnectionState.Closed) { throw new InvalidOperationException("Connection is closed"); }
lock (connectionLock) {
var logoutCommand = new CommandDocument("logout", 1);
var commandCollectionName = string.Format("{0}.$cmd", databaseName);
try {
RunCommand(commandCollectionName, QueryFlags.None, logoutCommand);
} catch (MongoCommandException ex) {
throw new MongoAuthenticationException("Error logging off", ex);
}
authentications.Remove(databaseName);
}
}
internal void Open() {
if (state != MongoConnectionState.Initial) {
throw new InvalidOperationException("Open called more than once");
}
var endPoint = serverInstance.EndPoint;
var tcpClient = new TcpClient(endPoint.AddressFamily);
tcpClient.NoDelay = true; // turn off Nagle
tcpClient.ReceiveBufferSize = MongoDefaults.TcpReceiveBufferSize;
tcpClient.SendBufferSize = MongoDefaults.TcpSendBufferSize;
//tcpClient.Connect(endPoint);
var asynResult = tcpClient.BeginConnect(endPoint.Address, endPoint.Port, null, null);
var waitHandle = asynResult.AsyncWaitHandle;
try {
if (!asynResult.AsyncWaitHandle.WaitOne(this.serverInstance.Server.Settings.ConnectTimeout, false)) {
tcpClient.Close();
throw new TimeoutException();
}
tcpClient.EndConnect(asynResult);
}
finally
{
waitHandle.Close();
}
this.tcpClient = tcpClient;
this.state = MongoConnectionState.Open;
}
// this is a low level method that doesn't require a MongoServer
// so it can be used while connecting to a MongoServer
internal CommandResult RunCommand(
string collectionName,
QueryFlags queryFlags,
CommandDocument command
) {
var commandName = command.GetElement(0).Name;
using (
var message = new MongoQueryMessage(
this,
collectionName,
queryFlags,
0, // numberToSkip
1, // numberToReturn (must be 1 or -1 for commands)
command,
null // fields
)
) {
SendMessage(message, SafeMode.False);
}
var reply = ReceiveMessage<BsonDocument>(null);
if (reply.NumberReturned == 0) {
var message = string.Format("Command '{0}' failed: no response returned", commandName);
throw new MongoCommandException(message);
}
var commandResult = new CommandResult(command, reply.Documents[0]);
if (!commandResult.Ok) {
throw new MongoCommandException(commandResult);
}
return commandResult;
}
internal MongoReplyMessage<TDocument> ReceiveMessage<TDocument>(
IBsonSerializationOptions serializationOptions
) {
if (state == MongoConnectionState.Closed) { throw new InvalidOperationException("Connection is closed"); }
lock (connectionLock) {
try {
using (var buffer = new BsonBuffer()) {
var networkStream = GetNetworkStream();
networkStream.ReadTimeout = (int) serverInstance.Server.Settings.SocketTimeout.TotalMilliseconds;
buffer.LoadFrom(networkStream);
var reply = new MongoReplyMessage<TDocument>(this);
reply.ReadFrom(buffer, serializationOptions);
return reply;
}
} catch (Exception ex) {
HandleException(ex);
throw;
}
}
}
internal SafeModeResult SendMessage(
MongoRequestMessage message,
SafeMode safeMode
) {
if (state == MongoConnectionState.Closed) { throw new InvalidOperationException("Connection is closed"); }
lock (connectionLock) {
message.WriteToBuffer();
CommandDocument safeModeCommand = null;
if (safeMode.Enabled) {
safeModeCommand = new CommandDocument {
{ "getlasterror", 1 }, // use all lowercase for backward compatibility
{ "fsync", true, safeMode.FSync },
{ "w", safeMode.W, safeMode.W > 1 },
{ "wtimeout", (int) safeMode.WTimeout.TotalMilliseconds, safeMode.W > 1 && safeMode.WTimeout != TimeSpan.Zero }
};
using (
var getLastErrorMessage = new MongoQueryMessage(
this,
"admin.$cmd", // collectionFullName
QueryFlags.None,
0, // numberToSkip
1, // numberToReturn
safeModeCommand,
null, // fields
message.Buffer // piggy back on network transmission for message
)
) {
getLastErrorMessage.WriteToBuffer();
}
}
try {
var networkStream = GetNetworkStream();
networkStream.WriteTimeout = (int) serverInstance.Server.Settings.SocketTimeout.TotalMilliseconds;
message.Buffer.WriteTo(networkStream);
messageCounter++;
} catch (Exception ex) {
HandleException(ex);
throw;
}
SafeModeResult safeModeResult = null;
if (safeMode.Enabled) {
var replyMessage = ReceiveMessage<BsonDocument>(null);
var safeModeResponse = replyMessage.Documents[0];
safeModeResult = new SafeModeResult();
safeModeResult.Initialize(safeModeCommand, safeModeResponse);
if (!safeModeResult.Ok) {
var errorMessage = string.Format("Safemode detected an error: {0} (response: {1})", safeModeResult.ErrorMessage, safeModeResponse.ToJson());
throw new MongoSafeModeException(errorMessage, safeModeResult);
}
if (safeModeResult.HasLastErrorMessage) {
var errorMessage = string.Format("Safemode detected an error: {0} (response: {1})", safeModeResult.LastErrorMessage, safeModeResponse.ToJson());
throw new MongoSafeModeException(errorMessage, safeModeResult);
}
}
return safeModeResult;
}
}
#endregion
#region private methods
private NetworkStream GetNetworkStream() {
if (state == MongoConnectionState.Initial) {
Open();
}
return tcpClient.GetStream();
}
private void HandleException(
Exception ex
) {
// TODO: figure out which exceptions are more serious than others
// there are three possible situations:
// 1. we can keep using the connection
// 2. just this one connection needs to be discarded
// 3. the whole connection pool needs to be discarded
// for now the only exception we know affects only one connection is FileFormatException
// and there are no cases where the connection can continue to be used
state = MongoConnectionState.Damaged;
if (!(ex is FileFormatException)) {
try {
serverInstance.Disconnect();
} catch { } // ignore any further exceptions
}
}
#endregion
#region private nested classes
// keeps track of what credentials were used with a given database
// and when that database was last used on this connection
private class Authentication {
#region private fields
private MongoCredentials credentials;
private DateTime lastUsed;
#endregion
#region constructors
public Authentication(
MongoCredentials credentials
) {
this.credentials = credentials;
this.lastUsed = DateTime.UtcNow;
}
#endregion
public MongoCredentials Credentials {
get { return credentials; }
}
public DateTime LastUsed {
get { return lastUsed; }
set { lastUsed = value; }
}
}
#endregion
}
}