Beispiel #1
0
        private static void CommentList(Socket client, Connection connection, String data)
        {
            Photo          photo = connection.User.GetPhoto(data);
            CommandPackage response;
            ILog           log;

            if (photo != null)
            {
                response = new CommandPackage(HeaderConstants.Response, CommandConstants.CommentList);
                CommandProtocol.SendCommand(client, response);
                CommandProtocol.SendList(client, photo.CommentList(), CommandConstants.CommentList);

                log         = new Info();
                log.User    = connection.User.Name;
                log.Message = "Usuario solicita comentarios de la foto " + photo.Name;
            }
            else
            {
                response = new CommandPackage(HeaderConstants.Response, CommandConstants.Error);
                CommandProtocol.SendCommand(client, response);
                log         = new Warning();
                log.User    = connection.User.Name;
                log.Message = "Solicita comentarios de foto no valida";
            }
            Server.GetInstance().LogAction(log);
        }
Beispiel #2
0
        private static void LoginMainMenu(ref bool keepRunning, Socket socket)
        {
            Console.WriteLine(separador);
            Console.WriteLine("Bienvenido al menu principal, ingresa a tu cuenta o registrate \n 1-Login \n 2-Register \n 3-Exit");
            var input = Console.ReadLine();

            switch (input)
            {
            case "1":
                LoginMenu(socket);
                break;

            case "2":
                RegisterMenu(socket);
                break;

            case "3":
                CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.Exit);
                CommandProtocol.SendCommand(socket, package);
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
                keepRunning = false;
                break;

            default:
                Console.WriteLine("Opcion no valida");
                break;
            }
        }
Beispiel #3
0
        private static void Register(Socket client, String data, Connection connection)
        {
            //lock (registerLocker)
            //{
            var            message  = data.Split("%");
            string         username = message[0];
            string         password = message[1];
            CommandPackage response;
            ILog           log;

            try
            {
                connection.User = Server.GetInstance().RegisterUser(username, password);
                response        = new CommandPackage(HeaderConstants.Response, CommandConstants.Register, MessageConstants.SuccessfulRegister);
                log             = new Info();
                log.User        = username;
                log.Message     = "Usuario registrado correctamente";
            }
            catch (Exception ex)
            {
                response    = new CommandPackage(HeaderConstants.Response, CommandConstants.Register, MessageConstants.FailedRegister);
                log         = new Warning();
                log.User    = username;
                log.Message = "Registro no valido, nombre de usuario en uso";
            }
            Server.GetInstance().LogAction(log);
            CommandProtocol.SendCommand(client, response);
            // }
        }
Beispiel #4
0
        private static void Menu(ref bool keepRunning, Socket socket, GreeterClient client)
        {
            Console.WriteLine(separador);
            Console.WriteLine("Bienvenido al menu principal de administrador, ingresa la opcion que deseas realizar \n 1-ABM usuario \n 2-Ver logs \n 3-Lista de usuarios \n 4-Exit");
            var input = Console.ReadLine();

            switch (input)
            {
            case "1":
                ABMMenuAsync(client);
                break;

            case "2":
                LogMenu(socket);
                break;

            case "3":
                ListUsers(client);
                break;

            case "4":
                CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.Exit);
                CommandProtocol.SendCommand(socket, package);
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
                keepRunning = false;
                break;

            default:
                Console.WriteLine("Opcion no valida");
                break;
            }
        }
Beispiel #5
0
        private static void Login(Socket client, String data, Connection connection)
        {
            var            message  = data.Split("%");
            string         username = message[0];
            string         password = message[1];
            CommandPackage response;
            ILog           log;

            try
            {
                connection.User = Server.GetInstance().Login(username, password);
                response        = new CommandPackage(HeaderConstants.Response, CommandConstants.Login, MessageConstants.SuccessfulLogin);
                log             = new Info();
                log.User        = username;
                log.Message     = "Login exitoso";
            }
            catch (Exception ex)
            {
                response    = new CommandPackage(HeaderConstants.Response, CommandConstants.Login, MessageConstants.FailedLogin);
                log         = new Warning();
                log.User    = username;
                log.Message = "Login no valido";
            }
            Server.GetInstance().LogAction(log);
            CommandProtocol.SendCommand(client, response);
        }
