Ejemplo n.º 1
0
        public async Task StartReceive()
        {
            connected = Convert.ToInt32(true);

            AsyncUserToken token = (AsyncUserToken)readEventArgs.UserToken;

            Socket         = token.Socket;
            Socket.NoDelay = true;

            RemoteEndPoint = (IPEndPoint)Socket.RemoteEndPoint;

            if (Direction == Direction.Client)
            {
                var afterPacket     = Observable.FromEventPattern <PacketEventArgs>(p => AfterPacketReceived += p, p => AfterPacketReceived -= p);
                var heartbeatPacket = (from p in afterPacket where p.EventArgs.Packet.PacketId == (int)KnownPacket.Heartbeat select p).Timeout(TimeSpan.FromMinutes(1));
                heartbeatChecker = heartbeatPacket.Subscribe(e => { }, e =>
                {
                    if (Server != null && Server.Player != null)
                    {
                        SharpStarLogger.DefaultLogger.Warn("Did not receive a heartbeat packet in a certain amount of time from player {0}. Kicking client!", Server.Player.Name);
                    }
                    else
                    {
                        SharpStarLogger.DefaultLogger.Warn("Did not receive a heartbeat packet in a certain amount of time. Kicking client!");
                    }

                    ForceDisconnect();

                    if (OtherClient != null)
                    {
                        OtherClient.ForceDisconnect();
                    }
                }, () => { });
            }

            bool willRaiseEvent = token.Socket.ReceiveAsync(readEventArgs);

            if (!willRaiseEvent)
            {
                await ProcessReceive(readEventArgs);
            }
        }
Ejemplo n.º 2
0
        public static bool OpenYS_Command_User_Kick_Method(Client ThisClient, CommandReader Command)
        {
            if (Command._CmdArguments.Count() < 1)
            {
                ThisClient.SendMessage("&eSpecify an IPAddress to kick.\n\nUse &a/ListUsers&e to get the IP.");
                return(false);
            }
            IPAddress output = IPAddress.None;

            if (!IPAddress.TryParse(Command._CmdArguments[0], out output))
            {
                ThisClient.SendMessage("&eFormat incorrect: Be sure you are using an IPAddress value!");
                return(false);
            }
            if (Clients
                .AllClients
                .Exclude(ThisClient)
                .Where(x => x.IsFakeClient())
                .Where(z => (z.YSFClient.Socket.RemoteEndPoint as IPEndPoint).Address.ToString() == output.ToString())
                .Count() == 0)
            {
                ThisClient.SendMessage("&eNo Client found with that IPAddress!");
                return(false);
            }
            foreach (Client OtherClient in Clients
                     .AllClients
                     .Exclude(ThisClient)
                     .Where(x => x.IsConnected())
                     .Where(z => (z.YSFClient.Socket.RemoteEndPoint as IPEndPoint).Address.ToString() == output.ToString()))
            {
                Clients.AllClients.Exclude(OtherClient).SendMessage("&c" + OtherClient.Username + "&c was kicked from the server.");
                OtherClient.SendMessage("You were kicked from the server.");
                OtherClient.Disconnect("Kicked from the Server by " + ThisClient.Username);
            }
            ThisClient.SendMessage("&eKicked all IP's matching &c" + output.ToString() + "&e.");
            return(true);
        }
