Exemplo n.º 1
0
 private void serverstopbtn_Click(object sender, EventArgs e)
 {
     Server.Stop();
     Server.Dispose();
     Server = new ProcessHandler(ServerOutput, ServerLoc, this);
     ServerOutput.Clear();
 }
 public void Minecraft_OutputDataReceived(object sender, DataReceivedEventArgs e)
 {
     Dispatcher.Invoke((Action) delegate
     {
         ServerOutput.AppendText(e.Data + "\n");
         ServerOutput.ScrollToEnd();
     });
 }
Exemplo n.º 3
0
        private static void OnPeerDisconnected(Peer peer, DisconnectInfo info)
        {
            ServerOutput.Line($"Connection {peer.ConnectionID} disconnected with message {info.Reason}");

            Network.RemovePeer(peer);

            OnClientDisconnected?.Invoke(peer, info);
        }
Exemplo n.º 4
0
        private static void OnPeerConnected(Peer peer)
        {
            ServerOutput.Line($"Connection {peer.ConnectionID} received from {peer.EndPoint}");

            Network.AddPeer(peer);

            OnClientConnected?.Invoke(peer);
        }
Exemplo n.º 5
0
        public JoinFlow(Peer peer)
        {
            _peer = peer;

            ServerOutput.Header($"Starting joinflow for {peer}");

            PeerController.Create(peer);
        }
Exemplo n.º 6
0
 private void StopServer_Click(object sender, EventArgs e)
 {
     // If the server process is running, stop it
     if (StopServerNow())
     {
         ServerOutput.AppendLine("FXServer has been stopped by the user.");
     }
 }
Exemplo n.º 7
0
        private static void OnExpectedShutdown()
        {
            System.TimeSpan timeSpan = new System.TimeSpan(0, 0, (int)Time.time);

            ServerOutput.Header($"EXPECTED SHUTDOWN AFTER {timeSpan}");

            ControllerManager.Shutdown();
        }
Exemplo n.º 8
0
        public static void Remove(JoinFlow flow)
        {
            if (!_removalQueue.Contains(flow.Peer))
            {
                _removalQueue.Enqueue(flow.Peer);

                ServerOutput.Header($"Finished joinflow for {flow.Peer}");
            }
        }
Exemplo n.º 9
0
        static ControllerManager()
        {
            _listener   = new PackageEventListener();
            _netManager = new NetManager(_listener);
            _netManager.Start(Utility.IPC_PORT);

            ServerOutput.Line($"Started IPC server on {Utility.IPC_PORT}");

            CreateProcess();
        }
Exemplo n.º 10
0
        public static void HandlePingTest(int index, byte[] data)
        {
            PacketBuffer buffer = new PacketBuffer();

            try
            {
                buffer.Write(data);
                var packetNum = buffer.ReadInteger();
                ServerOutput.Compose(Outbound.PingTest, index);
            }
            catch (Exception e) { Console.WriteLine(e.Message); }
            finally { buffer.Dispose(); }
        }
Exemplo n.º 11
0
 private void AutoRestart_Tick(object sender, EventArgs e)
 {
     // If the current status is running but the process is not there
     if (ServerStatus == Status.Running && !ServerProcess.IsRunning() && Properties.Settings.Default.AutoRestart)
     {
         // Show the last exit code to the user
         // NOTE: This is always going to show 1
         ServerOutput.AppendLine("The server has crashed, exit code: " + ServerProcess.ExitCode);
         // Force a stop just in case
         StopServerNow();
         // Store the build and data folders
         string BuildFolder = Path.Combine(Builds, BuildList.SelectedItem.ToString());
         string DataFolder  = Path.Combine(Data, DataList.SelectedItem.ToString());
         // Start the server... again
         StartServerNow();
     }
 }
