protected void addCRC() { if (this.packet != null) { try { byte[] temp = new byte[this.packet.Length + CRC_COUNTER]; byte[] crc = PacketUtility.HexStringToByteArray(Crc16.ComputeChecksum(this.packet).ToString("x2")); Array.Copy(this.packet, 0, temp, 0, this.packet.Length); Array.Copy(crc, 0, temp, this.packet.Length, CRC_COUNTER); this.packet = temp; } catch (Exception e) { throw e; } } else { throw new NullReferenceException(); } }
protected override void OnPlayerIntroduced(IPlayer player) { if (!Game.IsHost) { return; } var replStr = string.Empty; var vars = DevConsole.GetVariablesWithFlags(ConVarFlags.Replicator); foreach (var var in vars) { var str = var + " " + DevConsole.GetVariableAsString(var); if (replStr == string.Empty) { replStr = str; } else { replStr += "&" + str; } } var cp = PacketUtility.TakePacket <CustomPacket>(); cp.Sc = SendCategory.UI_Important; cp.AddString(replStr); cp.Label = "Replicate"; Game.Network.SendPacket(player.ClientIndex, cp); }
protected override void HandleHandshakeRequest() { // For incoming connection, the peer would send the public key to generate a shared secret. var networkStream = NetworkStream; var packet = Packet.Parser.ParseDelimitedFrom(networkStream); if (packet.PacketType != PacketType.Handshake) { throw new Exception("Invalid packet type."); } KeepAliveDuration = packet.PacketKeepAliveDuration; var handshakePacket = PacketUtility.DeserializePacketData(packet, HandshakePacket.Parser); if (handshakePacket.HandshakeType == HandshakeType.CipherText) { throw new Exception("Invalid handshake type."); } using var kem = new KeyEncapsulationMechanism(handshakePacket.KeyEncapsulationMechanismType switch { KeyEncapsulationMechanismType.NtruHps4096821 => "NTRU-HPS-4096-821", var _ => throw new ArgumentOutOfRangeException() });
private async void SynchronizeWithPlayer(IPlayer player) { var cp1 = PacketUtility.TakePacket <CustomPacket>(); cp1.Label = _clearTempPacketLabel; cp1.Sc = SendCategory.FileTransfer; Game.Network.SendPacket(player.ClientIndex, cp1); foreach (var file in _filesToSync) { if (file.FullPath.IsSubPathOf(Structure.PluginsPath)) { var result = await Game.FileTransfer.UploadFileAsync(player, file, true); if (result != FileTransfer.TransferStatus.Success) { UnityEngine.Debug.LogError("Failed to transfer plugin file: " + file.RelativePath); } } } var cp = PacketUtility.TakePacket <CustomPacket>(); cp.Label = _loadTemplPacketLabel; cp.Sc = SendCategory.FileTransfer; Game.Network.SendPacket(player.ClientIndex, cp); }
// Analyze: modify and/or log a pocket private static Packet Analyze(Packet packet, IPEndPoint endPoint, Direction direction) { if (modifiedPackets.Contains(packet.Layout.Name)) { try { Hashtable changes = (Hashtable)modifiedPackets[packet.Layout.Name]; Hashtable blocks = PacketUtility.Unbuild(packet); foreach (BlockField blockField in changes.Keys) { PacketUtility.SetField(blocks, blockField.block, blockField.field, changes[blockField]); } packet = PacketBuilder.BuildPacket(packet.Layout.Name, protocolManager, blocks, packet.Data[0]); } catch (Exception e) { Console.WriteLine("failed to modify " + packet.Layout.Name + ": " + e.Message); Console.WriteLine(e.StackTrace); } } if (loggedPackets.Contains(packet.Layout.Name)) { LogPacket(packet, endPoint, direction); } return(packet); }
// ChatFromViewerOut: outgoing ChatFromViewer delegate; check for Analyst commands private static Packet ChatFromViewerOut(Packet packet, IPEndPoint sim) { // deconstruct the packet Hashtable blocks = PacketUtility.Unbuild(packet); string message = DataConvert.toChoppedString(PacketUtility.GetField(blocks, "ChatData", "Message")); if (message.Length > 1 && message[0] == '/') { string[] words = message.Split(' '); if (commandDelegates.Contains(words[0])) { // this is an Analyst command; act on it and drop the chat packet ((CommandDelegate)commandDelegates[words[0]])(words); return(null); } } if (loggedPackets.Contains("ChatFromViewer") || modifiedPackets.Contains("ChatFromViewer")) { // user has asked to log or modify this packet return(Analyze(packet, sim, Direction.Outgoing)); } else { // return the packet unmodified return(packet); } }
protected override void _Update() { if (Game.IsHost || !SteamUser.VoiceRecord) { return; } _readTime -= UnityEngine.Time.deltaTime; if (_readTime > 0) { return; } _readTime = _audioReadTime; var data = SteamUser.ReadVoiceDataBytes(); if (data != null && data.Length > 0) { var voicePacket = PacketUtility.TakePacket <CompressedVoiceData>(); voicePacket.ClientIndex = Game.ClientIndex; voicePacket.SetData(data, data.Length); Client.GameClient.Instance.Socket.BroadcastPacket(voicePacket); } }
private void SendChunk(IPlayer player, UploadState state) { long remaining = state.InputStream.Length - state.SentOffset; int sendBytes = (remaining > state.ChunkLength ? state.ChunkLength : (int)remaining); var chunk = PacketUtility.TakePacket <FileChunk>(); chunk.Data = new byte[sendBytes]; chunk.ChunkLength = sendBytes; chunk.File = state.File.RelativePath; chunk.TotalLength = state.InputStream.Length; chunk.Temporary = state.IsTemporaryFile; state.InputStream.Read(chunk.Data, 0, sendBytes); Game.Network.SendPacket(player.ClientIndex, chunk); state.SentOffset += sendBytes; if (remaining - sendBytes <= 0) { state.InputStream.Close(); state.InputStream.Dispose(); state.Status = TransferStatus.Success; } }
public void SendPlayerBackfill(IPlayer player) { foreach (var playerToSend in Game.PlayerManager.Players) { if (playerToSend.ClientIndex != player.ClientIndex) { var ev = PacketUtility.TakePacket <PlayerEvent>(); ev.Sc = SendCategory.UI_Important; ev.EventType = PlayerEventType.Backfill; ev.ClientIndex = playerToSend.ClientIndex; ev.DisplayName = playerToSend.DisplayName; ev.TeamNumber = playerToSend.Team; ev.Latency = playerToSend.Latency; ev.SteamID = playerToSend.SteamId; Game.GetFSComponent <SocketManager>().SendPacketBrute(player.ClientIndex, ev); } } foreach (var ent in Game.EntityManager.Entities) { if (ent.IsValid()) { var updatePacket = PacketUtility.TakePacket <EntityUpdate>(); updatePacket.Sc = SendCategory.UI_Important; updatePacket.Load(ent); Game.GetFSComponent <SocketManager>().SendPacketBrute(player.ClientIndex, updatePacket); } } }
protected override void OnPlayerPacketReceived(IPlayer player, IBasePacket packet) { if (packet is ChatMessage chatMessage) { if (chatMessage.Message.Length < 1) { return; } if (Game.IsHost) { if (chatMessage.Message.Length > MaxMessageLength) { chatMessage.Message = chatMessage.Message.Substring(0, MaxMessageLength); } if (chatMessage.Message[0] == CommandChar) { ParseCommand(player, chatMessage.Message); } else { var msgToSend = PacketUtility.TakePacket <ChatMessage>(); msgToSend.ClientIndex = player.ClientIndex; msgToSend.Name = player.DisplayName; msgToSend.Message = chatMessage.Message; msgToSend.Scope = chatMessage.Scope; msgToSend.SupporterLevel = chatMessage.SupporterLevel; Game.Network.BroadcastPacket(msgToSend); } } OnMessageReceived?.Invoke(chatMessage, chatMessage.Name, chatMessage.Message, chatMessage.ClientIndex == -1); } }
protected override void OnPlayerDisconnected(IPlayer player) { var ev = PacketUtility.TakePacket <PlayerEvent>(); ev.EventType = PlayerEventType.Disconnected; ev.ClientIndex = player.ClientIndex; Game.GetFSComponent <SocketManager>().BroadcastPacket(ev); }
protected override void OnPlayerChangedName(IPlayer player) { var ev = PacketUtility.TakePacket <PlayerEvent>(); ev.EventType = PlayerEventType.ChangedName; ev.ClientIndex = player.ClientIndex; ev.DisplayName = player.DisplayName; Game.GetFSComponent <SocketManager>().BroadcastPacket(ev); }
protected override void OnPlayerSpectate(IPlayer spectator, IPlayer target) { var ev = PacketUtility.TakePacket <PlayerEvent>(); ev.EventType = PlayerEventType.Spectate; ev.ClientIndex = spectator.ClientIndex; ev.SpecTarget = target == null ? -1 : target.ClientIndex; Game.GetFSComponent <SocketManager>().BroadcastPacket(ev); }
private void SendMapChange(ServerPlayer player) { var mapChange = PacketUtility.TakePacket <MapChange>(); mapChange.MapName = MapLoader.Instance.CurrentMap.Name; mapChange.Gamemode = Game.GamemodeLoader.Gamemode.Name; mapChange.ClientIndex = player.ClientIndex; Game.GetFSComponent <SocketManager>().SendPacketBrute(player, mapChange); }
private void SendFileSync(ServerPlayer player) { var fileSync = PacketUtility.TakePacket <FileSync>(); fileSync.SyncType = FileSync.FileSyncType.Manifest; fileSync.DownloadUrl = DevConsole.GetVariable <string>("net.downloadurl") ?? string.Empty; fileSync.Files = new System.Collections.Generic.List <FSFileInfo>(FileSystem.DownloadList); Game.GetFSComponent <SocketManager>().SendPacketBrute(player, fileSync); }
protected override void OnPlayerLatencyUpdated(IPlayer player) { var ev = PacketUtility.TakePacket <PlayerEvent>(); ev.Sc = SendCategory.Unreliable; ev.EventType = PlayerEventType.LatencyUpdated; ev.ClientIndex = player.ClientIndex; ev.Latency = player.Latency; Game.GetFSComponent <SocketManager>().BroadcastPacket(ev); }
private ChatMessage GetChatPacket(string message) { var packet = PacketUtility.TakePacket <ChatMessage>(); packet.ClientIndex = Game.ClientIndex; packet.Message = message; packet.Name = Game.IsHost ? ServerName : Steamworks.SteamClient.Name; packet.SupporterLevel = 0; return(packet); }
public void HandleIncomingData(NetBuffer buffer) { var packetType = buffer.ReadByte(); var packet = PacketUtility.TakePacket(packetType); ProcessPacket(buffer, packetType, packet); if (packet != null && !PacketIsWaiting(packet)) { PacketUtility.PutPacket(packet); } }
private void BroadcastPlayerIntroduced(IPlayer player) { var ev = PacketUtility.TakePacket <PlayerEvent>(); ev.EventType = PlayerEventType.Introduced; ev.ClientIndex = player.ClientIndex; ev.DisplayName = player.DisplayName; ev.TeamNumber = player.Team; ev.Latency = player.Latency; ev.SteamID = player.SteamId; Game.GetFSComponent <SocketManager>().BroadcastPacket(ev); }
public void EmitToPlayer(IPlayer player, string eventPath, Vector3 position = default) { if (!Game.IsHost) { return; } var sound = PacketUtility.TakePacket <PlaySound>(); sound.Event = eventPath; sound.Position = position; sound.Twod = position == Vector3.zero; Game.Network.SendPacket(player.ClientIndex, sound); }
public void EmitToAll(string eventPath, Vector3 position = default) { if (!Game.IsHost) { return; } var sound = PacketUtility.TakePacket <PlaySound>(); sound.Event = eventPath; sound.Position = position; sound.Twod = position == Vector3.zero; Game.Network.BroadcastPacket(sound); }
private void SendCommand(string name, params object[] args) { var packet = PacketUtility.TakePacket <EntityCommand>(); packet.CommandName = name; packet.EntityId = EntityId; packet.ArgsJson = JsonConvert.SerializeObject(args, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); Game.Network.BroadcastPacket(packet); }
protected unsafe override void OnPlayerPacketReceived(IPlayer player, IBasePacket packet) { if (!(packet is CompressedVoiceData voicePacket)) { return; } if (Game.IsHost) { var packetToSend = PacketUtility.TakePacket <CompressedVoiceData>(); packetToSend.SetData(voicePacket.Data, voicePacket.DataLength); packetToSend.ClientIndex = player.ClientIndex; Server.GameServer.Instance.Socket.BroadcastPacket(packetToSend); } else { var vol = DevConsole.GetVariable <float>("audio.voiceoutput"); if (vol == 0) { return; } var clientIndex = voicePacket.ClientIndex; if (clientIndex == Game.ClientIndex && !_loopback) { return; } int uncompressedDataLength = 0; var speakingPlayer = Game.PlayerManager.FindPlayer(clientIndex); fixed(byte *src = voicePacket.Data) { fixed(byte *dst = _data) { uncompressedDataLength = SteamUser.DecompressVoice((IntPtr)src, voicePacket.DataLength, (IntPtr)dst, _data.Length); } } if (uncompressedDataLength == 0 || speakingPlayer == null) { return; } throw new System.NotImplementedException(); // _data to audio.. //UnityEngine.Debug.Log($"size: {data.Length} - group: {getChannelGroupResult} - create: {createSoundResult} - play: {playSoundResult}"); } }
private void HandleRunCommand(IPlayer player, UserCmd cmd, bool isPrediction = false) { if (!(player.Entity is Human human)) { return; } human.RunCommand(cmd, isPrediction); if (Game.IsHost || isPrediction) { Game.PlayerManager.RaiseRunCommand(player); } if (Game.IsHost && !isPrediction) { UserCmd newCmd; if (_finalCmds.ContainsKey(player)) { newCmd = _finalCmds[player]; } else { newCmd = PacketUtility.TakePacket <UserCmd>(); _finalCmds[player] = newCmd; } newCmd.Copy(cmd); newCmd.ClientIndex = player.ClientIndex; newCmd.Origin = human.Origin; newCmd.Velocity = human.Velocity; newCmd.BaseVelocity = human.BaseVelocity; // usercmd is ReliableSequenced by default so clients don't lose inputs // but we don't want the host to clog up with this shit so switch to to UnreliableSequenced just to send it back to the client newCmd.Sc = SendCategory.Gameplay; // broadcast //ServerLoop.Instance.BetterGameServer.BroadcastPacketEnqueue(newCmd); } else if (!Game.IsHost && isPrediction) { cmd.Origin = human.Origin; cmd.Velocity = human.Velocity; cmd.BaseVelocity = human.BaseVelocity; var cmdToSend = PacketUtility.TakePacket <UserCmd>(); cmdToSend.Copy(cmd); Game.Network.BroadcastPacket(cmdToSend); } }
private void FSConsole_OnVariableChanged(string varName) { if (!Game.IsHost || !DevConsole.VariableHasFlags(varName, ConVarFlags.Replicator)) { return; } var replStr = varName + " " + DevConsole.GetVariableAsString(varName); var cp = PacketUtility.TakePacket <CustomPacket>(); cp.Sc = SendCategory.UI_Important; cp.AddString(replStr); cp.Label = "Replicate"; Game.Network.BroadcastPacket(cp); }
public override byte[] toRaw() { try { if (this.Cmd == WRITE_CMD) { packet = new byte[SRC_ADD_COUNTER + DEST_ADD_COUNTER + CMD_COUNTER + ADD_VAR_COUNTER + MESSAGE_TEXT_COUNTER]; } else { packet = new byte[SRC_ADD_COUNTER + DEST_ADD_COUNTER + CMD_COUNTER + ADD_VAR_COUNTER]; } cIndex = SRC_ADD_COUNTER + DEST_ADD_COUNTER; packet[cIndex] = this.Cmd; cIndex += CMD_COUNTER; add_var = PacketUtility.IntToTwoBytes(getSMSTextAV(this.SimNumber)); Array.Copy(add_var, 0, packet, cIndex, ADD_VAR_COUNTER); cIndex += ADD_VAR_COUNTER; if (this.Cmd == AbstractPacket.WRITE_CMD) { byte[] temp = Encoding.BigEndianUnicode.GetBytes(this.Message); if (temp.Length > MESSAGE_TEXT_COUNTER) { throw new IndexOutOfRangeException(); } byte[] message_bytes = new byte[MESSAGE_TEXT_COUNTER]; Array.Copy(temp, 0, message_bytes, 0, temp.Length); Array.Copy(message_bytes, 0, packet, cIndex, MESSAGE_TEXT_COUNTER); cIndex += MESSAGE_TEXT_COUNTER; } return(base.toRaw()); } catch (Exception e) { throw; } }
private static Packet ChatFromSimulator(Packet packet, IPEndPoint sim) { // deconstruct the packet Hashtable blocks = PacketUtility.Unbuild(packet); string message = DataConvert.toChoppedString(PacketUtility.GetField(blocks, "ChatData", "Message")); string name = DataConvert.toChoppedString(PacketUtility.GetField(blocks, "ChatData", "FromName")); byte audible = (byte)PacketUtility.GetField(blocks, "ChatData", "Audible"); byte type = (byte)PacketUtility.GetField(blocks, "ChatData", "ChatType"); // if this was a normal, audible message, write it to the console if (audible != 0 && (type == 0 || type == 1 || type == 2)) { Console.WriteLine(name + ": " + message); } // return the packet unmodified return(packet); }
public override byte[] toRaw() { packet = new byte[SRC_ADD_COUNTER + DEST_ADD_COUNTER + CMD_COUNTER + ADD_VAR_COUNTER]; cIndex = SRC_ADD_COUNTER + DEST_ADD_COUNTER; packet[cIndex] = AbstractPacket.READ_CMD; cIndex += CMD_COUNTER; add_var = PacketUtility.IntToTwoBytes(getInboxAVBound(this.SimNumber)[0] + this.Index); Array.Copy(add_var, 0, packet, cIndex, ADD_VAR_COUNTER); cIndex += ADD_VAR_COUNTER; addCRC(); return(packet); }
public override byte[] toRaw() { if (this.Cmd == WRITE_CMD) { packet = new byte[SRC_ADD_COUNTER + DEST_ADD_COUNTER + CMD_COUNTER + ADD_VAR_COUNTER + NUMBER_COUNTER + ID_COUNTER + STATUS_COUNTER]; } else { packet = new byte[SRC_ADD_COUNTER + DEST_ADD_COUNTER + CMD_COUNTER + ADD_VAR_COUNTER]; } cIndex = SRC_ADD_COUNTER + DEST_ADD_COUNTER; packet[cIndex] = this.Cmd; cIndex += CMD_COUNTER; add_var = PacketUtility.IntToTwoBytes(getRegistrationAVBound(this.SimNumber)[0] + Index); Array.Copy(add_var, 0, packet, cIndex, ADD_VAR_COUNTER); cIndex += ADD_VAR_COUNTER; if (this.Cmd == WRITE_CMD) { number = number.Substring(2); int num = Convert.ToInt32(number); byte[] arr_number = PacketUtility.IntToByteArray(num); Array.Copy(arr_number, 0, packet, cIndex, NUMBER_COUNTER); cIndex += NUMBER_COUNTER; byte[] arr_id = { 0x00 }; Array.Copy(arr_id, 0, packet, cIndex, ID_COUNTER); cIndex += ID_COUNTER; byte[] arr_status = { 0x00 }; Array.Copy(arr_status, 0, packet, cIndex, STATUS_COUNTER); cIndex += STATUS_COUNTER; } return(base.toRaw()); }
public override string ToString() { try { if (packet != null) { return(string.Format("Unexpected Packet => {0}", PacketUtility.ByteArrayToHexString(packet))); } else { return("Null Packet"); } } catch { return("Unknown Packet;"); } }