Beispiel #6
0
        private static void PictureList(Socket client, Connection connection, String data)
        {
            User user;

            if (data == "")
            {
                user = connection.User;
            }
            else
            {
                user = Server.GetInstance().GetUser(data);
            }
            CommandPackage response;
            ILog           log;

            if (user != null)
            {
                response = new CommandPackage(HeaderConstants.Response, CommandConstants.PictureList);
                CommandProtocol.SendCommand(client, response);
                CommandProtocol.SendList(client, user.PictureList(), CommandConstants.PictureList);

                log         = new Info();
                log.User    = connection.User.Name;
                log.Message = "Usuario solicita fotos de " + user.Name;
            }
            else
            {
                response = new CommandPackage(HeaderConstants.Response, CommandConstants.Error);
                CommandProtocol.SendCommand(client, response);
                log         = new Warning();
                log.User    = connection.User.Name;
                log.Message = "Solicita fotos de usuario no valido";
            }
            Server.GetInstance().LogAction(log);
        }
Beispiel #7
0
        private static void LogMenu(Socket socket)
        {
            Console.WriteLine(separador);
            Console.WriteLine("Ingresa que tipo de logs deseas ver \n 1-Todos los logs \n 2-Info \n 3-Warning \n 4-Error");
            var            input  = Console.ReadLine();
            List <string>  result = new List <string>();
            CommandPackage request;
            string         ammount;

            switch (input)
            {
            case "1":
                Console.WriteLine("Ingrese la cantidad de logs que desea ver");
                ammount = Console.ReadLine();
                request = new CommandPackage(HeaderConstants.Request, CommandConstants.Logs, ammount);
                CommandProtocol.SendCommand(socket, request);
                result = CommandProtocol.RecieveList(socket);
                break;

            case "2":
                Console.WriteLine("Ingrese la cantidad de logs que desea ver");
                ammount = Console.ReadLine();
                request = new CommandPackage(HeaderConstants.Request, CommandConstants.LogInfo, ammount);
                CommandProtocol.SendCommand(socket, request);
                result = CommandProtocol.RecieveList(socket);
                break;

            case "3":
                Console.WriteLine("Ingrese la cantidad de logs que desea ver");
                ammount = Console.ReadLine();
                request = new CommandPackage(HeaderConstants.Request, CommandConstants.LogWarning, ammount);
                CommandProtocol.SendCommand(socket, request);
                result = CommandProtocol.RecieveList(socket);
                break;

            case "4":
                Console.WriteLine("Ingrese la cantidad de logs que desea ver");
                ammount = Console.ReadLine();
                request = new CommandPackage(HeaderConstants.Request, CommandConstants.LogError, ammount);
                CommandProtocol.SendCommand(socket, request);
                result = CommandProtocol.RecieveList(socket);
                break;

            default:
                Console.WriteLine("Opcion no valida");
                break;
            }
            if (result.Count > 0)
            {
                foreach (string log in result)
                {
                    Console.WriteLine(log);
                }
            }
        }
Beispiel #8
0
        private static void UserList(Socket client, Connection connection)
        {
            List <string> userList = Server.GetInstance().UserListStrings();

            CommandProtocol.SendList(client, userList, CommandConstants.UserList);
            ILog log = new Info();

            log.User    = connection.User.Name;
            log.Message = "Usuario solicita lista de usuarios";
            Server.GetInstance().LogAction(log);
        }
Beispiel #9
0
        private static void ListUsers(Socket socket)
        {
            CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.UserList);

            CommandProtocol.SendCommand(socket, package);
            List <string> list = CommandProtocol.RecieveList(socket);

            foreach (string user in list)
            {
                Console.WriteLine(user);
            }
        }
