Exemplo n.º 1
0
        /// <summary>
        /// Authenticates the specified connection.
        /// </summary>
        /// <param retval="connection">The connection.</param>
        /// <returns></returns>
        protected bool Authenticate(IConnection connection)
        {
            if (string.IsNullOrEmpty(ConnectionString.UserName))
            {
                return true;
            }

            var nonce = new MongoCollection<GetNonceResponse>("$cmd", new MongoDatabase("admin", connection), connection).FindOne(new { getnonce = 1 });

            if (nonce.WasSuccessful)
            {
                var result = new QueryMessage<GenericCommandResponse, AuthenticationRequest>(connection, string.Concat(connection.Database, ".$cmd"))
                {
                    NumberToTake = 1,
                    Query = new AuthenticationRequest
                    {
                        User = connection.UserName,
                        Nonce = nonce.Nonce,
                        Key = connection.Digest(nonce.Nonce),
                    }
                }.Execute();

                return result.Results.Count() == 1 && result.Results.ElementAt(0).WasSuccessful;
            }

            return false;
        }
 // methods
 private QueryFlags BuildQueryFlags(QueryMessage message)
 {
     var flags = QueryFlags.None;
     if (message.NoCursorTimeout)
     {
         flags |= QueryFlags.NoCursorTimeout;
     }
     if (message.PartialOk)
     {
         flags |= QueryFlags.Partial;
     }
     if (message.SlaveOk)
     {
         flags |= QueryFlags.SlaveOk;
     }
     if (message.TailableCursor)
     {
         flags |= QueryFlags.TailableCursor;
     }
     if (message.AwaitData)
     {
         flags |= QueryFlags.AwaitData;
     }
     return flags;
 }
Exemplo n.º 3
0
        public static void HandleClient(object obj)
        {
            // retrieve client from parameter passed to thread
            TcpClient client = (TcpClient)obj;

            Log("New Client Connected");

            String data = null;
            // Buffer for reading data
            Byte[] bytes = new Byte[256];

            // Get a stream object for reading and writing
            NetworkStream stream = client.GetStream();

            int i = stream.Read(bytes, 0, bytes.Length);
            // Loop to receive all the data sent by the client.

            // Translate data bytes to a ASCII string.
            data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
            Log(string.Format("Received Search Request: {0}", data));

            // Process the data sent by the client.
            String searchString = data;

            if (File.Exists(Searcher.dbFileName))
            {
                List<List<Contact>> answers = new List<List<Contact>>();
                QueryMessage queryMsg = new QueryMessage();
                queryMsg.query = searchString;
                queryMsg.nbNodes = nbNodes;
                Stopwatch stopwatch = Stopwatch.StartNew();
                g.OrderedQuery(Vsync.Group.ALL, new Vsync.Timeout(120000, Vsync.Timeout.TO_ABORTREPLY), SEARCH, queryMsg, new Vsync.EOLMarker(), answers);
                stopwatch.Stop();
                List<Contact> contacts = new List<Contact>();
                for (int ans = 0; ans < answers.Count; ans++)
                {
                    contacts.AddRange(answers[ans]);
                }
                if (contacts.Count > 100)
                {
                    contacts = contacts.GetRange(0, 100);
                }
                byte[] msg = ObjectToByteArray(contacts);
                byte[] msgSize = System.Text.Encoding.ASCII.GetBytes(msg.Length + "");
                stream.Write(msgSize, 0, msgSize.Length);
                stream.Write(msg, 0, msg.Length);
                Log(string.Format("Sent Result of \"{1}\": {0} - Search Completed In {2} (ms)", contacts.Count, searchString, stopwatch.ElapsedMilliseconds));
            }
            else
            {
                String Error = "Error: database not ready";
                byte[] msg = System.Text.Encoding.ASCII.GetBytes(Error);
                stream.Write(msg, 0, msg.Length);
            }

            // Shutdown and end connection
            client.Close();
        }
        protected QueryMessage generateQueryMessage()
        {
            Document qdoc = new Document();
            qdoc.Add("listDatabases", 1.0);
            //QueryMessage qmsg = new QueryMessage(qdoc,"system.namespaces");
            QueryMessage qmsg = new QueryMessage(qdoc,"admin.$cmd");
            qmsg.NumberToReturn = -1;

            return qmsg;
        }