Ejemplo n.º 3
0
    private static void RunClientWithServer(List <DeploymentContext> DeployContextList, string ServerLogFile, IProcessResult ServerProcess, string ClientApp, string ClientCmdLine, ERunOptions ClientRunFlags, string ClientLogFile, ProjectParams Params)
    {
        IProcessResult ClientProcess = null;
        var            OtherClients  = new List <IProcessResult>();

        bool   WelcomedCorrectly = false;
        int    NumClients        = Params.NumClients;
        string AllClientOutput   = "";
        int    LastAutoFailIndex = -1;

        if (Params.Unattended)
        {
            string LookFor = "Bringing up level for play took";
            if (Params.DedicatedServer)
            {
                LookFor = "Welcomed by server";
            }
            else if (Params.RunAutomationTest != "")
            {
                LookFor = "Automation Test Succeeded";
            }
            else if (Params.RunAutomationTests)
            {
                LookFor = "Automation Test Queue Empty";
            }
            {
                while (!FileExists(ServerLogFile) && !ServerProcess.HasExited)
                {
                    Log("Waiting for logging process to start...");
                    Thread.Sleep(2000);
                }
                Thread.Sleep(1000);

                string AllServerOutput = "";
                using (FileStream ProcessLog = File.Open(ServerLogFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    StreamReader LogReader    = new StreamReader(ProcessLog);
                    bool         bKeepReading = true;

                    FileStream   ClientProcessLog = null;
                    StreamReader ClientLogReader  = null;

                    // Read until the process has exited.
                    while (!ServerProcess.HasExited && bKeepReading)
                    {
                        while (!LogReader.EndOfStream && bKeepReading && ClientProcess == null)
                        {
                            string Output = LogReader.ReadToEnd();
                            if (!String.IsNullOrEmpty(Output))
                            {
                                AllServerOutput += Output;
                                if (ClientProcess == null &&
                                    (AllServerOutput.Contains("Game Engine Initialized") || AllServerOutput.Contains("Unreal Network File Server is ready")))
                                {
                                    Log("Starting Client for unattended test....");
                                    ClientProcess = Run(ClientApp, ClientCmdLine + " -testexit=\"" + LookFor + "\"", null, ClientRunFlags | ERunOptions.NoWaitForExit);
                                    //@todo no testing is done on these
                                    if (NumClients > 1 && NumClients < 9)
                                    {
                                        for (int i = 1; i < NumClients; i++)
                                        {
                                            Log("Starting Extra Client....");
                                            OtherClients.Add(Run(ClientApp, ClientCmdLine, null, ClientRunFlags | ERunOptions.NoWaitForExit));
                                        }
                                    }
                                    while (!FileExists(ClientLogFile) && !ClientProcess.HasExited)
                                    {
                                        Log("Waiting for client logging process to start...{0}", ClientLogFile);
                                        Thread.Sleep(2000);
                                    }
                                    if (!ClientProcess.HasExited)
                                    {
                                        Thread.Sleep(2000);
                                        Log("Client logging process started...{0}", ClientLogFile);
                                        ClientProcessLog = File.Open(ClientLogFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                                        ClientLogReader  = new StreamReader(ClientProcessLog);
                                    }
                                }
                                else if (ClientProcess == null && !ServerProcess.HasExited)
                                {
                                    Log("Waiting for server to start....");
                                    Thread.Sleep(2000);
                                }
                                if (ClientProcess != null && ClientProcess.HasExited)
                                {
                                    ServerProcess.StopProcess();
                                    throw new AutomationException("Client exited before we asked it to.");
                                }
                            }
                        }
                        if (ClientLogReader != null)
                        {
                            if (ClientProcess.HasExited)
                            {
                                ServerProcess.StopProcess();
                                throw new AutomationException("Client exited or closed the log before we asked it to.");
                            }
                            while (!ClientProcess.HasExited && !ServerProcess.HasExited && bKeepReading)
                            {
                                while (!ClientLogReader.EndOfStream && bKeepReading && !ServerProcess.HasExited && !ClientProcess.HasExited)
                                {
                                    string ClientOutput = ClientLogReader.ReadToEnd();
                                    if (!String.IsNullOrEmpty(ClientOutput))
                                    {
                                        AllClientOutput += ClientOutput;
                                        Console.Write(ClientOutput);

                                        if (AllClientOutput.LastIndexOf(LookFor) > AllClientOutput.IndexOf(LookFor))
                                        {
                                            if (Params.FakeClient)
                                            {
                                                Log("Welcomed by server or client loaded, lets wait ten minutes...");
                                                Thread.Sleep(60000 * 10);
                                            }
                                            else
                                            {
                                                Log("Welcomed by server or client loaded, lets wait 30 seconds...");
                                                Thread.Sleep(30000);
                                            }
                                            WelcomedCorrectly = true;
                                            bKeepReading      = false;
                                        }
                                        else if (Params.RunAutomationTests)
                                        {
                                            int FailIndex  = AllClientOutput.LastIndexOf("Automation Test Failed");
                                            int ParenIndex = AllClientOutput.LastIndexOf(")");
                                            if (FailIndex >= 0 && ParenIndex > FailIndex && FailIndex > LastAutoFailIndex)
                                            {
                                                string Tail            = AllClientOutput.Substring(FailIndex);
                                                int    CloseParenIndex = Tail.IndexOf(")");
                                                int    OpenParenIndex  = Tail.IndexOf("(");
                                                string Test            = "";
                                                if (OpenParenIndex >= 0 && CloseParenIndex > OpenParenIndex)
                                                {
                                                    Test = Tail.Substring(OpenParenIndex + 1, CloseParenIndex - OpenParenIndex - 1);
                                                    LogError("Automated test failed ({0}).", Test);
                                                    LastAutoFailIndex = FailIndex;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        else
        {
            LogFileReaderProcess(ServerLogFile, ServerProcess, (string Output) =>
            {
                bool bKeepReading = true;
                if (ClientProcess == null && !String.IsNullOrEmpty(Output))
                {
                    AllClientOutput += Output;
                    if (ClientProcess == null && (AllClientOutput.Contains("Game Engine Initialized") || AllClientOutput.Contains("Unreal Network File Server is ready")))
                    {
                        Log("Starting Client....");
                        var SC        = DeployContextList[0];
                        ClientProcess = SC.StageTargetPlatform.RunClient(ClientRunFlags | ERunOptions.NoWaitForExit, ClientApp, ClientCmdLine, Params);
//						ClientProcess = Run(ClientApp, ClientCmdLine, null, ClientRunFlags | ERunOptions.NoWaitForExit);
                        if (NumClients > 1 && NumClients < 9)
                        {
                            for (int i = 1; i < NumClients; i++)
                            {
                                Log("Starting Extra Client....");
                                IProcessResult NewClient = SC.StageTargetPlatform.RunClient(ClientRunFlags | ERunOptions.NoWaitForExit, ClientApp, ClientCmdLine, Params);
                                OtherClients.Add(NewClient);
                            }
                        }
                    }
                }
                else if (ClientProcess == null && !ServerProcess.HasExited)
                {
                    Log("Waiting for server to start....");
                    Thread.Sleep(2000);
                }

                if (String.IsNullOrEmpty(Output) == false)
                {
                    Console.Write(Output);
                }

                if (ClientProcess != null && ClientProcess.HasExited)
                {
                    Log("Client exited, stopping server....");
                    if (!GlobalCommandLine.NoKill)
                    {
                        ServerProcess.StopProcess();
                    }
                    bKeepReading = false;
                }

                return(bKeepReading);                // Keep reading
            });
        }
        Log("Server exited....");
        if (ClientProcess != null && !ClientProcess.HasExited)
        {
            ClientProcess.StopProcess();
        }
        foreach (var OtherClient in OtherClients)
        {
            if (OtherClient != null && !OtherClient.HasExited)
            {
                OtherClient.StopProcess();
            }
        }
        if (Params.Unattended)
        {
            if (!WelcomedCorrectly)
            {
                throw new AutomationException("Server or client exited before we asked it to.");
            }
        }
    }
Ejemplo n.º 4
0
 public static bool OpenYS_Command_Chat_ListUser_Method(Client ThisClient, CommandReader Command)
 {
     if (!ThisClient.IsConsole())
     {
         ThisClient.SendMessage("&aList of Users Online:    &e" + Clients.AllClients.Select(x => x.Username).ToList().ToStringList());
         return(true);
     }
     else
     {
         string output = "";
         foreach (Client OtherClient in Clients.AllClients)
         {
             if (OtherClient == null)
             {
                 continue;
             }
             if (OtherClient.IsFakeClient())
             {
                 continue;
             }
             if (output.Length > 0)
             {
                 output += "\n";
             }
             output += "&8[";
             if (OtherClient.Vehicle != null & OtherClient.Vehicle != Vehicles.NoVehicle)
             {
                 string vehiclestring = OtherClient.Vehicle.ID.ToString();
                 while (vehiclestring.Length < 5)
                 {
                     vehiclestring = " " + vehiclestring;
                 }
                 output += "&f" + vehiclestring.Substring(0, 5);
             }
             else
             {
                 output += "&7-----";
             }
             output += "&8] ";
             string uname = OtherClient.Username;
             if (uname.Length > 16)
             {
                 uname = uname.Substring(0, 16);
             }
             output += "&2" + uname;
             output += Strings.Repeat(" ", 17 - uname.Length);
             if (OtherClient.YSFClient.Socket == null)
             {
                 output += "&7<No IP Address Available>";
                 continue;
             }
             try
             {
                 IPEndPoint remoteIpEndPoint = OtherClient.YSFClient.Socket.RemoteEndPoint as IPEndPoint;
                 if (remoteIpEndPoint.Address.ToString().Count(x => x == '.') != 3 | remoteIpEndPoint.Address.IsIPv6Multicast)
                 {
                     output += "&7" + remoteIpEndPoint.Address.ToString();
                     continue;
                 }
                 string Byte0 = remoteIpEndPoint.Address.ToString().Split('.')[0];
                 string Byte1 = remoteIpEndPoint.Address.ToString().Split('.')[1];
                 string Byte2 = remoteIpEndPoint.Address.ToString().Split('.')[2];
                 string Byte3 = remoteIpEndPoint.Address.ToString().Split('.')[3];
                 //while (Byte0.Length < 3) Byte0 = "0" + Byte0;
                 //while (Byte1.Length < 3) Byte1 = "0" + Byte1;
                 //while (Byte2.Length < 3) Byte2 = "0" + Byte2;
                 //while (Byte3.Length < 3) Byte3 = "0" + Byte3;
                 output += "&8" + Byte0 + "." + Byte1 + "." + Byte2 + "." + Byte3;
             }
             catch
             {
                 output += "&7<Error Parsing IP Address>";
                 continue;
             }
         }
         if (output.Length == 0)
         {
             output = "&7<No users to list>";
         }
         Console.WriteLine(output);
         return(true);
     }
 }
Ejemplo n.º 5
0
        public bool Disconnect(string Reason)
        {
            lock (this)
            {
                if (IsDisconnecting())
                {
                    return(false);
                }
                if (IsDisconnected())
                {
                    return(false);
                }

                //Console.WriteLine(ConsoleColor.Red, Utilities.GetSourceCodePosition(1));
                if (IsFakeClient())
                {
                    return(true);
                }
                if (IsDisconnecting())
                {
                    Log.Warning("Disconnect() Called for Client: " + Username + ". Disconnecting Flag is Currently ON, A duplicate has occured and will be ignored.");
                    return(false);
                }
                if (IsDisconnected())
                {
                    Log.Warning("Disconnect() Called for Client: " + Username + ". Disconnect Flag is Currently ON, A duplicate has occured and will be ignored.");
                    return(false);
                }
                try
                {
                    if (YSFClient.Socket.Connected ||
                        (!YSFClient.Socket.Poll(1000, SelectMode.SelectRead) && YSFClient.Socket.Available != 0))
                    {
                        //The socket still exists!
                        //DO NOT DISCONNECT!

                        Log.Warning("Client " + Username + " Socket told to disconnect when it should not be disconnected? (Data Still Available?)");
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.ToString());
                }
                Log.Warning("Disconnect() Called for Client: " + Username + ". Disconnect Flag is Currently OFF, Setting to ON. (This is completely normal...)");
                Log.Warning("Disconnect() Reason: " + Reason);
                SetDisconnecting();
                #region Despawn Vehicle
                if (Vehicle != Vehicles.NoVehicle)
                {
                    //Need to tell all the other clients the vehicle is removed!
                    Packets.Packet_13_RemoveAirplane  RemoveAirplane   = new Packets.Packet_13_RemoveAirplane(Vehicle.ID);
                    Packets.Packet_06_Acknowledgement AcknowledgeLeave = new Packets.Packet_06_Acknowledgement(2, RemoveAirplane.ID);
                    foreach (Client OtherClient in Clients.AllClients.Exclude(this))
                    {
                        OtherClient.SendPacket(RemoveAirplane);
                        //OtherClient.GetPacket(AcknowledgeLeave);
                    }
                    if (Vehicle.VirtualCarrierObject_ID != 0)
                    {
                        Packets.Packet_19_RemoveGround RemoveVCO = new Packets.Packet_19_RemoveGround(Vehicle.VirtualCarrierObject_ID);
                        Clients.AllClients.Exclude(this).SendPacket(RemoveVCO);
                    }
                    Vehicles.List.RemoveAll(x => x == Vehicle);
                }
                #endregion
                Clients.RemoveClient(this); //remove self from the client list.
                #region Inform Players
                if ((this.Username == "nameless" & !this.ClientType.HasFlag(Client.FlagsClientType.YSFlightClient)) | this.IsBot())
                {
                    if (this.Username == "nameless")
                    {
                        if (Settings.Loading.BotPingMessages)
                        {
                            Console.WriteLine(ConsoleColor.Magenta, "Server was pinged by an unknown service.");
                        }
                    }
                    else if (this.IsBot())
                    {
                        if (Settings.Loading.BotPingMessages)
                        {
                            Console.WriteLine(ConsoleColor.Magenta, "Server was pinged by a serverlist.");
                        }
                    }
                }
                else
                {
                    foreach (Client OtherClient in Clients.AllClients.Exclude(this).ToArray())
                    {
                        OtherClient.SendMessage("&c" + Username + " left the server.");
                    }
                }
                #endregion
                #region Kill Client.
                try
                {
                    //lock (YSFClient.PacketWaiters)
                    //{
                    //    foreach (Connection.PacketWaiter ThisPacketWaiter in YSFClient.PacketWaiters.ToArray())
                    //    {
                    //        //force all listener threads to invalidate and cancel.
                    //        ThisPacketWaiter.Signal.Set();
                    //        ThisPacketWaiter.Signal.Dispose();
                    //    }
                    //}

                    //YSFClient.Disconnect();
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
                #endregion
                #region Kill Server.
                try
                {
                    //YSFServer.ReceiveThread.Abort();
                    //foreach (Connection.PacketWaiter ThisPacketWaiter in YSFServer.PacketWaiters.ToArray())
                    //{
                    //    //force all listener threads to invalidate and cancel.
                    //    ThisPacketWaiter.Signal.Set();
                    //    ThisPacketWaiter.Signal.Dispose();
                    //}

                    //YSFServer.Disconnect();
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
                #endregion
                //YSFClient.PacketLog.Log();
                StateConnection = Client.FlagsStateConnection.Disconnected;
                return(true);
            }
        }
Ejemplo n.º 6
0
        public static bool MicroTick()
        {
            #region DoWeather
            if (AdvancedWeatherOptions._Weather_Variable)
            {
                Packets.Packet_33_Weather TempWeather = AdvancedWeatherOptions.GetUpdatedWeather();
                TempWeather.Control_BlackOut       = false;
                TempWeather.Control_Collisions     = false;
                TempWeather.Control_LandEverywhere = false;
                Clients.AllClients.SendPacket(TempWeather);
            }
            #endregion
            #region DoHeartbeatMonitor
            Clients.DoHeartbeatMonitor();
            #endregion
            #region DoOnTickUpdateEvent
            lock (Events_OnMicroTickUpdate)
            {
                foreach (OnMicroTickUpdateEvent ThisMethod in Events_OnMicroTickUpdate)
                {
                    ThisMethod();
                }
            }
            #endregion

            #region CountThreads
            Thread[] _ThreadsArray;
            lock (Threads.List) _ThreadsArray = Threads.List.ToArray();
            foreach (Thread ThisThread in _ThreadsArray)
            {
                if (!ThisThread.IsAlive)
                {
                    //Log.Error("Thread killed as part of maintenance: " + ThisThread.Name);
                    Threads.List.RemoveAll(x => x == ThisThread);
                }
            }
            #endregion
            #region ManageVehicles
            Vehicle[] _VehiclesArray;
            lock (Vehicles.List) _VehiclesArray = Vehicles.List.ToArray();
            foreach (Vehicle ThisVehicle in _VehiclesArray)
            {
                if (Clients.Flying.Where(x => x.Vehicle == ThisVehicle).Count() < 1
                    & !ThisVehicle.IsVirtualVehicle)
                {
                    Vehicles.List.RemoveAll(x => x == ThisVehicle);
                    Packets.Packet_13_RemoveAirplane RemoveAirplane = new Packets.Packet_13_RemoveAirplane(ThisVehicle.ID);
                    foreach (Client OtherClient in Clients.AllClients)
                    {
                        Packets.Packet_06_Acknowledgement AcknowledgeLeave = new Packets.Packet_06_Acknowledgement(2, RemoveAirplane.ID);
                        //OtherClient.SendPacketGetPacket(RemoveAirplane, AcknowledgeLeave);
                        OtherClient.SendPacket(RemoveAirplane);
                    }
                    Console.WriteLine("&3Found a lost Vehicle... Cleaned it up!");
                    continue;
                }
                if (ThisVehicle.Invincible)
                {
                    Clients.LoggedIn.SendPacket(new Packets.Packet_30_AirCommand(ThisVehicle.ID, "STRENGTH", "255"));
                }
            }
            #endregion
            return(true);
        }
Ejemplo n.º 7
0
        private async Task ProcessReceive(SocketAsyncEventArgs e)
        {
            AsyncUserToken token = (AsyncUserToken)e.UserToken;

            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                PacketReader.NetworkBuffer = new ArraySegment <byte>(e.Buffer, e.Offset, e.BytesTransferred);

                var packets = PacketReader.UpdateBuffer(true);
                foreach (IPacket packet in packets)
                {
                    try
                    {
                        if (Server == null)
                        {
                            break;
                        }

                        EventHandler <PacketEventArgs> packetArgs = PacketReceived;
                        if (packetArgs != null)
                        {
                            packetArgs(this, new PacketEventArgs(this, packet));
                        }

                        var handlers = Server.PacketHandlers;

                        foreach (IPacketHandler handler in handlers)
                        {
                            if (packet.PacketId == handler.PacketId)
                            {
                                await handler.Handle(packet, this);
                            }
                        }

                        await SharpStarMain.Instance.PluginManager.CallEvent(packet, OtherClient);

                        if (!packet.Ignore && OtherClient != null)
                        {
                            await OtherClient.SendPacket(packet);
                        }

                        foreach (IPacketHandler handler in handlers)
                        {
                            if (packet.PacketId == handler.PacketId)
                            {
                                await handler.HandleAfter(packet, this);
                            }
                        }

                        EventHandler <PacketEventArgs> afterPacketArgs = AfterPacketReceived;
                        if (afterPacketArgs != null)
                        {
                            afterPacketArgs(this, new PacketEventArgs(this, packet));
                        }

                        await SharpStarMain.Instance.PluginManager.CallEvent(packet, OtherClient, true);
                    }
                    catch (Exception ex)
                    {
                        ex.LogError();
                    }
                }

                try
                {
                    bool willRaiseEvent = token.Socket.ReceiveAsync(e);

                    if (!willRaiseEvent)
                    {
                        await ProcessReceive(e);
                    }
                }
                catch
                {
                }
            }
            else
            {
                CloseClientSocket(e);
            }
        }
Ejemplo n.º 8
0
            private static bool Process_Type_08_JoinRequest(IConnection thisConnection, IPacket_08_JoinRequest packet)
            {
                #region Join Request Pending
                if (thisConnection.JoinRequestPending)
                {
                    Logger.Debug.AddWarningMessage("Join Request already pending for " + thisConnection.User.UserName.ToInternallyFormattedSystemString() + ".");
                    thisConnection.SendMessage("Issue with last join request. Cancelling last join request...");
                    IPacket_10_JoinRequestDenied JoinDenied = ObjectFactory.CreatePacket10JoinRequestDenied();
                    thisConnection.Send(JoinDenied);
                    thisConnection.JoinRequestPending = false;
                    return(true);
                }
                thisConnection.JoinRequestPending = true;
                #endregion

                #region Convert To JoinRequest
                IPacket_08_JoinRequest JoinRequest = ObjectFactory.CreatePacket08JoinRequest();
                JoinRequest.Data = packet.Data;
                #endregion

                #region Deny Requests if server is join locked!
                if (Settings.Flight.Join.Lock)
                {
                    //Reject the join request - don't have the start position requested!
                    IPacket_10_JoinRequestDenied JoinDenied = ObjectFactory.CreatePacket10JoinRequestDenied();
                    thisConnection.Send(JoinDenied);
                    thisConnection.SendMessage("Join request denied - Server is join locked!");
                    thisConnection.JoinRequestPending = false;
                    return(false);
                }
                #endregion

                #region Acknowledge Join Request
                //Acknowledge Join Request.
                IPacket_06_Acknowledgement AcknowledgeRequest = ObjectFactory.CreatePacket06Acknowledgement();
                AcknowledgeRequest.Arguments = new uint[] { 5, 0 };
                thisConnection.Send(AcknowledgeRequest);
                #endregion

                #region Check For Requested STP
                //Check if Server has STP - deny if it doesn't!
                if (!World.AllStartPositions.Select(x => x.Identify).Contains(JoinRequest.StartPositionIdentify))
                {
                    //Reject the join request - don't have the start position requested!
                    IPacket_10_JoinRequestDenied JoinDenied = ObjectFactory.CreatePacket10JoinRequestDenied();
                    thisConnection.Send(JoinDenied);
                    thisConnection.SendMessage("Join request denied - Server does not have that start position installed!");
                    thisConnection.JoinRequestPending = false;
                    return(false);
                }
                IWorldStartPosition StartPosition = World.AllStartPositions.First(x => x.Identify == JoinRequest.StartPositionIdentify);
                #endregion

                #region Check For Requested Aircraft
                IMetaDataAircraft MetaAircraft = MetaData.Aircraft.FindByName(JoinRequest.AircraftIdentify);
                if (MetaAircraft == MetaData.Aircraft.None)
                {
                    //Reject the join request - don't have the aircraft requested!
                    IPacket_10_JoinRequestDenied JoinDenied = ObjectFactory.CreatePacket10JoinRequestDenied();
                    thisConnection.Send(JoinDenied);
                    thisConnection.SendMessage("Join request denied - Server does not have that aircraft installed!");
                    thisConnection.JoinRequestPending = false;
                    return(false);
                }

                //TODO : Cache Aircraft!
                //CachedData.Aircraft CachedAircraft = MetaAircraft.Cache();
                #endregion

                #region Build EntityJoined(05)
                IPacket_05_AddVehicle EntityJoined = ObjectFactory.CreatePacket05AddVehicle();
                EntityJoined.VehicleType = Packet_05VehicleType.Aircraft;
                EntityJoined.Version     = 0;
                EntityJoined.ID          = World.GetNextID() | 256 * 256;
                EntityJoined.IFF         = JoinRequest.IFF;
                EntityJoined.PosX        = StartPosition.Position.X;
                EntityJoined.PosY        = StartPosition.Position.Y;
                EntityJoined.PosZ        = StartPosition.Position.Z;
                EntityJoined.HdgH        = StartPosition.Attitude.H;
                EntityJoined.HdgP        = StartPosition.Attitude.P;
                EntityJoined.HdgB        = StartPosition.Attitude.B;
                EntityJoined.Identify    = JoinRequest.AircraftIdentify;
                EntityJoined.OwnerName   = thisConnection.User.UserName.ToUnformattedSystemString();
                EntityJoined.OwnerType   = Packet_05OwnerType.Self;
                #endregion

                #region Build Flight Data Packet
                IPacket_11_FlightData FlightData = ObjectFactory.CreatePacket11FlightData(3);
                FlightData.ID = EntityJoined.ID;

                IDATFile CachedAircraft = ObjectFactory.CreateDATFileReference(Settings.YSFlight.Directory + MetaAircraft.Path_0_PropertiesFile);
                CachedAircraft.Load();

                FlightData.WeightFuel     = (CachedAircraft.CachedData.WeightOfFuel.ToKiloGrams().RawValue *(JoinRequest.FuelPercent)).KiloGrams();
                FlightData.WeightSmokeOil = 100.KiloGrams();
                FlightData.AmmoGUN        = CachedAircraft.CachedData.AmmoGun;
                if (!Settings.Options.AllowUnguidedWeapons)
                {
                    FlightData.AmmoGUN = 0;
                }
                FlightData.Strength     = CachedAircraft.CachedData.Strength;
                FlightData.AnimThrottle = StartPosition.Throttle;
                if (StartPosition.GearDown)
                {
                    FlightData.AnimGear = 1.0f;
                }
                FlightData.Timestamp = 0.Seconds().ToTime();
                FlightData.PosX      = EntityJoined.PosX;
                FlightData.PosY      = EntityJoined.PosY;
                FlightData.PosZ      = EntityJoined.PosZ;
                if (FlightData.PosY.ToMeters().RawValue < 1)
                {
                    FlightData.PosY = 1.Meters();
                }
                FlightData.HdgH   = EntityJoined.HdgH;
                FlightData.HdgP   = EntityJoined.HdgP;
                FlightData.HdgB   = EntityJoined.HdgB;
                FlightData.V_PosX = ((Math.Sin(-StartPosition.Attitude.H.ToRadians().RawValue) * (StartPosition.Speed.ToMetersPerSecond().RawValue))).MetersPerSecond();
                FlightData.V_PosZ = ((Math.Cos(-StartPosition.Attitude.H.ToRadians().RawValue) * (StartPosition.Speed.ToMetersPerSecond().RawValue))).MetersPerSecond();

                #region Turn on the brakes if Velocity == 0
                if (FlightData.V_PosX.ToMetersPerSecond().RawValue == 0 && FlightData.V_PosZ.ToMetersPerSecond().RawValue == 0 && Settings.Flight.Join.UseWheelChocks)
                {
                    FlightData.AnimBrake = 100;
                }
                #endregion
                #endregion

                #region Prepare Acknolwedgement Reponse.
                IPacketWaiter PacketWaiter_AcknowledgeJoinPacket = thisConnection.CreatePacketWaiter(6);
                if (EntityJoined.VehicleType == Packet_05VehicleType.Aircraft)
                {
                    PacketWaiter_AcknowledgeJoinPacket.Require(4, EntityJoined.ID);
                }
                else
                {
                    PacketWaiter_AcknowledgeJoinPacket.Require(0, 1);
                }
                PacketWaiter_AcknowledgeJoinPacket.StartListening();
                #endregion

                #region Assign Vehicle
                thisConnection.Vehicle          = ObjectFactory.CreateVehicle();
                thisConnection.Vehicle.Owner    = thisConnection.User;
                thisConnection.Vehicle.MetaData = MetaAircraft;
                #endregion

                #region Send Owner Join Data
                thisConnection.Vehicle.Update(EntityJoined);
                thisConnection.Vehicle.CreateVehicle();
                thisConnection.Send(EntityJoined);
                if (!thisConnection.GetResponseOrResend(PacketWaiter_AcknowledgeJoinPacket, EntityJoined))
                {
                    thisConnection.SendMessage("Expected an acknowledge Join Data Reply and didn't get an answer. Disconnecting...");
                    foreach (var thisConnectionLast5Packet in thisConnection.Last5Packets)
                    {
                        Logger.Debug.AddDetailMessage("&aIn Packet (" + thisConnectionLast5Packet.Type + ")\n" +
                                                      thisConnectionLast5Packet.Serialise().ToHexString() + "\n" +
                                                      thisConnectionLast5Packet.Serialise().ToSystemString());
                    }
                    //thisConnection.Disconnect();
                    //return false;
                }
                thisConnection.Vehicle.Update(FlightData);
                thisConnection.Send(FlightData);
                #endregion

                #region Send Owner Join Approved
                IPacket_09_JoinRequestApproved JoinApproved = ObjectFactory.CreatePacket09JoinRequestApproved();
                #region Prepare Acknowledgement Reponse.
                IPacketWaiter PacketWaiter_AcknowledgeJoinApproved = thisConnection.CreatePacketWaiter(6);
                PacketWaiter_AcknowledgeJoinApproved.Require(0, 6);
                PacketWaiter_AcknowledgeJoinApproved.StartListening();
                #endregion
                //thisConnection.SendGetPacket(JoinApproved, AcknowledgeJoinApproved);
                thisConnection.Send(JoinApproved);
                if (!thisConnection.GetResponseOrResend(PacketWaiter_AcknowledgeJoinApproved, JoinApproved))
                {
                    thisConnection.SendMessage("Expected an acknowledge Join Approval and didn't get an answer. Disconnecting...");
                    //thisConnection.Disconnect();
                    //return false;
                }
                thisConnection.JoinRequestPending = false;
                #endregion

                #region Send Others Join Data
                if (Settings.Flight.Join.Notification)
                {
                    Logger.Console.AddInformationMessage("&b" + thisConnection.User.UserName.ToInternallyFormattedSystemString() + "&b took off (" + EntityJoined.Identify + ")");
                }
                foreach (IConnection OtherClient in Connections.AllConnections.Exclude(thisConnection).ToArray())
                {
                    if (Settings.Flight.Join.Notification)
                    {
                        OtherClient.SendMessage(thisConnection.User.UserName.ToUnformattedSystemString() + " took off (" + EntityJoined.Identify + ")");
                    }

                    IPacket_05_AddVehicle OtherJoinPacket = ObjectFactory.CreatePacket05AddVehicle();
                    OtherJoinPacket.Data      = EntityJoined.Data;
                    OtherJoinPacket.OwnerType = Packet_05OwnerType.Other;

                    IPacketWaiter PacketWaiter_AcknowledgeOtherJoinPacket = thisConnection.CreatePacketWaiter(6);
                    if (EntityJoined.VehicleType == Packet_05VehicleType.Aircraft)
                    {
                        PacketWaiter_AcknowledgeOtherJoinPacket.Require(4, EntityJoined.ID);
                    }
                    else
                    {
                        PacketWaiter_AcknowledgeOtherJoinPacket.Require(0, 1);
                    }
                    PacketWaiter_AcknowledgeOtherJoinPacket.StartListening();
                    Logger.Console.AddInformationMessage("Sending Join Notification.");
                    OtherClient.Send(OtherJoinPacket);

                    if (!OtherClient.GetResponseOrResend(PacketWaiter_AcknowledgeOtherJoinPacket, OtherJoinPacket))
                    {
                        thisConnection.SendMessage("Expected a Other Entity Join Acknowldge for ID " + OtherJoinPacket.ID + " and didn't get an answer.");
                        //thisConnection.Disconnect();
                        //return false;
                    }
                    Logger.Console.AddInformationMessage("Sent Join Notification.");
                }
                #endregion
                return(true);
            }