Beispiel #10
0
        private static void RequestLoggedUser(Socket client, Connection connection)
        {
            CommandPackage response;

            if (connection.User == null)
            {
                response = new CommandPackage(HeaderConstants.Response, CommandConstants.RequestLoggedUser, MessageConstants.NoUserFound);
            }
            else
            {
                response = new CommandPackage(HeaderConstants.Response, CommandConstants.RequestLoggedUser, connection.User.Name);
            }
            CommandProtocol.SendCommand(client, response);
        }
Beispiel #11
0
        private void AdminWarning(Socket socket, CommandPackage package)
        {
            List <ILog> warnings = new List <ILog>();

            foreach (ILog log in logs)
            {
                if (log is Warning)
                {
                    warnings.Add(log);
                }
            }
            List <string> list = ReturnLastN(warnings, int.Parse(package.Data));

            CommandProtocol.SendList(socket, list, package.Command);
        }
Beispiel #12
0
        private void AdminError(Socket socket, CommandPackage package)
        {
            List <ILog> errors = new List <ILog>();

            foreach (ILog log in logs)
            {
                if (log is Error)
                {
                    errors.Add(log);
                }
            }
            List <string> list = ReturnLastN(errors, int.Parse(package.Data));

            CommandProtocol.SendList(socket, list, package.Command);
        }
Beispiel #13
0
        private static void MainMenu(ref bool keepRunning, Socket socket)
        {
            CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.RequestLoggedUser);

            CommandProtocol.SendCommand(socket, package);
            CommandPackage response = CommandProtocol.RecieveCommand(socket);

            if (response.Data == MessageConstants.NoUserFound)
            {
                LoginMainMenu(ref keepRunning, socket);
            }
            else
            {
                LoggedMainMenu(ref keepRunning, socket, response.Data);
            }
        }
Beispiel #14
0
        private static void RegisterMenu(Socket socket)
        {
            Console.WriteLine(separador);
            Console.WriteLine("Ingrese nombre de usuario");
            bool   validInput = false;
            string username   = "";

            while (!validInput)
            {
                username = Console.ReadLine();
                if (username.Contains("%") || username.Trim().Length == 0)
                {
                    Console.WriteLine("Su nombre de usuario no puede ser vacio ni contener %");
                }
                else
                {
                    validInput = true;
                }
            }
            validInput = false;
            Console.WriteLine("Ingrese contraseña");
            string password = "";

            while (!validInput)
            {
                password = Console.ReadLine();
                if (password.Contains("%") || password.Trim().Length == 0)
                {
                    Console.WriteLine("Su contraseña no puede ser vacia ni contener %");
                }
                else
                {
                    validInput = true;
                }
            }
            CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.Register, username + "%" + password);

            CommandProtocol.SendCommand(socket, package);
            CommandPackage response = CommandProtocol.RecieveCommand(socket);

            if (response.Data == MessageConstants.FailedRegister)
            {
                Console.WriteLine("Ese nombre de usuario ya esta en uso");
            }
        }
Beispiel #15
0
        private static void LoginMenu(Socket socket)
        {
            Console.WriteLine(separador);
            Console.WriteLine("Ingrese nombre de usuario");
            var username = Console.ReadLine();

            Console.WriteLine("Ingrese contraseña");
            var            password = Console.ReadLine();
            CommandPackage package  = new CommandPackage(HeaderConstants.Request, CommandConstants.Login, username + "%" + password);

            CommandProtocol.SendCommand(socket, package);
            CommandPackage response = CommandProtocol.RecieveCommand(socket);

            if (response.Data == MessageConstants.FailedLogin)
            {
                Console.WriteLine("Usuario y/o contraseña incorrectos");
            }
        }