Exemplo n.º 5
0
        public void TestAllBytesWritten()
        {
            Document query = new Document();
            query.Add("col1", 1);

            QueryMessage msg = new QueryMessage(query,"TestDB.TestCol");
            MemoryStream buffer = new MemoryStream();
            msg.Write(buffer);

            Byte[] output = buffer.ToArray();
            String hexdump = BitConverter.ToString(output);
            //Console.WriteLine("Dump: " + hexdump);

            Assert.IsTrue(output.Length > 0);
            Assert.AreEqual("3A-00-00-00-00-00-00-00-00-00-00-00-D4-07-00-00-00-00-00-00-54-65-73-74-44-42-2E-54-65-73-74-43-6F-6C-00-00-00-00-00-00-00-00-00-0F-00-00-00-10-63-6F-6C-31-00-01-00-00-00-00", hexdump);
        }
Exemplo n.º 6
0
        public void TestWriteMessageTwice()
        {
            string expectedHex = "3A-00-00-00-00-00-00-00-00-00-00-00-D4-07-00-00-00-00-00-00-54-65-73-74-44-42-2E-54-65-73-74-43-6F-6C-00-00-00-00-00-00-00-00-00-0F-00-00-00-10-63-6F-6C-31-00-01-00-00-00-00";
            Document query = new Document();
            query.Add("col1", 1);

            QueryMessage msg = new QueryMessage(query,"TestDB.TestCol");
            MemoryStream buffer = new MemoryStream();
            msg.Write(buffer);

            Byte[] output = buffer.ToArray();
            String hexdump = BitConverter.ToString(output);

            MemoryStream buffer2 = new MemoryStream();
            msg.Write(buffer2);

            Byte[] output2 = buffer.ToArray();
            String hexdump2 = BitConverter.ToString(output2);

            Assert.AreEqual(expectedHex,hexdump);
            Assert.AreEqual(hexdump,hexdump2);
        }
Exemplo n.º 7
0
 public CreateEventRec()
 {
     m_parent = null;
     m_RequestID = 0;
     m_EventType = 0;
     m_RequestedPeriodicRate = 0;
     m_QueryMessage = new QueryMessage();
     m_QueryMessage.setParent(this);
 }
 public static void Add(this IObservableCollection<QueryMessageViewModel> collection, QueryMessage message) {
     collection.Add(new QueryMessageViewModel() {
         Index = collection.Count,
         Model = message
     });
 }
Exemplo n.º 9
0
        private void IgnoreResponse(IConnection connection, QueryMessage message, CancellationToken cancellationToken)
        {
            var encoderSelector = new ReplyMessageEncoderSelector <IgnoredReply>(IgnoredReplySerializer.Instance);

            connection.ReceiveMessageAsync(message.RequestId, encoderSelector, _messageEncoderSettings, cancellationToken).IgnoreExceptions();
        }
        /// <summary>
        /// Writes the message.
        /// </summary>
        /// <param name="message">The message.</param>
        public void WriteMessage(QueryMessage message)
        {
            Ensure.IsNotNull(message, nameof(message));

            var messageDocument = new BsonDocument
            {
                { "opcode", "query" },
                { "requestId", message.RequestId },
                { "database", message.CollectionNamespace.DatabaseNamespace.DatabaseName },
                { "collection", message.CollectionNamespace.CollectionName },
                { "fields", message.Fields, message.Fields != null },
                { "skip", message.Skip, message.Skip != 0 },
                { "batchSize", message.BatchSize, message.BatchSize != 0 },
                { "slaveOk", true, message.SlaveOk },
                { "partialOk", true, message.PartialOk },
                { "noCursorTimeout", true, message.NoCursorTimeout },
                { "oplogReplay", true, message.OplogReplay },
                { "tailableCursor", true, message.TailableCursor },
                { "awaitData", true, message.AwaitData },
                { "query", message.Query }
            };

            var jsonWriter = CreateJsonWriter();
            var messageContext = BsonSerializationContext.CreateRoot(jsonWriter);
            BsonDocumentSerializer.Instance.Serialize(messageContext, messageDocument);
        }
