Example #1
0
        private void ListenForEvents()
        {
            _eventClient = new System.Net.Sockets.TcpClient();
            _eventClient.Connect(_host, _eventPort);

            _eventStream = OnPrepareStream(_eventClient.GetStream());

            while (_listenForEvents)
            {
                var rawMessage = TcpProtocolHelper.Read(_eventStream);
                if (rawMessage == null)
                {
                    break;
                }

                var message = TcpMessage.FromRaw(rawMessage);

                foreach (var handler in _eventHandlers)
                {
                    if (handler(message))
                    {
                        break;
                    }
                }
            }
        }
Example #2
0
        private TcpMessage HandleUniqueItemQuery(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType(TcpRequestType.UniqueItemQuery))
            {
                return(null);
            }

            if (!IsAuthenticated(host))
            {
                throw AuthException.NotLoggedIn();
            }

            var request = new ParamTcpMessage(message);

            var response = new ObjectTcpMessage <DbItem>(TcpRequestType.List);

            if (request.HasParam("id"))
            {
                var id = request.GetParamAsNullableInt("id");
                if (id != null)
                {
                    var item = _dataService.GetItem(id.Value);
                    response.Add(item);
                    return(response);
                }
            }

            return(TcpMessage.Error("Missing or badly formatted query parameters"));
        }
Example #3
0
        private void Init(string serverPublicKey = null)
        {
            _asyncServerCryptographyHandler = new RSACryptographyHandler();
            _asyncClientCryptographyHandler = new RSACryptographyHandler { IsReady = true };
            _syncCryptographyHandler = new AESCryptographyHandler();

            // Send client's RSA public key and request the server's RSA public key
            var request = new TcpMessage("rsakey") { Content = _asyncClientCryptographyHandler.PublicKey };
            var response = SendAndReceive(request);
            if (response.HasType("rsakey"))
            {
                var key = response.Content;
                if (!string.IsNullOrEmpty(serverPublicKey) && !serverPublicKey.Equals(key))
                    throw new Exception("Server did not return correct public key");
                _asyncServerCryptographyHandler.PublicKey = key;
            }

            // Request the AES key from the server
            request = new TcpMessage("aeskey");
            response = SendAndReceive(request);
            if (response.HasType("aeskey"))
                _syncCryptographyHandler.KeyAsString = response.Content;

            // Request the AES initialization vector from the server
            request = new TcpMessage("aesiv");
            response = SendAndReceive(request);
            if (response.HasType("aesiv"))
                _syncCryptographyHandler.InitializationVectorAsString = response.Content;
        }
Example #4
0
        private TcpMessage HandleInsertItem(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType(TcpRequestType.InsertItem))
            {
                return(null);
            }

            if (!IsAuthenticated(host))
            {
                throw AuthException.NotLoggedIn();
            }

            var request = new ObjectTcpMessage <DbItem>(message);

            var response = new ObjectTcpMessage <DbItem>(TcpRequestType.List);
            var item     = request.Item;

            if (item != null)
            {
                _dataService.Insert(item);
                response.Add(item); // Send the item back to report assigned Id
            }

            return(response);
        }
Example #5
0
        private TcpMessage HandleMultiRelationQuery(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType(TcpRequestType.MultiRelationQuery))
            {
                return(null);
            }

            if (!IsAuthenticated(host))
            {
                throw AuthException.NotLoggedIn();
            }

            var request = new ParamTcpMessage(message);

            var response = new ObjectTcpMessage <DbRelation>(TcpRequestType.List);

            if (request.HasParam("from_id"))
            {
                var fromId = request.GetParamAsNullableInt("from_id");
                var items  = _dataService.GetRelations(fromId);
                response.Add(items);
                return(response);
            }

            return(TcpMessage.Error("Missing or badly formatted query parameters"));
        }