Beispiel #16
0
        private static void ListPhotos(Socket socket)
        {
            Console.WriteLine("Inserte el usuario del cual desea ver las fotos, si desea ver las suyas puede dejar en blanco");
            var            user    = Console.ReadLine();
            CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.PictureList, user);

            CommandProtocol.SendCommand(socket, package);

            CommandPackage response = CommandProtocol.RecieveCommand(socket);

            if (response.Command == CommandConstants.PictureList)
            {
                List <string> pictures = CommandProtocol.RecieveList(socket);

                if (pictures.Count != 0)
                {
                    if (user == "")
                    {
                        Console.WriteLine("Sus fotos son:");
                    }
                    else
                    {
                        Console.WriteLine("Las fotos de " + user + " son:");
                    }

                    foreach (string picture in pictures)
                    {
                        Console.WriteLine(picture);
                    }
                }
                else
                {
                    if (user == "")
                    {
                        user = "******";
                    }
                    Console.WriteLine(user + " no tiene fotos actualmente");
                }
            }
            else
            {
                Console.WriteLine("Usuario invalido");
            }
        }
Beispiel #17
0
        private static void AddComment(Socket socket)
        {
            Console.WriteLine("Indique el usuario al cual pertenece la foto que desea comentar");
            var user = Console.ReadLine();

            Console.WriteLine("Indique la foto que desea comentar");
            var photo = Console.ReadLine();

            Console.WriteLine("Ingrese el comentario");
            var comment = Console.ReadLine();
            var data    = user + "%" + photo + "%" + comment;

            CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.NewComment, data);

            CommandProtocol.SendCommand(socket, package);

            CommandPackage response = CommandProtocol.RecieveCommand(socket);

            Console.WriteLine(response.Data);
        }
Beispiel #18
0
        private static void LoggedMainMenu(ref bool keepRunning, Socket socket, String username)
        {
            Console.WriteLine(separador);
            Console.WriteLine("Bienvenido {0}!", username);
            Console.WriteLine("\n 1-Subir Foto \n 2-Listado usuarios sistema \n 3-Listado fotos usuario \n 4-Ver comentarios de mis fotos \n 5-Agregar comentario \n 6-Salir");
            var input = Console.ReadLine();

            switch (input)
            {
            case "1":
                UploadPicture(socket);
                break;

            case "2":
                ListUsers(socket);
                break;

            case "3":
                ListPhotos(socket);
                break;

            case "4":
                ListComments(socket);
                break;

            case "5":
                AddComment(socket);
                break;

            case "6":
                CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.Logout);
                CommandProtocol.SendCommand(socket, package);
                break;

            default:
                Console.WriteLine("Opcion no valida");
                break;
            }
        }
Beispiel #19
0
        private static void UploadPicture(Socket socket)
        {
            Console.WriteLine("Por favor inserte el path de la imagen que desea subir");
            string path = Console.ReadLine();

            while (path.Equals(string.Empty) || !FileHandler.FileExists(path))
            {
                Console.WriteLine("path invalido");
                path = Console.ReadLine();
            }

            Console.WriteLine("Ingrese el nombre que desea darle a la foto");
            string         name    = Console.ReadLine();
            CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.SendPicture, name);

            CommandProtocol.SendCommand(socket, package);

            FileProtocol fileProtocol = new FileProtocol(socket);

            fileProtocol.SendFile(path);
            Console.WriteLine("Su foto fue subida con exito");
        }