Exemplo n.º 12
0
        private static void AcceptCallback(IAsyncResult ar)
        {
            Socket socket = serverSocket.EndAccept(ar);

            serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);

            for (int i = 0; i < Log.MAX_PLAYERS; i++)
            {
                if (clients[i].socket == null)
                {
                    clients[i].socket = socket;
                    clients[i].index  = i;
                    clients[i].ip     = socket.RemoteEndPoint.ToString();
                    clients[i].StartClient();
                    Console.WriteLine("[ServerTCP] " + Log.SERVER_LOBBY_JOIN, i);
                    ServerOutput.Compose(Outbound.ConnectionOK, i);
                    return;
                }
            }
        }
Exemplo n.º 13
0
        private static void PollProcess()
        {
            if (_process == null)
            {
                ServerOutput.HeaderError("Unexpected shutdown of controller");

                if (Application.isEditor)
                {
                    Hooks.StopPlaying();
                }
                else
                {
                    Application.Quit();
                }
            }
            else if (_process.HasExited)
            {
                _process = null;
            }
        }
Exemplo n.º 14
0
        public void TestServerOutput()
        {
            //Test valid URL and Device
            //	to view correct POST:
            //		go to http://postcatcher.in/ and click "Start testing your POST requests now"
            //		copy the URL directly after "Content-Type: application/json" and replace the
            //		URL below (http://postcatcher.in/catchers/5536e135f9562d0300003e57) with the
            //		URL from postcatcher

            const string url    = "http://postcatcher.in/catchers/55439a9f51155a03000005a5";
            var          testSO = new ServerOutput(url);

            Assert.IsNotNull(testSO);
            Assert.IsTrue(url == testSO.getServerURL());

            testSO.write(new GarageDoor(null, null, null));

            Assert.IsNotNull(Encoding.UTF8.GetString(testSO.getData(), 0, testSO.getData().Length));
            Assert.IsNull(testSO.getURLException());

            //Test null URL
            const string nullURL       = null;
            var          testNullURLSO = new ServerOutput(nullURL);

            testNullURLSO.write(new AlarmSystem(null, null, null));

            Assert.IsNotNull(testNullURLSO.getURLException());
            Assert.IsNull(testNullURLSO.getStreamException());
            Assert.IsNull(testNullURLSO.getRequestException());

            //Test bad URL
            const string badURL       = "http://bkicia";
            var          testBadURLSO = new ServerOutput(badURL);

            testBadURLSO.write(new GarageDoor(null, null, null));

            Assert.IsNull(testBadURLSO.getURLException());
            //Assert.IsNotNull(testBadURLSO.getStreamException());
            Assert.IsNull(testBadURLSO.getRequestException());
        }
Exemplo n.º 15
0
        private void StartServerNow()
        {
            // Get the build and data folders
            string BuildFolder = Path.Combine(Builds, BuildList.SelectedItem.ToString());
            string DataFolder  = Path.Combine(Data, DataList.SelectedItem.ToString());

            // Lock both of the selectors
            LimitAvailableControls(true);
            // Set the parameters for launching the server process and capture the output
            ServerProcess = new Process();
            ServerProcess.StartInfo.FileName               = Path.Combine(BuildFolder, "FXServer.exe");
            ServerProcess.StartInfo.Arguments              = $"+set citizen_dir \"{BuildFolder}\\citizen\" +set sv_licenseKey {Properties.Settings.Default.License} +exec server.cfg";
            ServerProcess.StartInfo.WorkingDirectory       = DataFolder;
            ServerProcess.StartInfo.UseShellExecute        = false;
            ServerProcess.StartInfo.RedirectStandardError  = true;
            ServerProcess.StartInfo.RedirectStandardInput  = true;
            ServerProcess.StartInfo.RedirectStandardOutput = true;
            ServerProcess.StartInfo.CreateNoWindow         = true;
            ServerProcess.OutputDataReceived              += (S, A) => ServerOutput.Invoke(new Action(() => { if (!string.IsNullOrWhiteSpace(A.Data))
                                                                                                              {
                                                                                                                  ServerOutput.AppendLine(A.Data);
                                                                                                              }
                                                                                                      }));
            ServerProcess.Start();
            ServerProcess.BeginOutputReadLine();
            ServerProcess.BeginErrorReadLine();
            ServerStatus = Status.Running;

            // Try to get the RCON password
            string Config = File.ReadAllText(Path.Combine(DataFolder, "server.cfg"));
            Match  RCON   = Expressions.RCONPassword.Match(Config);
            Match  Port   = Expressions.PortUDP.Match(Config);

            // If both matches are successful
            if (RCON.Success && Port.Success)
            {
                // Do the work
            }
        }