Example #6
0
        public static TcpMessage FromRaw(string rawContent)
        {
            var message = new TcpMessage();

            message.SetRaw(rawContent);
            return(message);
        }
        private TcpMessage HandleLoginRequest(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType("loginbasic"))
            {
                return(null);
            }

            var request = new ParamTcpMessage(message);

            var username = request.GetParam("username");
            var password = request.GetParam("password");

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                var userItem = _dataService.GetItemByRelation(UsersParentId, username);

                if (userItem == null)
                {
                    if (!AutoRegisterUsers)
                    {
                        return(TcpMessage.Error("User not found. Automatic registering of users is currently disabled."));
                    }

                    // Register
                    userItem = new DbItem(username);
                    _dataService.Insert(userItem);
                    _dataService.Insert(new DbRelation(UsersParentId, username, userItem.Id));

                    var saltItem = new DbItem(HashHelper.CreateSaltString(10));
                    _dataService.Insert(saltItem);
                    _dataService.Insert(new DbRelation(userItem.Id, "salt", saltItem.Id));

                    var passwordItem = new DbItem(HashHelper.GenerateSaltedHash(password, saltItem.Value));
                    _dataService.Insert(passwordItem);
                    _dataService.Insert(new DbRelation(userItem.Id, "password", passwordItem.Id));
                }
                else
                {
                    // Login
                    var saltItem     = _dataService.GetItemByRelation(userItem.Id, "salt");
                    var passwordItem = _dataService.GetItemByRelation(userItem.Id, "password");

                    if (saltItem == null || saltItem.Value == null || passwordItem == null || passwordItem.Value == null || !HashHelper.ConfirmPassword(passwordItem.Value, password, saltItem.Value))
                    {
                        return(TcpMessage.Error("Login failed. Wrong password."));
                    }
                }

                _hostUsers[host] = userItem;

                var response = new ObjectTcpMessage <DbItem>(TcpRequestType.Ok);
                response.Add(userItem);
                return(response);
            }

            return(TcpMessage.Error("Missing or badly formatted login parameters"));
        }
Example #8
0
        public void Add(TcpMessage message)
        {
            if (message == null)
                return;

            lock (_messages)
            {
                _messages.AddLast(message);
            }
            _eventListener.Set();
        }
Example #9
0
        public void Add(TcpMessage message)
        {
            if (message == null)
            {
                return;
            }

            lock (_messages)
            {
                _messages.AddLast(message);
            }
            _eventListener.Set();
        }
Example #10
0
        private bool HandleItemChanged(TcpMessage request)
        {
            if (!request.HasType(TcpRequestType.List))
            {
                return(false);
            }

            var items = new ObjectTcpMessage <ItemChangeEvent>(request).Items;

            if (items != null)
            {
                OnItemsChanged(items.Select(i => i.Id).ToList());
            }

            return(true);
        }
Example #11
0
        private TcpMessage HandleAESKeyExchangeRequest(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType("aeskey"))
            {
                return(null);
            }

            var client = GetClient(host);

            client.AESHandler.GenerateKey();

            return(new TcpMessage("aeskey")
            {
                Content = client.AESHandler.KeyAsString
            });
        }
Example #12
0
        private bool HandleRelationRemoved(TcpMessage request)
        {
            if (!request.HasType(TcpRequestType.DeleteRelation))
            {
                return(false);
            }

            var relation = new ObjectTcpMessage <DbRelation>(request).Item;

            if (relation != null)
            {
                OnRelationRemoved(relation);
            }

            return(true);
        }
Example #13
0
        private TcpMessage HandleRSAKeyExchangeRequest(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType("rsakey"))
            {
                return(null);
            }

            var client = GetClient(host);

            client.RSAHandler.PublicKey    = message.Content;
            client.EncryptNextMessageAsync = false;

            return(new TcpMessage("rsakey")
            {
                Content = _serverCryptographyHandler.PublicKey
            });
        }
Example #14
0
        private TcpMessage HandleDeleteItem(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType(TcpRequestType.DeleteItem))
                return null;

            if (!IsAuthenticated(host))
                throw AuthException.NotLoggedIn();

            var request = new ObjectTcpMessage<DbItem>(message);

            var item = request.Item;
            if (item != null)
            {
                _dataService.Delete(item);
            }

            return new TcpMessage(TcpRequestType.Ok);
        }
Example #15
0
        private void Init(string serverPublicKey = null)
        {
            _asyncServerCryptographyHandler = new RSACryptographyHandler();
            _asyncClientCryptographyHandler = new RSACryptographyHandler {
                IsReady = true
            };
            _syncCryptographyHandler = new AESCryptographyHandler();

            // Send client's RSA public key and request the server's RSA public key
            var request = new TcpMessage("rsakey")
            {
                Content = _asyncClientCryptographyHandler.PublicKey
            };
            var response = SendAndReceive(request);

            if (response.HasType("rsakey"))
            {
                var key = response.Content;
                if (!string.IsNullOrEmpty(serverPublicKey) && !serverPublicKey.Equals(key))
                {
                    throw new Exception("Server did not return correct public key");
                }
                _asyncServerCryptographyHandler.PublicKey = key;
            }

            // Request the AES key from the server
            request  = new TcpMessage("aeskey");
            response = SendAndReceive(request);
            if (response.HasType("aeskey"))
            {
                _syncCryptographyHandler.KeyAsString = response.Content;
            }

            // Request the AES initialization vector from the server
            request  = new TcpMessage("aesiv");
            response = SendAndReceive(request);
            if (response.HasType("aesiv"))
            {
                _syncCryptographyHandler.InitializationVectorAsString = response.Content;
            }
        }