Beispiel #20
0
        private static void AddComment(Socket client, Connection connection, String data)
        {
            var            dataStruct = data.Split('%');
            User           user       = Server.GetInstance().GetUser(dataStruct[0]);
            CommandPackage response;
            ILog           log;

            if (user != null)
            {
                Photo photo = user.GetPhoto(dataStruct[1]);
                if (photo != null)
                {
                    Comment comment = new Comment();
                    comment.User = user;
                    comment.Text = dataStruct[2];
                    photo.Comments.Add(comment);
                    response    = new CommandPackage(HeaderConstants.Response, CommandConstants.NewComment, "Comentario ingresado con exito");
                    log         = new Info();
                    log.User    = connection.User.Name;
                    log.Message = "Usuario comenta la foto " + photo.Name + " del usuario " + user.Name;
                }
                else
                {
                    response    = new CommandPackage(HeaderConstants.Response, CommandConstants.Error, "El usuario no contiene una foto con ese nombre");
                    log         = new Warning();
                    log.User    = connection.User.Name;
                    log.Message = "Intenta comentar una foto inexistente del usuario " + user.Name;
                }
            }
            else
            {
                response    = new CommandPackage(HeaderConstants.Response, CommandConstants.Error, "El usuario ingresado no es valido");
                log         = new Warning();
                log.User    = connection.User.Name;
                log.Message = "Intenta comentar una foto de usuario no existente";
            }
            CommandProtocol.SendCommand(client, response);
            Server.GetInstance().LogAction(log);
        }
Beispiel #21
0
        private static void ListComments(Socket socket)
        {
            Console.WriteLine("Indique de que foto desea ver los comentarios");
            var            photo   = Console.ReadLine();
            CommandPackage package = new CommandPackage(HeaderConstants.Request, CommandConstants.CommentList, photo);

            CommandProtocol.SendCommand(socket, package);

            CommandPackage response = CommandProtocol.RecieveCommand(socket);

            if (response.Command == CommandConstants.CommentList)
            {
                Console.WriteLine("Los comentarios son:");
                List <string> comments = CommandProtocol.RecieveList(socket);
                foreach (string comment in comments)
                {
                    Console.WriteLine(comment);
                }
            }
            else
            {
                Console.WriteLine("Nombre de foto invalido");
            }
        }
