public static void Save(string save_name) { if (SaveGame.m_State != SaveGame.State.None) { Debug.LogWarning("Can't save, state = " + SaveGame.m_State.ToString()); return; } if (GreenHellGame.Instance.IsGamescom()) { return; } if (!ReplTools.IsPlayingAlone() && !ReplTools.AmIMaster()) { SaveGame.SaveCoop(); return; } Debug.Log("SAVE - " + save_name); SaveGame.m_State = SaveGame.State.Save; HUDSaving.Get().Activate(); SaveGame.SetupObjects(); SaveGame.m_IVals.Clear(); SaveGame.m_SVals.Clear(); SaveGame.m_FVals.Clear(); SaveGame.m_BVals.Clear(); foreach (ISaveLoad saveLoad in SaveGame.m_Objects) { saveLoad.Save(); } BinaryFormatter binaryFormatter = new BinaryFormatter(); MemoryStream memoryStream = new MemoryStream(); binaryFormatter.Serialize(memoryStream, GreenHellGame.s_GameVersion); binaryFormatter.Serialize(memoryStream, GreenHellGame.Instance.m_GameMode); long num = DateTime.Now.ToBinary(); binaryFormatter.Serialize(memoryStream, num); int ivalue = StatsManager.Get().GetStatistic(Enums.Event.DaysSurvived).IValue; binaryFormatter.Serialize(memoryStream, ivalue); int activePresetType = (int)DifficultySettings.GetActivePresetType(); binaryFormatter.Serialize(memoryStream, activePresetType); binaryFormatter.Serialize(memoryStream, MainLevel.Instance.m_Tutorial); bool flag = Player.Get().IsDead(); binaryFormatter.Serialize(memoryStream, flag); binaryFormatter.Serialize(memoryStream, ReplicatedSessionState.Get() != null && ReplicatedSessionState.Get().m_PlayedCoop); Stream serializationStream = memoryStream; P2PSession instance = P2PSession.Instance; binaryFormatter.Serialize(serializationStream, ((instance != null) ? instance.GetSessionId() : null) ?? ""); binaryFormatter.Serialize(memoryStream, SaveGame.m_IVals); binaryFormatter.Serialize(memoryStream, SaveGame.m_SVals); binaryFormatter.Serialize(memoryStream, SaveGame.m_FVals); binaryFormatter.Serialize(memoryStream, SaveGame.m_BVals); DebugUtils.Assert(GreenHellGame.Instance.m_RemoteStorage.FileWrite(save_name, memoryStream.GetBuffer()), "SaveGame - remote storage write failed", true, DebugUtils.AssertType.Info); memoryStream.Close(); SaveGame.SaveScreenshot(save_name); SaveGame.m_State = SaveGame.State.None; }
public bool Start(IP2PAddress address) { this.StartInternal(); if (P2PTransportLayer.Instance.GetLayerType() == ETransporLayerType.UNet) { P2PAddressUnet p2PAddressUnet = address as P2PAddressUnet; if (p2PAddressUnet.m_IP.Equals("localhost")) { p2PAddressUnet.m_IP = "127.0.0.1"; } else if (p2PAddressUnet.m_IP.IndexOf(":") != -1 && !P2PSession.IsValidIpV6(p2PAddressUnet.m_IP) && P2PLogFilter.logError) { Debug.LogError("Invalid ipv6 address " + p2PAddressUnet.m_IP); } } this.SetGameVisibility(GreenHellGame.Instance.m_Settings.m_GameVisibility); this.m_LocalPeer.SetLocalHostId((short)P2PTransportLayer.Instance.AddHost(P2PSession.s_HostTopology, ref address)); if (this.m_LocalPeer.GetLocalHostId() == P2PPeer.s_InvalidId) { if (P2PLogFilter.logError) { Debug.LogError("StartServer listen failed."); } return(false); } this.m_LocalPeer.m_Address = address; this.m_LocalPeer.SetHostId(this.m_LocalPeer.GetLocalHostId()); if (P2PLogFilter.logDebug) { Debug.Log("P2PSession listen start with id: " + this.GetSessionId()); } this.Status = P2PSession.ESessionStatus.Listening; return(true); }
public override bool ProcessData(P2PBridge bridge, byte[] data, bool reset) { if (_sending) { // We are sender but remote client want to kill me :) return(false); } if (reset) { _dataStream.SetLength(0); } if (data.Length > 0) { _dataStream.Write(data, 0, data.Length); } OnProgressed(EventArgs.Empty); if (_dataStream.Length == (long)_context.FileSize) { // Finished transfer OnTransferFinished(EventArgs.Empty); P2PSession.Close(); } return(true); }
/// <summary> /// We are sender /// </summary> /// <param name="p2pSession"></param> public ObjectTransfer(P2PSession p2pSession) : base(p2pSession) { msnObject = new MSNObject(); msnObject.SetContext(p2pSession.Invitation.BodyValues["Context"].Value, true); if (msnObject.ObjectType == MSNObjectType.UserDisplay || msnObject.ObjectType == MSNObjectType.Unknown) { msnObject = NSMessageHandler.Owner.DisplayImage; objStream = NSMessageHandler.Owner.DisplayImage.OpenStream(); } else if (msnObject.ObjectType == MSNObjectType.Scene) { msnObject = NSMessageHandler.Owner.SceneImage; objStream = NSMessageHandler.Owner.SceneImage.OpenStream(); } else if (msnObject.ObjectType == MSNObjectType.Emoticon && Local.Emoticons.ContainsKey(msnObject.Sha)) { msnObject = Local.Emoticons[msnObject.Sha]; objStream = ((Emoticon)msnObject).OpenStream(); } sending = true; if (p2pSession.Invitation.BodyValues.ContainsKey("AppID")) { applicationId = uint.Parse(p2pSession.Invitation.BodyValues["AppID"]); } }
public static void LoadPlayer(string save_name) { if (SaveGame.m_State != SaveGame.State.None) { Debug.LogWarning("Can't load player, state = " + SaveGame.m_State.ToString()); return; } if (!File.Exists(Application.persistentDataPath + "/" + save_name)) { return; } Debug.Log("LOAD_PLAYER - " + save_name); SaveGame.m_State = SaveGame.State.Load; SaveGame.SetupObjects(); SaveGame.m_IVals.Clear(); SaveGame.m_SVals.Clear(); SaveGame.m_FVals.Clear(); SaveGame.m_BVals.Clear(); BinaryFormatter binaryFormatter = new BinaryFormatter(); FileStream fileStream = File.Open(Application.persistentDataPath + "/" + save_name, FileMode.Open); GameVersion lhs = new GameVersion((GameVersion)binaryFormatter.Deserialize(fileStream)); GameMode gameMode = (GameMode)binaryFormatter.Deserialize(fileStream); long num = (long)binaryFormatter.Deserialize(fileStream); int num2 = (int)binaryFormatter.Deserialize(fileStream); int num3 = (int)binaryFormatter.Deserialize(fileStream); if (lhs >= GreenHellGame.s_GameVersionEarlyAccessUpdate8) { bool flag = (bool)binaryFormatter.Deserialize(fileStream); } if (lhs >= GreenHellGame.s_GameVersionEarlyAccessUpdate12 && lhs < GreenHellGame.s_GameVersionEarlyAccessUpdate13 && (bool)binaryFormatter.Deserialize(fileStream)) { DifficultySettings.SetActivePresetType(DifficultySettings.PresetType.PermaDeath); } if (lhs >= GreenHellGame.s_GameVersionEarlyAccessUpdate13) { bool flag2 = (bool)binaryFormatter.Deserialize(fileStream); } if (GreenHellGame.s_GameVersion >= GreenHellGame.s_GameVersionMasterShelters1_3) { BinaryFormatter binaryFormatter2 = binaryFormatter; Stream serializationStream = fileStream; P2PSession instance = P2PSession.Instance; binaryFormatter2.Serialize(serializationStream, ((instance != null) ? instance.GetSessionId() : null) ?? ""); } SaveGame.m_IVals = (Dictionary <string, int>)binaryFormatter.Deserialize(fileStream); SaveGame.m_SVals = (Dictionary <string, string>)binaryFormatter.Deserialize(fileStream); SaveGame.m_FVals = (Dictionary <string, float>)binaryFormatter.Deserialize(fileStream); SaveGame.m_BVals = (Dictionary <string, bool>)binaryFormatter.Deserialize(fileStream); fileStream.Close(); Player.Get().Load(); PlayerInjuryModule.Get().Load(); PlayerConditionModule.Get().Load(); PlayerDiseasesModule.Get().Load(); ItemsManager.Get().Load(); MainLevel.Instance.Load(); GreenHellGame.Instance.m_LoadGameState = LoadGameState.FullLoadCompleted; SaveGame.m_State = SaveGame.State.None; }
/// <summary> /// We are receiver. /// </summary> /// <param name="p2pSession"></param> public FileTransfer(P2PSession p2pSession) : base(p2pSession) { _context = new FTContext(Convert.FromBase64String(p2pSession.Invitation.BodyValues["Context"].Value)); _sending = false; _dataStream = null; // Must be set when InvitationReceived }
protected P2PApplication(P2PSession p2pSess) : this(p2pSess.Version, p2pSess.Remote, p2pSess.RemoteContactEndPointID) { P2PSession = p2pSess; // Register events Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Application associated with session: " + p2pSess.SessionId, GetType().Name); }
private void InitializeChannel(IChannel channel, EncryptionHandshakeRole role, NodeId remoteId = null, string remoteHost = null, int?remotePort = null) { var connectionType = remoteId == null ? ClientConnectionType.In : ClientConnectionType.Out; P2PSession p2PSession = new P2PSession( LocalNodeId, _localPort, _serializationService, _synchronizationManager, _logManager) { ClientConnectionType = connectionType }; //This is the first moment we get confirmed publicKey of remote node in case of outgoing connections if (connectionType == ClientConnectionType.Out) { if (_logger.IsInfoEnabled) { _logger.Info($"Initializing {connectionType.ToString().ToUpper()} channel{(connectionType == ClientConnectionType.Out ? $": {remoteId}@{remoteHost}:{remoteId}" : string.Empty)}"); } p2PSession.RemoteNodeId = remoteId; p2PSession.RemoteHost = remoteHost; p2PSession.RemotePort = remotePort; ConnectionInitialized?.Invoke(this, new ConnectionInitializedEventArgs(p2PSession, connectionType)); } var handshakeHandler = new NettyHandshakeHandler(_encryptionHandshakeService, p2PSession, role, remoteId, _logger); handshakeHandler.HandshakeInitialized += (s, e) => { //This is the first moment we get confirmed publicKey of remote node in case of incoming connections if (connectionType == ClientConnectionType.In) { if (_logger.IsInfoEnabled) { _logger.Info($"Initializing {connectionType.ToString().ToUpper()} channel {p2PSession.RemoteNodeId}@{p2PSession.RemoteHost}:{p2PSession.RemotePort}"); } ConnectionInitialized?.Invoke(this, new ConnectionInitializedEventArgs(p2PSession, connectionType)); } }; IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new LoggingHandler(connectionType.ToString().ToUpper(), DotNetty.Handlers.Logging.LogLevel.TRACE)); pipeline.AddLast("enc-handshake-dec", new LengthFieldBasedFrameDecoder(ByteOrder.BigEndian, ushort.MaxValue, 0, 2, 0, 0, true)); pipeline.AddLast("enc-handshake-handler", handshakeHandler); channel.CloseCompletion.ContinueWith(async x => { if (_logger.IsInfoEnabled) { _logger.Info($"Channel disconnection: {p2PSession.RemoteNodeId}"); } await p2PSession.DisconnectAsync(DisconnectReason.ClientQuitting, DisconnectType.Remote); }); }
private void InitializeChannel(IChannel channel, ConnectionDirection connectionDirection, NodeId remoteId = null, string remoteHost = null, int?remotePort = null, INodeStats nodeStats = null) { if (connectionDirection == ConnectionDirection.In) { Metrics.IncomingConnections++; } else { Metrics.OutgoingConnections++; } P2PSession session = new P2PSession( LocalNodeId, remoteId, _localPort, connectionDirection, _serializationService, _synchronizationManager, _nodeStatsProvider, nodeStats, _logManager, channel, _perfService, _blockTree, _transactionPool, _timestamp); if (connectionDirection == ConnectionDirection.Out) { if (_logger.IsTrace) { _logger.Trace($"Initializing {connectionDirection.ToString().ToUpper()} channel{(connectionDirection == ConnectionDirection.Out ? $": {remoteId}@{remoteHost}:{remotePort}" : string.Empty)}"); } // this is the first moment we get confirmed publicKey of remote node in case of outgoing connections session.RemoteNodeId = remoteId; session.RemoteHost = remoteHost; session.RemotePort = remotePort; } SessionCreated?.Invoke(this, new SessionEventArgs(session)); HandshakeRole role = connectionDirection == ConnectionDirection.In ? HandshakeRole.Recipient : HandshakeRole.Initiator; var handshakeHandler = new NettyHandshakeHandler(_encryptionHandshakeService, session, role, remoteId, _logManager); IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new LoggingHandler(connectionDirection.ToString().ToUpper(), DotNetty.Handlers.Logging.LogLevel.TRACE)); pipeline.AddLast("enc-handshake-dec", new LengthFieldBasedFrameDecoder(ByteOrder.BigEndian, ushort.MaxValue, 0, 2, 0, 0, true)); pipeline.AddLast("enc-handshake-handler", handshakeHandler); channel.CloseCompletion.ContinueWith(async x => { if (_logger.IsTrace) { _logger.Trace($"Channel disconnected: {session.RemoteNodeId}"); } await session.DisconnectAsync(DisconnectReason.ClientQuitting, DisconnectType.Remote); SessionClosing?.Invoke(this, new SessionEventArgs(session)); }); }
public void Can_start_p2p_session() { IPacketSender sender = Substitute.For <IPacketSender>(); IMessageSerializationService service = Build.A.SerializationService().WithP2P().TestObject; P2PSession factory = new P2PSession(new NodeId(NetTestVectors.StaticKeyA.PublicKey), ListenPort, service, Substitute.For <ISynchronizationManager>(), NullLogManager.Instance); factory.Init(4, Substitute.For <IChannelHandlerContext>(), sender); sender.Received().Enqueue(Arg.Is <Packet>(p => p.PacketType == 0 && p.Protocol == "p2p")); }
/// <summary> /// Frees the resources for this <see cref="P2PApplication"/>. /// </summary> public virtual void Dispose() { P2PSession = null; // Unregister events if ((status != P2PApplicationStatus.Aborted) && (status != P2PApplicationStatus.Finished) && (status != P2PApplicationStatus.Error)) { OnTransferError(EventArgs.Empty); } Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Application disposed", GetType().Name); }
/// <summary> /// Creates a new P2PApplication instance with the parameters provided. /// </summary> /// <param name="eufGuid"></param> /// <param name="appId"></param> /// <param name="withSession"></param> internal static P2PApplication CreateInstance(Guid eufGuid, uint appId, P2PSession withSession) { if (withSession != null && eufGuid != Guid.Empty && p2pAppCache.ContainsKey(eufGuid)) { if (appId != 0) { foreach (P2PApp app in p2pAppCache[eufGuid]) { if (appId == app.AppId) { return((P2PApplication)Activator.CreateInstance(app.AppType, withSession)); } } } return((P2PApplication)Activator.CreateInstance(p2pAppCache[eufGuid][0].AppType, withSession)); } return(null); }
public P2PActivity(P2PSession p2pSess) : base(p2pSess.Version, p2pSess.Remote, p2pSess.RemoteContactEndPointID) { try { byte[] byts = Convert.FromBase64String(p2pSess.Invitation.BodyValues["Context"].Value); string activityUrl = System.Text.Encoding.Unicode.GetString(byts); string[] activityProperties = activityUrl.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (activityProperties.Length >= 3) { uint.TryParse(activityProperties[0], out applicationId); activityName = activityProperties[2]; } } catch (Exception ex) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "An error occured while parsing activity context, error info: " + ex.Message, GetType().Name); } sending = false; }
public override void Start() { if (_dataStream == null) { throw new InvalidOperationException("DataStream must be set before start"); } base.Start(); if (Sending) { P2PSession.SendDirectInvite(); _dataStream.Seek(0, SeekOrigin.Begin); _sendingData = true; packNum = ++base.P2PSession.Bridge.PackageNo; if (P2PSession.Bridge.Ready(P2PSession)) { SendChunk(); } } }
private void ConnectInternal(IP2PAddress address) { this.StartInternal(); this.m_AmIMaster = false; P2PAddressUnet p2PAddressUnet = address as P2PAddressUnet; if (p2PAddressUnet != null) { if (p2PAddressUnet.m_IP.Equals("localhost")) { p2PAddressUnet.m_IP = "127.0.0.1"; } else if (p2PAddressUnet.m_IP.IndexOf(":") != -1 && !P2PSession.IsValidIpV6(p2PAddressUnet.m_IP) && P2PLogFilter.logError) { Debug.LogError("Invalid ipv6 address " + p2PAddressUnet.m_IP); } } int networkConnectionId; if (this.m_UseSimulator) { int num = this.m_SimulatedLatency / 3; if (num < 1) { num = 1; } if (P2PLogFilter.logDebug) { Debug.Log(string.Concat(new object[] { "Connect Using Simulator ", this.m_SimulatedLatency / 3, "/", this.m_SimulatedLatency })); } ConnectionSimulatorConfig config = new ConnectionSimulatorConfig(num, this.m_SimulatedLatency, num, this.m_SimulatedLatency, this.m_PacketLoss); byte b; networkConnectionId = P2PTransportLayer.Instance.ConnectWithSimulator(address, out b, config); } else { byte b; networkConnectionId = P2PTransportLayer.Instance.Connect(address, out b); } P2PConnection p2PConnection = (P2PConnection)Activator.CreateInstance(typeof(P2PConnection)); p2PConnection.SetHandlers(this.m_MessageHandlers); P2PPeer p2PPeer = null; for (int i = 0; i < this.m_PendingPeers.Count; i++) { if (this.m_PendingPeers[i].IsSameAddress(address)) { p2PPeer = this.m_PendingPeers[i]; this.m_PendingPeers.RemoveAt(i); break; } } if (p2PPeer == null) { p2PPeer = new P2PPeer(); p2PPeer.m_Address = address; } if (!this.m_RemotePeersInternal.Contains(p2PPeer)) { this.m_RemotePeersInternal.Add(p2PPeer); } p2PConnection.Initialize(p2PPeer, networkConnectionId, P2PSession.s_HostTopology); this.SetConnectionAtIndex(p2PConnection); if (this.Status == P2PSession.ESessionStatus.Idle) { this.Status = P2PSession.ESessionStatus.Connecting; } }
private void SendChunk() { if (!_sendingData) { return; } P2PDataMessage p2pChunk = new P2PDataMessage(P2PVersion); long offset = _dataStream.Position; // First chunk if (offset == 0) { if (P2PVersion == P2PVersion.P2PV1) { P2PSession.IncreaseLocalIdentifier(); p2pChunk.V1Header.TotalSize = (ulong)_dataStream.Length; } else if (P2PVersion == P2PVersion.P2PV2) { p2pChunk.V2Header.TFCombination = TFCombination.First; } } p2pChunk.Header.Identifier = P2PSession.LocalIdentifier; p2pChunk.WriteBytes(_dataStream, P2PSession.Bridge.MaxDataSize); AckHandler ackHandler = null; int ackTimeout = P2PBridge.MaxTimeout; if (P2PVersion == P2PVersion.P2PV1) { p2pChunk.V1Header.Flags = P2PFlag.FileData; } else if (P2PVersion == P2PVersion.P2PV2) { p2pChunk.V2Header.PackageNumber = packNum; p2pChunk.V2Header.TFCombination |= TFCombination.FileTransfer; if (p2pv2NextRAK < DateTime.Now) { _sendingData = false; // Activate when ack received. p2pChunk.V2Header.OperationCode |= (byte)OperationCode.RAK; p2pv2NextRAK = DateTime.Now.AddSeconds(8); ackTimeout = P2PBridge.DefaultTimeout; ackHandler = delegate(P2PMessage ack) { _sendingData = true; // Ack received, continue sending... SendChunk(); }; } } if (_dataStream.Position == _dataStream.Length) { _sendingData = false; SendMessage(p2pChunk); // This is the last chunk of data, register the ACKHandler P2PMessage rak = new P2PMessage(P2PVersion); SendMessage(rak, P2PBridge.DefaultTimeout, delegate(P2PMessage ack) { Abort(); OnTransferFinished(EventArgs.Empty); }); } else { SendMessage(p2pChunk, ackTimeout, ackHandler); } OnProgressed(EventArgs.Empty); }
public override bool ProcessData(P2PBridge bridge, byte[] data, bool reset) { if (sending) { // We are sender but remote client want to kill me :) return(false); } if (reset) { // Data prep or TFCombination.First objStream.SetLength(0); } if (data.Length > 0) { objStream.Write(data, 0, data.Length); Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, String.Format("Received {0} / {1}", objStream.Length, msnObject.Size), GetType().Name); if (objStream.Length == msnObject.Size) { // Finished transfer byte[] allData = new byte[msnObject.Size]; objStream.Seek(0, SeekOrigin.Begin); objStream.Read(allData, 0, allData.Length); string dataSha = Convert.ToBase64String(new SHA1Managed().ComputeHash(allData)); if (dataSha != msnObject.Sha) { Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, "Object hash doesn't match data hash, data invalid", GetType().Name); return(false); } MemoryStream ms = new MemoryStream(allData); ms.Position = 0; // Data CHECKSUM is ok, update MsnObject if (msnObject.ObjectType == MSNObjectType.UserDisplay) { DisplayImage newDisplayImage = new DisplayImage(Remote.Account.ToLowerInvariant(), ms); Remote.SetDisplayImageAndFireDisplayImageChangedEvent(newDisplayImage); msnObject = newDisplayImage; } else if (msnObject.ObjectType == MSNObjectType.Scene) { SceneImage newSceneImage = new SceneImage(Remote.Account.ToLowerInvariant(), ms); Remote.SetSceneImageAndFireSceneImageChangedEvent(newSceneImage); msnObject = newSceneImage; } else if (msnObject.ObjectType == MSNObjectType.Emoticon) { ((Emoticon)msnObject).Image = Image.FromStream(objStream); } else if (msnObject.ObjectType == MSNObjectType.Wink) { Stream s = ((Wink)msnObject).OpenStream(); s.Write(allData, 0, allData.Length); } objStream.Close(); OnTransferFinished(EventArgs.Empty); if (P2PSession != null) { P2PSession.Close(); // Send first BYE } } } return(true); }
public void Disconnect(DisconnectReason disconnectReason) { _headersRequests.CompleteAdding(); _bodiesRequests.CompleteAdding(); P2PSession.DisconnectAsync(disconnectReason, DisconnectType.Local); }
public FileTransferForm(P2PSession p2pSess) { this.p2pSession = p2pSess; this.fileTransfer = p2pSess.Application as FileTransfer; InitializeComponent(); }