Exemplo n.º 11
0
                    public QueryMessage(QueryMessage value)
                    {
                        /// Initiliaze the protected variables
                        m_parent = null;
                        m_Length = 0;
                        m_Data = null;

                        /// Copy the values
                        this.m_Length = value.m_Length;

                        m_Data = null;

                        if (m_Length > 0)
                        {
                        m_Data = new byte[(int)m_Length];
                        this.m_Data = value.m_Data;
                        }
                    }
Exemplo n.º 12
0
                    public bool isEqual(QueryMessage value)
                    {
                        if (this.m_Length != value.m_Length)
                        {
                        return false;
                        }

                        if ((this.m_Data != null) && (value.m_Data!= null))
                        {
                        for(int i = 0; i < value.m_Length; i++)
                        {
                            if (this.m_Data[i] != value.m_Data[i])
                            {
                                return false;
                            }
                        }
                        }
                        // This case should never be true since it should not be possible
                        // for the two variables to have equal lengths but one has no data.
                        // This check is placed here as a secondary check.
                        else if ((this.m_Data != null) || (value.m_Data != null))
                        {
                        return false;
                        }

                        return true;
                    }
Exemplo n.º 13
0
 public void setQueryMessage(QueryMessage value)
 {
     m_QueryMessage = value;
     setParentPresenceVector();
 }
Exemplo n.º 14
0
 void RaiseMessageSent(Node node, IPEndPoint endpoint, QueryMessage query, ResponseMessage response)
 {
     QuerySent?.Invoke(this, new SendQueryEventArgs(node, endpoint, query, response));
 }
Exemplo n.º 15
0
 // constructors
 public PostProcessor(QueryMessage message, BsonStream stream, long messageStartPosition)
 {
     _message = message;
     _stream  = stream;
     _messageStartPosition = messageStartPosition;
 }
Exemplo n.º 16
0
 public void setQueryMessage(QueryMessage value)
 {
     m_QueryMessage = value;
     setParentPresenceVector();
 }
Exemplo n.º 17
0
 public bool notEquals(QueryMessage value)
 {
     return(!this.isEqual(value));
 }
Exemplo n.º 18
0
                    public UpdateEvent.Body.UpdateEventRec.QueryMessage  setQueryMessage(QueryMessage value)
                    {
                        this.m_Length = value.m_Length;

                        m_Data = null;

                        if (m_Length > 0)
                        {
                            m_Data      = new byte[(int)m_Length];
                            this.m_Data = value.m_Data;
                        }

                        return(this);
                    }
Exemplo n.º 19
0
 protected ResponseMessage(BEncodedDictionary d, QueryMessage m)
     : base(d)
 {
     Query = m;
 }
Exemplo n.º 20
0
                public CreateEventRec(CreateEventRec value)
                {
                    /// Initiliaze the protected variables
                    m_parent = null;
                    m_RequestID = 0;
                    m_EventType = 0;
                    m_RequestedPeriodicRate = 0;
                    m_QueryMessage = new QueryMessage();
                    m_QueryMessage.setParent(this);

                    /// Copy the values
                    m_RequestID = value.m_RequestID;
                    m_EventType = value.m_EventType;
                    m_RequestedPeriodicRate = value.m_RequestedPeriodicRate;
                    m_QueryMessage = value.getQueryMessage();
                }
Exemplo n.º 21
0
                public CreateEvent.Body.CreateEventRec setCreateEventRec(CreateEventRec value)
                {
                    m_RequestID = value.m_RequestID;
                    m_EventType = value.m_EventType;
                    m_RequestedPeriodicRate = value.m_RequestedPeriodicRate;
                    m_QueryMessage = value.getQueryMessage();

                    return this;
                }