Example #16
0
        private TcpMessage HandleDeleteItem(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType(TcpRequestType.DeleteItem))
            {
                return(null);
            }

            if (!IsAuthenticated(host))
            {
                throw AuthException.NotLoggedIn();
            }

            var request = new ObjectTcpMessage <DbItem>(message);

            var item = request.Item;

            if (item != null)
            {
                _dataService.Delete(item);
            }

            return(new TcpMessage(TcpRequestType.Ok));
        }
Example #17
0
        private TcpMessage HandleAESKeyExchangeRequest(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType("aeskey"))
                return null;

            var client = GetClient(host);
            client.AESHandler.GenerateKey();

            return new TcpMessage("aeskey") { Content = client.AESHandler.KeyAsString };
        }
Example #18
0
        private bool HandleRelationRemoved(TcpMessage request)
        {
            if (!request.HasType(TcpRequestType.DeleteRelation))
                return false;

            var relation = new ObjectTcpMessage<DbRelation>(request).Item;
            if (relation != null)
                OnRelationRemoved(relation);

            return true;
        }
Example #19
0
        private TcpMessage HandleRSAKeyExchangeRequest(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType("rsakey"))
                return null;

            var client = GetClient(host);

            client.RSAHandler.PublicKey = message.Content;
            client.EncryptNextMessageAsync = false;

            return new TcpMessage("rsakey") { Content = _serverCryptographyHandler.PublicKey };
        }
        private TcpMessage HandleLoginRequest(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType("loginbasic"))
                return null;

            var request = new ParamTcpMessage(message);

            var username = request.GetParam("username");
            var password = request.GetParam("password");

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                var userItem = _dataService.GetItemByRelation(UsersParentId, username);

                if (userItem == null)
                {
                    if (!AutoRegisterUsers)
                        return TcpMessage.Error("User not found. Automatic registering of users is currently disabled.");

                    // Register
                    userItem = new DbItem(username);
                    _dataService.Insert(userItem);
                    _dataService.Insert(new DbRelation(UsersParentId, username, userItem.Id));

                    var saltItem = new DbItem(HashHelper.CreateSaltString(10));
                    _dataService.Insert(saltItem);
                    _dataService.Insert(new DbRelation(userItem.Id, "salt", saltItem.Id));

                    var passwordItem = new DbItem(HashHelper.GenerateSaltedHash(password, saltItem.Value));
                    _dataService.Insert(passwordItem);
                    _dataService.Insert(new DbRelation(userItem.Id, "password", passwordItem.Id));
                }
                else
                {
                    // Login
                    var saltItem = _dataService.GetItemByRelation(userItem.Id, "salt");
                    var passwordItem = _dataService.GetItemByRelation(userItem.Id, "password");

                    if (saltItem == null || saltItem.Value == null || passwordItem == null || passwordItem.Value == null || !HashHelper.ConfirmPassword(passwordItem.Value, password, saltItem.Value))
                        return TcpMessage.Error("Login failed. Wrong password.");
                }

                _hostUsers[host] = userItem;

                var response = new ObjectTcpMessage<DbItem>(TcpRequestType.Ok);
                response.Add(userItem);
                return response;
            }

            return TcpMessage.Error("Missing or badly formatted login parameters");
        }
Example #21
0
        private bool HandleItemChanged(TcpMessage request)
        {
            if (!request.HasType(TcpRequestType.List))
                return false;

            var items = new ObjectTcpMessage<ItemChangeEvent>(request).Items;
            if (items != null)
                OnItemsChanged(items.Select(i => i.Id).ToList());

            return true;
        }
Example #22
0
 public ObjectTcpMessage <T> SendAndReceive <T>(TcpMessage request) where T : class
 {
     return(new ObjectTcpMessage <T>(SendAndReceive(request)));
 }
Example #23
0
        private TcpMessage HandleUniqueItemQuery(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType(TcpRequestType.UniqueItemQuery))
                return null;

            if (!IsAuthenticated(host))
                throw AuthException.NotLoggedIn();

            var request = new ParamTcpMessage(message);

            var response = new ObjectTcpMessage<DbItem>(TcpRequestType.List);
            if (request.HasParam("id"))
            {
                var id = request.GetParamAsNullableInt("id");
                if (id != null)
                {
                    var item = _dataService.GetItem(id.Value);
                    response.Add(item);
                    return response;
                }
            }

            return TcpMessage.Error("Missing or badly formatted query parameters");
        }
Example #24
0
 public static bool Write(Stream stream, TcpMessage message)
 {
     return(Write(stream, message.ToString()));
 }
Example #25
0
 public static TcpMessage FromRaw(string rawContent)
 {
     var message = new TcpMessage();
     message.SetRaw(rawContent);
     return message;
 }