Exemplo n.º 16
0
        public static bool Initialize()
        {
            try
            {
                ServerLog.Initialize();
                Network.ApplicationQuit += () => { OnSave?.Invoke(); };
                Session.Initialize();
                Instance.CreateServer();

                IsInitialized = true;

                ServerInitializer.Initialize();

                ServerOutput.Header("Successfully started server");
                return(true);
            }
            catch (System.Exception)
            {
                ServerOutput.HeaderError("Failed starting server");

                throw;
            }
        }
Exemplo n.º 17
0
        public void ReceiveDownloadRequest(List <System.Guid> toDownload)
        {
            ServerOutput.Line($"{Peer}: Download Request For {toDownload.Count} Mods");

            foreach (ModFile modFile in Server.LoadedModFiles)
            {
                if (toDownload.Contains(modFile.GUID))
                {
                    ServerOutput.Line($"Sending {modFile.GUID}");

                    _peer.SendReliableOrdered(new NetworkPackage(PackageIdentification.ModDownload, modFile));

                    toDownload.Remove(modFile.GUID);
                }
            }

            //This means the client has requested a mod we don't have
            if (toDownload.Count > 0)
            {
                ServerOutput.LineError($"{Peer}: Requested {toDownload.Count} mods we don't posess\n\n{string.Join("\n", toDownload)}\n");
            }

            SwitchState(State.SendObjectManifest);
        }
Exemplo n.º 18
0
        private void SwitchState(State newState)
        {
            ServerOutput.Line($"{_peer}: {newState}");

            _state = newState;
        }
Exemplo n.º 19
0
 private static void OnNetworkError(IPEndPoint endPoint, int socketErrorCode)
 {
     ServerOutput.Line($"Error ({socketErrorCode}) from {endPoint}");
 }
Exemplo n.º 20
0
        private async void StartServer_Click(object sender, EventArgs e)
        {
            // Check that the user has entered a FiveM license key
            if (string.IsNullOrWhiteSpace(Properties.Settings.Default.License))
            {
                ServerOutput.AppendLine("To start a server, go to the Settings menu and add a FiveM license.");
                return;
            }

            // And also check if there is no build selected, return
            if (BuildList.SelectedIndex == -1 || DataList.SelectedIndex == -1)
            {
                ServerOutput.AppendLine("You need to select a Build and a Server Data.");
                return;
            }

            // Store the path that we are going to use with the download origin and destination
            string BuildFolder      = Path.Combine(Builds, BuildList.SelectedItem.ToString());
            string DataFolder       = Path.Combine(Data, DataList.SelectedItem.ToString());
            Uri    DownloadOrigin   = new Uri(string.Format(DownloadUrl, BuildList.SelectedItem.ToString()));
            string DownloadLocation = Path.Combine(Builds, BuildList.SelectedItem.ToString() + ".zip");

            // Check if the FiveM build exists locally
            if (!Directory.Exists(BuildFolder))
            {
                // Looks like there is no build, notify the user
                ServerOutput.AppendLine("The build was not found locally, attempting a download...");
                // And download the file
                ServerOutput.AppendLine("The download for the file has started, check the Progress Bar.");
                await DownloadClient.DownloadFileTaskAsync(DownloadOrigin, DownloadLocation);

                // Wait until the file has been downloaded
                while (DownloadClient.IsBusy)
                {
                    await Task.Delay(0);
                }
                // Sanity check: Check if the folder already exists and delete it recursively
                if (Directory.Exists(BuildFolder))
                {
                    Directory.Delete(BuildFolder, true);
                }
                // Create the folder for the current build
                Directory.CreateDirectory(BuildFolder);
                // Notify the user about the extraction
                ServerOutput.AppendLine("The file was downloaded, extracting the content...");
                // And extract the files
                await Task.Run(() => ZipFile.ExtractToDirectory(DownloadLocation, BuildFolder));

                ServerOutput.AppendLine("The file has been extracted, no problems found.");
                // Finally, restore the progress bar status
                GeneralProgress.Value = 0;
            }

            // If the user wants to delete the cache folder and is there
            if (Directory.Exists(Path.Combine(DataFolder, "cache")) && Properties.Settings.Default.ClearCache)
            {
                // Remove it and notify the user
                Directory.Delete(Path.Combine(DataFolder, "cache"), true);
                ServerOutput.AppendLine("The 'cache' folder was present and it was removed.");
            }

            StartServerNow();
        }
