private static byte[] insertCommand(IEnumerable <byte> data, ServerCommands command) { var list = data.ToList(); list.Insert(0, (byte)command); return(list.ToArray()); }
public static void ReadConsole() { var Commands = new Commands(); var ServerCommands = new ServerCommands(); while (true) { Console.Write("ScarDesktop@" + MainWindow.CurrentUser.Name + "> "); string[] input = Console.ReadLine().Split(' '); if (input.Length > 0) { if (input[0] == "$") { if (ServerCommands.GetType().GetMethod(input[0]) != null) { ServerCommands.GetType().GetMethod(input[0].Substring(1).ToLower()).Invoke(ServerCommands, new[] { input.Skip(1) }); } else { Console.WriteLine("Invalid command!"); } } else if (Commands.GetType().GetMethod(input[0]) != null) { Commands.GetType().GetMethod(input[0].ToLower()).Invoke(Commands, new[] { input }); } else { Console.WriteLine("Invalid command!"); } } } }
private async Task ProccessMessage() { TcpMessage requestMessage = await MessageTransport.ReadAsync(this._connectionInfo); if (requestMessage == null) { throw new Exception("Сообщение имеет некорректный формат"); } Command = requestMessage.Header.Command; bool isNeedExeLog = ServerCommands.IsNeedExeLog(Command); Stopwatch stopwatch = null; if (isNeedExeLog) { stopwatch = new Stopwatch(); stopwatch.Start(); } using (CommandContext commandContext = new CommandContext(this, requestMessage, _bufferManager)) { this._commandContext = commandContext; await CommandDispatcher.Instance.ExecuteAsync(commandContext); this._commandContext = null; } if (isNeedExeLog) { stopwatch.Stop(); ServerLog.AddFBLog(ExecuteFolder, string.Format("| {0,8} | {1,8} | {2}", Command, stopwatch.ElapsedMilliseconds, ClientAddress)); } }
public void GetFriends() { var response = ServerCommands.GetFriendsCommand(ref connection); if (response.error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(response.error)); } List <Friend> dirtyFriends = JsonConvert.DeserializeObject <List <Friend> >(response.friendsJSON); foreach (Friend dirtyFriend in dirtyFriends) { bool newFriend = true; for (int i = 0; i < friends.Count; i++) { if (dirtyFriend.username == friends[i].Name) { newFriend = false; friends[i].Active = Convert.ToBoolean(dirtyFriend.active); } } if (newFriend) { friends.Add(new FriendItem(dirtyFriend.username, Convert.ToBoolean(dirtyFriend.active))); } } }
public bool GetNotifications() { var response = ServerCommands.GetNotificationsCommand(ref connection); if (response.error == (int)ErrorCodes.NO_NOTIFICATIONS) { return(false); } if (response.error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(response.error)); } List <Notification> notificationsList = JsonConvert.DeserializeObject <List <Notification> >(response.newMessagesInfoJSON); foreach (Notification notification in notificationsList) { for (int i = 0; i < friends.Count; i++) { if (notification.username == friends[i].Name) { friends[i].NotificationsAmount = notification.numberOfMessages; } } } return(true); }
/// <summary> /// Ticks the server, include the network, /// and all worlds (and all chunks within those [and all entities within those]). /// </summary> /// <param name="delta">The time between the last tick and this one</param> public static void Tick(double delta) { Delta = delta; GlobalTickTime += delta; try { NetworkBase.Tick(); } catch (Exception ex) { SysConsole.Output(OutputType.ERROR, "Error / networktick: " + ex.ToString()); } try { secondTracker += Delta; if (secondTracker >= 1.0) { secondTracker -= 1.0; OncePerSecondTick(); } } catch (Exception ex) { SysConsole.Output(OutputType.ERROR, "Error / oncepersecondtick: " + ex.ToString()); } try { ServerCommands.Tick(); ConsoleHandler.CheckInput(); } catch (Exception ex) { SysConsole.Output(OutputType.ERROR, "Error / command tick: " + ex.ToString()); } try { for (int i = 0; i < WaitingPlayers.Count; i++) { if (GlobalTickTime - WaitingPlayers[i].JoinTime > 10) { WaitingPlayers.RemoveAt(i); i--; } } for (int i = 0; i < Players.Count; i++) { // TODO: CVar if (GlobalTickTime - Players[i].LastPing > 60 || GlobalTickTime - Players[i].LastSecondaryPing > 60) { DespawnPlayer(Players[i]); i--; } } } catch (Exception ex) { SysConsole.Output(OutputType.ERROR, "Error / general tick: " + ex.ToString()); } }
private void Tile_Click(object sender, RoutedEventArgs e) { if (Window == null) { Window = new CommandsGeneratorTemplate(this); Window.win = (Application.Current.MainWindow as IMainWindowCommands).AddWindow(Icon, Window, "命令生成器", this); Window.win.WindowClosed += Win_WindowClosed; } object content = null; string title = (sender as Tile).Title; switch (title) { case "基础命令": content = new BasicCommands(Window); break; case "服务器命令": content = new ServerCommands(Window); break; case "实体命令": content = new EntityCommands(Window); break; case "玩家命令": content = new PlayerCommands(Window); break; case "Json书": content = new Book(Window); break; case "告示牌": content = new Sign(Window); break; case "消息文本": content = new Tellraw(Window); break; case "显示标题": content = new Title(Window); break; case "记分板目标": content = new ScoreboardObjective(Window); break; case "记分板玩家": content = new ScoreboardPlayers(Window); break; case "记分板队伍": content = new ScoreboardTeam(Window); break; case "物品NBT": content = new ItemNBT(Window); break; case "实体NBT": content = new EntityNBT(Window); break; case "物品与生成": content = new GetElement(); break; case "检测与执行": content = new ExecuteAndDetect(); break; case "方块NBT/放置填充方块": content = new SetBlocks(Window); break; case "村民交易": content = new VillagerTrade(Window); break; case "刷怪笼": content = new MobSpawner(Window); break; case "烟花": content = new Firework(Window); break; case "旗帜/盾牌": content = new Banners(Window); break; case "药水/药水箭": content = new Potion(Window); break; case "盔甲架": content = new ArmorStand(Window); break; } Window.AddPage(title, content); }
private string GetRankingXML() { ServerCommands.GetRankingCommandResponse response = ServerCommands.GetRankingCommand(ref connection, user.SessionID); if (response.error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(response.error)); } return(response.rankingXML); }
public void SendPublicDHKey(string invitationID, string publicDHKey, string privateEncryptedDHKey, string privateEncryptedDHKeyIV) { int error = ServerCommands.SendPublicDHKeyCommand(ref connection, invitationID, publicDHKey, privateEncryptedDHKey, privateEncryptedDHKeyIV); if (error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(error)); } }
public void DeclineFriendInvitation(string invitationID) { var error = ServerCommands.DeclineFriendInvitationCommand(ref connection, invitationID); if (error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(error)); } }
public void SendMessage(string friendUsername, string messageJSON) { int error = ServerCommands.SendMessageCommand(ref connection, conversations[friendUsername].ConversationID, messageJSON); if (error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(error)); } }
public void Disconnect() { int error = ServerCommands.DisconnectCommand(ref connection); if (error != (int)ErrorCodes.NO_ERROR && error != (int)ErrorCodes.NOT_LOGGED_IN) { throw new Exception(GetErrorCodeName(error)); } }
public void ActivateConversation(string friendUsername) { int error = ServerCommands.ActivateConversationCommand(ref connection, conversations[friendUsername].ConversationID); if (error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(error)); } }
public Opponent GetFoundMatch() { ServerCommands.GetFoundMatchResponse response = ServerCommands.GetFoundMatchCommand_responseOnly(ref connection); if (response.error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(response.error)); } return(new Opponent(response.opponentName, response.opponentRank)); }
public void LogoutUser() { int error = ServerCommands.LogoutCommand(ref connection); if (error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(error)); } }
public void SendEncryptedConversationKey(string conversationID, byte[] encryptedConversationKey) { string encryptedConversationKeyHexString = Security.ByteArrayToHexString(encryptedConversationKey); int error = ServerCommands.SendEncryptedConversationKeyCommand(ref connection, conversationID, encryptedConversationKeyHexString); if (error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(error)); } }
/// <summary> /// Пересылка сообщения клиенту /// </summary> /// <param name="command">команда которую хотим переслать клиенту</param> /// <param name="message">сообщение прилагаемое к команде</param> /// <param name="stream">поток в который будем отправлять</param> /// <param name="consoled">Нужно ли экранировать сообщение в консоль сервера. По умолчанию - нужно</param> private void SendMessage(Commands command, string message, NetworkStream stream, bool consoled = true) { message = ServerCommands.CommandToText(command) + message; byte[] data = Encoding.Unicode.GetBytes(message); stream.Write(data, 0, data.Length); if (consoled) { Console.WriteLine("Server sent: {0}", message.Trim()); } }
public (string conversationID, byte[] conversationIV) AcceptFriendInvitation(string invitationID, string PKB) { var response = ServerCommands.AcceptFriendInvitationCommand(ref connection, invitationID, PKB); if (response.error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(response.error)); } return(response.conversationID, Security.HexStringToByteArray(response.conversationIV)); }
public bool LogoutUser() { int error = ServerCommands.LogoutCommand(ref connection, user.SessionID); if (error == (int)ErrorCodes.NO_ERROR) { return(true); } else { throw new Exception(GetErrorCodeName(error)); } }
public bool RegisterUser(byte[] userIV, byte[] userKeyHash) { int error = ServerCommands.RegisterUser(ref connection, username, pass2, Security.ByteArrayToHexString(userIV), Security.ByteArrayToHexString(userKeyHash)); if (error == (int)ErrorCodes.NO_ERROR) { return(true); } else { throw new Exception(GetErrorCodeName(error)); } }
public bool RegisterUser(string username, string pass) { int error = ServerCommands.RegisterUser(ref connection, username, pass); if (error == (int)ErrorCodes.NO_ERROR) { return(true); } else { throw new Exception(GetErrorCodeName(error)); } }
public List <ExtendedInvitation> GetAcceptedInvitations() { var response = ServerCommands.GetAcceptedInvitationsCommand(ref connection); if (response.error == (int)ErrorCodes.NOTHING_TO_SEND) { return(null); } if (response.error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(response.error)); } return(JsonConvert.DeserializeObject <List <ExtendedInvitation> >(response.ExtendedInvitationJSON)); }
public bool GetInvitations() { var response = ServerCommands.GetInvitationsCommand(ref connection); if (response.error == (int)ErrorCodes.NOTHING_TO_SEND) { return(false); } if (response.error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(response.error)); } receivedInvitations = JsonConvert.DeserializeObject <List <Invitation> >(response.invitationsJSON); return(true); }
public User LoginUser(string username, string password) { ServerCommands.LoginCommandResponse response = ServerCommands.LoginCommand(ref connection, username, password); if (response.error == (int)ErrorCodes.NO_ERROR) { return(new User(response.sessionID, username, response.elo)); } else if (response.error == (int)ErrorCodes.USER_NOT_FOUND || response.error == (int)ErrorCodes.INCORRECT_PASSWORD) { return(null); } else { throw new Exception(GetErrorCodeName(response.error)); } }
public (byte[] userIV, byte[] userKeyHash) LoginUser() { (int error, string userIV, string userKeyHash) = ServerCommands.LoginCommand(ref connection, username, pass); if (error == (int)ErrorCodes.NO_ERROR) { return(Security.HexStringToByteArray(userIV), Security.HexStringToByteArray(userKeyHash)); } else if (error == (int)ErrorCodes.USER_NOT_FOUND || error == (int)ErrorCodes.INCORRECT_PASSWORD) { return(null, null); } else { throw new Exception(GetErrorCodeName(error)); } }
public string ProcessRequest(string reqest) { string user = TryGetUser(reqest); if (!String.IsNullOrEmpty(user)) { UserInstance userInstance; m_connectedUsers.TryGetValue(user, out userInstance); string decryptedRequest = userInstance.cryptoManager.DecryptWithSessionB64(reqest); ServerCommands command = ParseCommand(decryptedRequest); switch (command) { case ServerCommands.ClientUpdate: return(userInstance.cryptoManager.EncryptWithSessionB64(PackMessages(user))); case ServerCommands.ClientRegister: return(userInstance.cryptoManager.EncryptWithSessionB64(RegisterUser(decryptedRequest, user))); case ServerCommands.ClientAuth: return(userInstance.cryptoManager.EncryptWithSessionB64(AuthUser(decryptedRequest, user))); case ServerCommands.RecieveMessage: return(userInstance.cryptoManager.EncryptWithSessionB64(RetranslateMessage(decryptedRequest) ? ServerSpecificStrings.MesageOk : ServerSpecificStrings.MesageNotOnline)); case ServerCommands.AddGroupChat: return(userInstance.cryptoManager.EncryptWithSessionB64(AddGroupChat(decryptedRequest) ? ServerSpecificStrings.MesageOk : ServerSpecificStrings.MesageNotOnline)); case ServerCommands.OkCheck: return(userInstance.cryptoManager.EncryptWithSessionB64(ServerSpecificStrings.MesageOk)); default: return(""); } } else { // UserId is IV string newUser = TryAddUser(reqest); if (!String.IsNullOrEmpty(newUser)) { UserInstance userInstance; m_connectedUsers.TryGetValue(newUser, out userInstance); return(userInstance.cryptoManager.EncryptWithSessionB64(ServerSpecificStrings.MesageOk)); } } return(""); }
public bool CheckUserExist(string username) { int error = ServerCommands.CheckUsernameExistCommand(ref connection, username); if (error == (int)ErrorCodes.NO_ERROR) { return(false); } else if (error == (int)ErrorCodes.USER_ALREADY_EXISTS) { return(true); } else { throw new Exception(GetErrorCodeName(error)); } }
public (InvitationStatus invitationStatus, string g, string p, string invitationID) SendInvitation(string username) { var response = ServerCommands.SendInvitationCommand(ref connection, username); if (response.error == (int)ErrorCodes.SELF_INVITE_ERROR) { return(InvitationStatus.SELF_INVITATION, "", "", ""); } if (response.error == (int)ErrorCodes.INVITATION_ALREADY_EXIST) { return(InvitationStatus.INVITATION_ALREADY_EXIST, "", "", ""); } if (response.error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(response.error)); } return(InvitationStatus.INVITATION_SENT, response.g, response.p, response.invitationID); }
public bool GetMessages(string friendUsername) { var response = ServerCommands.GetNewMessagesCommand(ref connection); if (response.error == (int)ErrorCodes.NO_MESSAGES) { return(false); } if (response.error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(response.error)); } List <Message> dirtyMessages = JsonConvert.DeserializeObject <List <Message> >(response.newMessegesJSON); byte[] conversationKey = conversations[friendUsername].ConversationKey; conversations[friendUsername].Messages.AddRange(DecryptMessages(dirtyMessages, conversationKey)); return(true); }
public void GetConversation(string friendUsername) { var response = ServerCommands.GetConversationCommand(ref connection, friendUsername); if (response.error != (int)ErrorCodes.NO_ERROR) { throw new Exception(GetErrorCodeName(response.error)); } byte[] encryptedConversationKey = Security.HexStringToByteArray(response.conversationKey); byte[] conversationIV = Security.HexStringToByteArray(response.conversationIV); byte[] conversationKey = Security.AESDecrypt(encryptedConversationKey, userKey, conversationIV); List <Message> dirtyMessages = new List <Message>(); if (response.messagesJSON != null && response.messagesJSON != "" && response.messagesJSON != "[{}]") { dirtyMessages = JsonConvert.DeserializeObject <List <Message> >(response.messagesJSON); } conversations[friendUsername] = new Conversation(response.conversationID, conversationKey, conversationIV, DecryptMessages(dirtyMessages, conversationKey)); }
private void WorkWith(ConnectionInfo connection, ServerCommands command, string request) { string[] requests = request.Split(' '); Console.WriteLine("COMMAND : " + command); byte[] response = null; switch (command) { case ServerCommands.Login: if (!IsLoginSuccessful(requests[1], requests[2], out connection.UserID, out response)) { SendBySocket(connection, response); } else { if (connection.PreviousID > 0) SqlRequests.ChangeUserStatus(UserStatuses.Offline, connection.PreviousID); ChangeUserStatus(UserStatuses.Online, connection); SendBySocket(connection, response); connection.PreviousID = connection.UserID; } break; case ServerCommands.CheckLogin: if (IsSuitable(requests[1], out response)) SqlRequests.AddUser(requests[1], requests[2], requests[3], requests[4]); SendBySocket(connection, response); break; case ServerCommands.GetUsersByPattern: GetUsersByPattern(requests[1], out response); SendBySocket(connection, response); Console.WriteLine("Sent list of users for {0}", connection.socket.RemoteEndPoint.ToString()); break; case ServerCommands.ChangeUserStatus: Console.WriteLine("Changed status for {0}", connection.socket.RemoteEndPoint.ToString()); ChangeUserStatus((UserStatuses)int.Parse(requests[1]), connection); break; case ServerCommands.FriendRequest: SetFriendRequest(connection.UserID, int.Parse(requests[1])); Console.WriteLine("Add friend request from {0}", connection.socket.RemoteEndPoint.ToString()); break; case ServerCommands.RequestForSystemMessages: GetMessages(connection.UserID, (int)MessageType.System, (int)MessageState.Sent, out response); Console.WriteLine("Sending system messages to {0}", connection.socket.RemoteEndPoint.ToString()); SendBySocket(connection, response); break; case ServerCommands.ReadMessages: SqlRequests.SetStateForMessages(requests[1], (int)MessageState.Received); Console.WriteLine("Setting state to RECEIVED to messages"); break; case ServerCommands.AcceptedFriendsRequests: List<int> IDs; ServerHelper.WorkWithAcceptedFriendRequests(connection.UserID, requests[1], out IDs); SendNotificationToUsers(IDs, connection.UserID); Console.WriteLine("Added new friendship and sent notifications"); break; case ServerCommands.RequestForFriendsList: GetFriendsList(connection.UserID, out response); SendBySocket(connection, response); Console.WriteLine("Sending friend's list to {0}", connection.socket.RemoteEndPoint.ToString()); break; case ServerCommands.Message: Console.WriteLine("Sent message from {0}", connection.socket.RemoteEndPoint.ToString()); SendMessage(connection.UserID, int.Parse(requests[1]), Concatinations(request, 2)); break; case ServerCommands.RequestForOfflineMessages: GetOfflineMessagesAndSend(connection.UserID); break; case ServerCommands.DeleteMessages: SqlRequests.DeleteMessages(requests[1]); Console.WriteLine("Deleted messages for {0}", connection.socket.RemoteEndPoint.ToString()); break; case ServerCommands.GetHistory: SendHistory(int.Parse(requests[1]), connection); Console.WriteLine("Sent history for {0}", connection.socket.RemoteEndPoint.ToString()); break; case ServerCommands.GetInformation: GetInformation(int.Parse(requests[1]), out response); SendBySocket(connection, response); Console.WriteLine("Sent user's information for {0}", connection.socket.RemoteEndPoint.ToString()); break; case ServerCommands.DeleteFriend: SqlRequests.DeleteFriend(connection.UserID, int.Parse(requests[1])); SendNoticationTo(connection.UserID, int.Parse(requests[1])); Console.WriteLine("Deleted friendship for {0}", connection.socket.RemoteEndPoint.ToString()); break; case ServerCommands.AskSendFile: SendAskSendFile(connection.UserID, int.Parse(requests[1]), int.Parse(requests[2]), int.Parse(requests[3]), request); break; case ServerCommands.ResponseAskSendFile: SendAcceptedAskSendFile(connection.UserID, int.Parse(requests[1]), (ServerAskSendFileResponses)int.Parse(requests[2])); break; case ServerCommands.SendPacket: SendPacket(connection.UserID, int.Parse(requests[1]), int.Parse(requests[2]), request); break; case ServerCommands.Offline: CloseConnection(connection); break; case ServerCommands.Knock: // donothing break; default: break; } }
private static void Request(string request, ServerCommands command) { try { List<byte> requestBuffer = new List<byte>(); requestBuffer.AddRange(BitConverter.GetBytes((int)request.Length)); requestBuffer.AddRange(BitConverter.GetBytes((Int16)command)); requestBuffer.AddRange(Encoding.GetEncoding(1251).GetBytes(request)); // change implementation for (int i = 0; i < 5; i++) { try { clientSocket.Send(requestBuffer.ToArray(), requestBuffer.Count, SocketFlags.None); return; } catch { } } throw new Exception(); } catch { MessageBox.Show(Properties.Resources.ErrorConnetingToServer, Properties.Resources.AppName, MessageBoxButton.OK, MessageBoxImage.Error); } }
public static void RegisterDecoder(ServerCommands command, INetworkReader decoder) { if (decoders.ContainsKey(command)) throw new ArgumentException("Command is allready registered!", nameof(command)); decoders.Add(command, decoder); }
private static byte[] insertCommand(IEnumerable<byte> data, ServerCommands command) { var list = data.ToList(); list.Insert(0, (byte)command); return list.ToArray(); }