Example #26
0
        private TcpMessage HandleAESInitializationVectorExchangeRequest(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType("aesiv"))
                return null;

            var client = GetClient(host);
            client.AESHandler.GenerateInitializationVector();
            client.EncryptNextMessageSync = false;

            return new TcpMessage("aesiv") { Content = client.AESHandler.InitializationVectorAsString };
        }
Example #27
0
 public ParamTcpMessage(TcpMessage message)
     : base(message.RequestType)
 {
     SetByContent(message.Content);
 }
Example #28
0
        private TcpMessage HandleInsertRelation(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType(TcpRequestType.InsertRelation))
                return null;

            if (!IsAuthenticated(host))
                throw AuthException.NotLoggedIn();

            var request = new ObjectTcpMessage<DbRelation>(message);

            var response = new ObjectTcpMessage<DbRelation>(TcpRequestType.List);
            var relation = request.Item;
            if (relation != null)
            {
                _dataService.Insert(relation);
                response.Add(relation); // Send the item back to report assigned Id
            }

            return response;
        }
Example #29
0
 public static bool Write(Stream stream, TcpMessage message)
 {
     return Write(stream, message.ToString());
 }
Example #30
0
        private void HandleDataClientComm(object client)
        {
            var tcpClient = (System.Net.Sockets.TcpClient)client;

            var addressSplits = tcpClient.Client.RemoteEndPoint.ToString().Split(':');

            var host = new TcpConnectedHost
            {
                TcpClient = tcpClient,
                IPAddress = addressSplits[0]
            };

            if (!IsAllowed(host.IPAddress))
            {
                Debug.WriteLine("Client refused access to data channel. IP: " + host.IPAddress);
                tcpClient.Close();
                return;
            }

            Debug.WriteLine("Client connected to data channel. IP: " + host.IPAddress);

            var stream = OnPrepareStream(host.TcpClient.GetStream());

            _connectedDataClients.AddLast(host);

            while (true)
            {
                var rawRequest = TcpProtocolHelper.Read(stream);

                if (rawRequest == null)
                {
                    break;
                }

                rawRequest = PrepareIncommingMessage(host, rawRequest);

                Debug.WriteLine(DateTime.Now.ToLongTimeString() + " [R] " + rawRequest);

                TcpMessage response = null;

                var request = TcpMessage.FromRaw(rawRequest);

                foreach (var handler in _dataRequestHandlers)
                {
                    try
                    {
                        response = handler.Invoke(host, request);
                        if (response != null)
                        {
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        response = TcpMessage.Error(e.ToString());
                        break;
                    }
                }

                if (response == null)
                {
                    response = TcpMessage.Error("Could not handle request");
                }

                var responseMessage = response.ToString();

                Debug.WriteLine(DateTime.Now.ToLongTimeString() + " [S] " + responseMessage);

                responseMessage = PrepareOutgoingMessage(host, responseMessage);

                var success = TcpProtocolHelper.Write(stream, responseMessage);
                if (!success)
                {
                    break;
                }
            }

            Debug.WriteLine("Client disconnected from data channel. IP: " + host.IPAddress);
            tcpClient.Close();
        }
Example #31
0
 public ObjectTcpMessage(TcpMessage message)
     : this(message.RequestType)
 {
     SetByContent(message.Content);
 }
Example #32
0
        private TcpMessage HandleUniqueRelationQuery(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType(TcpRequestType.UniqueRelationQuery))
                return null;

            if (!IsAuthenticated(host))
                throw AuthException.NotLoggedIn();

            var request = new ParamTcpMessage(message);

            var response = new ObjectTcpMessage<DbRelation>(TcpRequestType.List);
            if (request.HasParam("from_id") && request.HasParam("identifier"))
            {
                var fromId = request.GetParamAsNullableInt("from_id");
                var identifier = request.GetParam("identifier");
                var relation = _dataService.GetRelation(fromId, identifier);
                response.Add(relation);
                return response;
            }

            return TcpMessage.Error("Missing or badly formatted query parameters");
        }
Example #33
0
 public void Enqueue(TcpMessage message)
 {
     DoOnQueues(q => q.Add(message));
 }
Example #34
0
 public TcpMessage SendAndReceive(TcpMessage request)
 {
     return(TcpMessage.FromRaw(SendAndReceive(request.ToString())));
 }
Example #35
0
        private TcpMessage HandleAESInitializationVectorExchangeRequest(TcpConnectedHost host, TcpMessage message)
        {
            if (!message.HasType("aesiv"))
            {
                return(null);
            }

            var client = GetClient(host);

            client.AESHandler.GenerateInitializationVector();
            client.EncryptNextMessageSync = false;

            return(new TcpMessage("aesiv")
            {
                Content = client.AESHandler.InitializationVectorAsString
            });
        }
Example #36
0
 public ParamTcpMessage(TcpMessage message)
     : base(message.RequestType)
 {
     SetByContent(message.Content);
 }