Exemplo n.º 22
0
                        public ReportEvents.Body.EventList.ReportEventRec.QueryMessage  setQueryMessage(QueryMessage value)
                        {
                            this.m_Length = value.m_Length;

                            m_Data = null;

                            if (m_Length > 0)
                            {
                                m_Data      = new byte[(int)m_Length];
                                this.m_Data = value.m_Data;
                            }

                            return(this);
                        }
Exemplo n.º 23
0
                    public CreateEvent.Body.CreateEventRec.QueryMessage setQueryMessage(QueryMessage value)
                    {
                        this.m_Length = value.m_Length;

                        m_Data = null;

                        if (m_Length > 0)
                        {
                        m_Data = new byte[(int)m_Length];
                        this.m_Data = value.m_Data;
                        }

                        return this;
                    }
Exemplo n.º 24
0
        /// <summary>
        /// Finds documents.
        /// </summary>
        /// <param name="template">The document template.</param>
        /// <param name="limit">The limit.</param>
        /// <param name="fullyQualifiedName">The fully qualified name.</param>
        /// <returns></returns>
        public IEnumerable Find(object template, int limit, string fullyQualifiedName)
        {
            var qm = new QueryMessage<object, object>(this._db.CurrentConnection, fullyQualifiedName)
                         {
                             NumberToTake = limit,
                             Query = template
                         };
            var reply = qm.Execute();

            foreach (var r in reply.Results)
            {
                yield return r;
            }

            yield break;
        }