Beispiel #22
0
        private static void HandleAdmin(Socket socket)
        {
            bool keepRunning = true;

            while (keepRunning)
            {
                try
                {
                    CommandPackage package = CommandProtocol.RecieveCommand(socket);
                    switch (package.Command)
                    {
                    case CommandConstants.Logs:
                        LogServer.GetInstance().AdminLog(socket, package);
                        break;

                    case CommandConstants.LogInfo:
                        LogServer.GetInstance().AdminInfo(socket, package);
                        break;

                    case CommandConstants.LogWarning:
                        LogServer.GetInstance().AdminWarning(socket, package);
                        break;

                    case CommandConstants.LogError:
                        LogServer.GetInstance().AdminError(socket, package);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    keepRunning = false;
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                }
            }
        }
Beispiel #23
0
        public async Task <byte[]> ProcessRequestAsync(byte[] rawRequest, string clientInformation)
        {
            if (rawRequest == null || rawRequest.Length == 0)
            {
                return(null);
            }

            var tlsEnvelope = new TLSEnvelope(rawRequest);
            var request     = this.tlsServerRatchet.TLSServerDecryptRequest(tlsEnvelope);

            if (request == null)
            {
                this.logger.LogWarning($"TLSServerRequestHandler: Unknown DynamicPublicKey {tlsEnvelope.DynamicPublicKeyId}, sending {CommandId.LostDynamicKey_Response}.");
                // request == null means we lost the dynamic private key to to the public key the client used.
                // We don't know who the client is, because TLS could not decrypt the message at all.
                // We now need to tell the client it needs to reset its key schedule, i.e. start over
                // using my static public key.
                // We must use our static private key to encrypt this message, so that the client knows the server is talking.
                // We then use the dynamic public key we just received, to calculate a new shared secret that only the unknown
                // client can reproduce for decryption of this message.
                byte[] lostDynamicKeyResponseCommand = this.commandProcessor.ExecuteLostDynamicKey();
                byte[] lostDynamicKeyResponse        = this.tlsServerRatchet.TLSServerEncryptRequestAnonymous(lostDynamicKeyResponseCommand, tlsEnvelope.DynamicPublicKey, tlsEnvelope.DynamicPublicKeyId).Serialize();
                return(lostDynamicKeyResponse);
            }

            Command command = request.ParseCommand();

            if (!command.CommandId.IsCommandDefined())
            {
                return(null);
            }

            byte[] response;
            if (CommandProtocol.IsAuthenticationRequired(command.CommandId))
            {
                if (!request.IsAuthenticated)
                {
                    this.logger.LogWarning($"ServerRequestHandler: Command {command.CommandId} from {request.UserId} requires Auth, which failed. Sending {CommandId.NoSuchUser_Response}");
                    // We may be here, when the server has lost the identity (and client public key for the calling user id), or if the
                    // user id is locked, revoked etc.
                    byte[] noSuchUserResponseCommand = this.commandProcessor.ExecuteNoSuchUser();
                    byte[] noSuchUserResponse        = this.tlsServerRatchet.TLSServerEncryptRequestAnonymous(noSuchUserResponseCommand, tlsEnvelope.DynamicPublicKey, tlsEnvelope.DynamicPublicKeyId).Serialize();
                    return(noSuchUserResponse);
                }

                response = await this.commandProcessor.ExecuteAuthenticatedRequestAsync(command);
            }
            else
            {
                response = await this.commandProcessor.ExecutePublishIdentityAsync(command, this.tlsServerRatchet.RefreshTLSUser);

                // when PublishIdentity has returned successfully, we can save the DynamicPublicKey we did not save in TLSDecrpt, because we wanted more logic to run before this
                // Specifically, the IdentityController has called RefreshTLSUser by now, creating the place where this key can be stored.
                if (response != null)
                {
                    this.tlsServerRatchet.SaveIncomingDynamicPublicKey(request.UserId, tlsEnvelope.DynamicPublicKey, tlsEnvelope.DynamicPublicKeyId);
                }
            }
            return(response == null ?
                   null :
                   this.tlsServerRatchet.TLSServerEncryptRequest(response, request.UserId).Serialize());
        }
Beispiel #24
0
        public static void HandleClient(Socket client, Connection connection)
        {
            var id        = Interlocked.Add(ref _clientNumber, 1);
            var connected = true;

            Console.WriteLine("Conectado el cliente " + id);
            while (connected)
            {
                try
                {
                    CommandPackage package = CommandProtocol.RecieveCommand(client);
                    switch (package.Command)
                    {
                    case CommandConstants.Exit:
                        connected = false;
                        Console.WriteLine("El cliente " + id + " cerró la conexión: ");
                        break;

                    case CommandConstants.RequestLoggedUser:
                        RequestLoggedUser(client, connection);
                        break;

                    case CommandConstants.Login:
                        Login(client, package.Data, connection);
                        break;

                    case CommandConstants.Register:
                        Register(client, package.Data, connection);
                        break;

                    case CommandConstants.UserList:
                        UserList(client, connection);
                        break;

                    case CommandConstants.SendPicture:
                        RecievePicture(client, connection, package.Data);
                        break;

                    case CommandConstants.PictureList:
                        PictureList(client, connection, package.Data);
                        break;

                    case CommandConstants.CommentList:
                        CommentList(client, connection, package.Data);
                        break;

                    case CommandConstants.NewComment:
                        AddComment(client, connection, package.Data);
                        break;

                    case CommandConstants.Logout:
                        Logout(connection);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("El cliente " + id + " cerró la conexión: ");
                    connected = false;
                    if (Server.keepRunning)
                    {
                        client.Shutdown(SocketShutdown.Both);
                        client.Close();
                    }
                    else
                    {
                        Console.WriteLine("server is shuting down");
                    }
                }
            }
            Server.GetInstance().connections.Remove(connection);
        }
Beispiel #25
0
        private void AdminLog(Socket socket, CommandPackage package)
        {
            List <string> list = ReturnLastN(logs, int.Parse(package.Data));

            CommandProtocol.SendList(socket, list, package.Command);
        }