Exemplo n.º 21
0
        private async void CreateServerData_Click(object sender, EventArgs e)
        {
            // Request for the name of the server data folder
            string DataName = Microsoft.VisualBasic.Interaction.InputBox("Insert the name for your server data folder:", "Server Data creator");

            // Check that is not null or empty, if it does return
            if (string.IsNullOrWhiteSpace(DataName))
            {
                ServerOutput.AppendLine("Looks like the name that you entered is not valid, or you closed the window.");
                return;
            }

            // Store the path
            string NewPath = Path.Combine(Data, DataName);

            // Make sure that the folder does not exists
            if (Directory.Exists(NewPath))
            {
                ServerOutput.AppendLine("The name that you just entered is already being used.");
                return;
            }

            // Lock both of the selectors to avoid unexpected behaviours
            LimitAvailableControls(true);

            // Check if the user wants to download the cfx-server-data repo
            if (Properties.Settings.Default.DownloadScripts)
            {
                // Store the location of the file
                string DataFile = Path.Combine(Data, "cfx-server-data.zip");
                // Notify the user about the download
                ServerOutput.AppendLine("Downloading the cfx-server-data repository...");
                // And start getting the file
                await DownloadClient.DownloadFileTaskAsync("https://github.com/citizenfx/cfx-server-data/archive/master.zip", DataFile);

                // Wait until the file has been downloaded
                while (DownloadClient.IsBusy)
                {
                    await Task.Delay(0);
                }
                // Notify the user about the extraction
                ServerOutput.AppendLine("The file was downloaded, extracting the content...");
                // And extract the files
                await Task.Run(() => ZipFile.ExtractToDirectory(DataFile, Data));

                ServerOutput.AppendLine("The file has been extracted, no problems found.");
                // Then, rename the folder to the one requested by the user
                Directory.Move(Path.Combine(Data, "cfx-server-data-master"), NewPath);
                // Delete the temporary file
                File.Delete(DataFile);
                // Finally, restore the progress bar status
                GeneralProgress.Value = 0;
            }
            else
            {
                // Create the directory for the server data
                Directory.CreateDirectory(NewPath);
                ServerOutput.AppendLine("New Server Data folder has been created.");
            }

            // Get the string and add a random rcon password to it
            string Config = string.Format(Encoding.UTF8.GetString(Properties.Resources.ServerTemplate), Tools.GenerateSecureString(16));

            // Then, write the file and notify the user
            File.WriteAllText(Path.Combine(NewPath, "server.cfg"), Config);
            ServerOutput.AppendLine("A Template for the new Server Data folder has been created.");

            // Finally, refresh the list of server data folders
            RefreshServerData();
            // And if the server is stopped, enable the selectors
            if (ServerStatus == Status.Stopped)
            {
                LimitAvailableControls(false);
            }
        }
Exemplo n.º 22
0
        public static void InitializeObjectReferenceManifest(IEnumerable <ModFile> mods)
        {
            ServerOutput.Line($"Initialize ObjectReferenceManifest with {mods.Count()} mods");

            ObjectReferenceManifest.Initialize(mods, x => ObjectReferenceManifest.ObjectReferenceData.CreateAsServer(x));
        }