Exemplo n.º 25
0
 public bool notEquals(QueryMessage value)
 {
     return !this.isEqual(value);
 }
        /// <summary>
        /// Writes the message.
        /// </summary>
        /// <param name="message">The message.</param>
        public void WriteMessage(QueryMessage message)
        {
            Ensure.IsNotNull(message, "message");

            var binaryWriter = CreateBinaryWriter();
            var stream = binaryWriter.BsonStream;
            var startPosition = stream.Position;

            stream.WriteInt32(0); // messageSize
            stream.WriteInt32(message.RequestId);
            stream.WriteInt32(0); // responseTo
            stream.WriteInt32((int)Opcode.Query);
            stream.WriteInt32((int)BuildQueryFlags(message));
            stream.WriteCString(message.CollectionNamespace.FullName);
            stream.WriteInt32(message.Skip);
            stream.WriteInt32(message.BatchSize);
            WriteQuery(binaryWriter, message.Query, message.QueryValidator);
            WriteOptionalFields(binaryWriter, message.Fields);
            stream.BackpatchSize(startPosition);
        }
        private void ProcessQueryMessage(QueryMessage originalMessage, ConnectionId connectionId, QueryMessageBinaryEncoder encoder, Stopwatch stopwatch)
        {
            var requestId   = originalMessage.RequestId;
            var operationId = EventContext.OperationId;

            var decodedMessage = encoder.ReadMessage(RawBsonDocumentSerializer.Instance);

            try
            {
                var          isCommand = IsCommand(decodedMessage.CollectionNamespace);
                string       commandName;
                BsonDocument command;
                if (isCommand)
                {
                    command = decodedMessage.Query;
                    var firstElement = command.GetElement(0);
                    commandName = firstElement.Name;
                    if (__securitySensitiveCommands.Contains(commandName))
                    {
                        command = new BsonDocument();
                    }
                }
                else
                {
                    commandName = "find";
                    command     = BuildFindCommandFromQuery(decodedMessage);
                    if (decodedMessage.Query.GetValue("$explain", false).ToBoolean())
                    {
                        commandName = "explain";
                        command     = new BsonDocument("explain", command);
                    }
                }

                if (_startedEvent != null)
                {
                    var @event = new CommandStartedEvent(
                        commandName,
                        command,
                        decodedMessage.CollectionNamespace.DatabaseNamespace,
                        operationId,
                        requestId,
                        connectionId);

                    _startedEvent(@event);
                }

                if (_shouldTrackState)
                {
                    _state.TryAdd(requestId, new CommandState
                    {
                        CommandName          = commandName,
                        OperationId          = operationId,
                        Stopwatch            = stopwatch,
                        QueryNamespace       = decodedMessage.CollectionNamespace,
                        ExpectedResponseType = isCommand ? ExpectedResponseType.Command : ExpectedResponseType.Query
                    });
                }
            }
            finally
            {
                var disposable = decodedMessage.Query as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
                disposable = decodedMessage.Fields as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
        private BsonDocument BuildFindCommandFromQuery(QueryMessage message)
        {
            var batchSize = EventContext.FindOperationBatchSize ?? 0;
            var limit     = EventContext.FindOperationLimit ?? 0;
            var command   = new BsonDocument
            {
                { "find", message.CollectionNamespace.CollectionName },
                { "projection", message.Fields, message.Fields != null },
                { "skip", message.Skip, message.Skip > 0 },
                { "batchSize", batchSize, batchSize > 0 },
                { "limit", limit, limit != 0 },
                { "awaitData", message.AwaitData, message.AwaitData },
                { "noCursorTimeout", message.NoCursorTimeout, message.NoCursorTimeout },
                { "allowPartialResults", message.PartialOk, message.PartialOk },
                { "tailable", message.TailableCursor, message.TailableCursor },
                { "oplogReplay", message.OplogReplay, message.OplogReplay }
            };

            var query = message.Query;

            if (query.ElementCount == 1 && !query.Contains("$query"))
            {
                command["filter"] = query;
            }
            else
            {
                foreach (var element in query)
                {
                    switch (element.Name)
                    {
                    case "$query":
                        command["filter"] = element.Value;
                        break;

                    case "$orderby":
                        command["sort"] = element.Value;
                        break;

                    case "$showDiskLoc":
                        command["showRecordId"] = element.Value;
                        break;

                    case "$explain":
                        // explain is special and gets handled elsewhere
                        break;

                    default:
                        if (element.Name.StartsWith("$"))
                        {
                            command[element.Name.Substring(1)] = element.Value;
                        }
                        else
                        {
                            // theoretically, this should never happen and is illegal.
                            // however, we'll push this up anyways and a command-failure
                            // event will likely get thrown.
                            command[element.Name] = element.Value;
                        }
                        break;
                    }
                }
            }

            return(command);
        }
Exemplo n.º 29
0
                        public ReportEvents.Body.EventList.ReportEventRec.QueryMessage setQueryMessage(QueryMessage value)
                        {
                            this.m_Length = value.m_Length;

                            m_Data = null;

                            if (m_Length > 0)
                            {
                            m_Data = new byte[(int)m_Length];
                            this.m_Data = value.m_Data;
                            }

                            return this;
                        }
Exemplo n.º 30
0
 void RaiseMessageSent(Node node, IPEndPoint endpoint, QueryMessage query, ErrorMessage error)
 {
     QuerySent?.Invoke(this, new SendQueryEventArgs(node, endpoint, query, error));
 }
Exemplo n.º 31
0
 /// <summary>TODO::Description.</summary>
 public IEnumerable Find(object template, object orderBy, int limit, int skip, string fullyQualifiedName)
 {
     var qm = new QueryMessage<object, object>(this._db.CurrentConnection, fullyQualifiedName)
         {
             NumberToTake = limit,
             Query = template,
             OrderBy = orderBy,
             NumberToSkip = skip
         };
     return new MongoQueryExecutor<object, object>(qm);
 }
Exemplo n.º 32
0
 public ReportEventRec()
 {
     m_parent = null;
     m_EventType = 0;
     m_EventID = 0;
     m_QueryMessage = new QueryMessage();
     m_QueryMessage.setParent(this);
 }
Exemplo n.º 33
0
                    public ReportEventRec(ReportEventRec value)
                    {
                        /// Initiliaze the protected variables
                        m_parent = null;
                        m_EventType = 0;
                        m_EventID = 0;
                        m_QueryMessage = new QueryMessage();
                        m_QueryMessage.setParent(this);

                        /// Copy the values
                        m_EventType = value.m_EventType;
                        m_EventID = value.m_EventID;
                        m_QueryMessage = value.getQueryMessage();
                    }
Exemplo n.º 34
0
 public SendQueryTask(DhtEngine engine, QueryMessage query, Node node)
     : this(engine, query, node, 3)
 {
 }