// Done!
        private static void CommandTesterHelper(string s, EventHandler <MessageEventArgs> call)
        {
            // Vamos enviar isto!
            IList <AsyncDataEventArgs> data = FragmentAssyncDataCollection(ConvertToAssyncDataCollection(RandomSplit(s)));

            AsyncStreamReader ar = CreateAsyncStreamReader();
            MessengerReader   mr = new MessengerReader(ar);

            bool done = false;

            mr.MessageReceived += (o, e) =>
            {
                call.Invoke(o, e);
                done = true;
            };

            // Send data!
            for (int i = 0; i < data.Count; ++i)
            {
                ar.Invoke(data[i]);
            }

            int time = Environment.TickCount;

            while (done == false)
            {
                Thread.Sleep(20);
                if (Environment.TickCount - time > 2000)
                {
                    throw new AssertionException("Could not complete operation on time");
                }
            }
        }
        private void OpenConnection(Connection connection, string data, Action initializeCallback, Action<Exception> errorCallback)
        {
            var url = connection.Url + GetReceiveQueryString(connection, data);

            Action<HttpWebRequest> prepareRequest = PrepareRequest(connection);

            HttpHelper.GetAsync(url, request =>
            {
                prepareRequest(request);

                request.Accept = "text/event-stream";

                if (connection.MessageId != null)
                {
                    request.Headers["Last-Event-ID"] = connection.MessageId.ToString();
                }

            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    errorCallback(task.Exception);
                }
                else
                {
                    // Get the reseponse stream and read it for messages
                    var stream = task.Result.GetResponseStream();
                    var reader = new AsyncStreamReader(stream, connection, initializeCallback, errorCallback);
                    reader.StartReading();

                    // Set the reader for this connection
                    connection.Items[ReaderKey] = reader;
                }
            });
        }
Beispiel #3
0
        private void OpenConnection(Connection connection, string data, Action initializeCallback, Action <Exception> errorCallback)
        {
            var url = connection.Url + GetReceiveQueryString(connection, data);

            Action <HttpWebRequest> prepareRequest = PrepareRequest(connection);

            HttpHelper.GetAsync(url, request =>
            {
                prepareRequest(request);

                request.Accept = "text/event-stream";

                if (connection.MessageId != null)
                {
                    request.Headers["Last-Event-ID"] = connection.MessageId.ToString();
                }
            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    errorCallback(task.Exception);
                }
                else
                {
                    // Get the reseponse stream and read it for messages
                    var stream = task.Result.GetResponseStream();
                    var reader = new AsyncStreamReader(stream, connection, initializeCallback, errorCallback);
                    reader.StartReading();

                    // Set the reader for this connection
                    connection.Items[ReaderKey] = reader;
                }
            });
        }
Beispiel #4
0
        public static Task <string> ReadAsString(this IResponse response, Func <ArraySegment <byte>, bool> onChunk)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            var stream    = response.GetStream();
            var reader    = new AsyncStreamReader(stream);
            var result    = new StringBuilder();
            var resultTcs = new TaskCompletionSource <string>();

            reader.Data = buffer =>
            {
                if (onChunk(buffer))
                {
                    result.Append(Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count));
                }
            };

            reader.Closed = exception =>
            {
                response.Dispose();
                resultTcs.SetResult(result.ToString());
            };

            reader.Start();

            return(resultTcs.Task);
        }
 /// <summary>
 /// Create a set of readers to read the specified streams, handles are assigned
 /// based upon the index of each stream in the provided array.
 /// </summary>
 /// <param name="streams">Streams to read.</param>
 /// <param name="bufferSize">Size of the buffer to use to read each stream.</param>
 public static AsyncStreamReader[] CreateFromStreams(Stream[] streams, int bufferSize)
 {
     AsyncStreamReader[] readers = new AsyncStreamReader[streams.Length];
     for (int i = 0; i < streams.Length; i++)
     {
         readers[i] = new AsyncStreamReader(i, streams[i], bufferSize);
     }
     return(readers);
 }
Beispiel #6
0
        protected void OpenLisp()
        {
            // Close the lisp process if one has already
            // been started.
            CloseLisp();

            if (String.IsNullOrEmpty(this.LispPath))
            {
                throw new NullReferenceException("The Lisp Path cannot be empty or null.");
            }

            this.Scintilla.Text = String.Empty;

            try
            {
                // Redirect the output stream of the child process.
                this.lispProcess.StartInfo.UseShellExecute        = false;
                this.lispProcess.StartInfo.RedirectStandardOutput = true;
                this.lispProcess.StartInfo.RedirectStandardError  = true;
                this.lispProcess.StartInfo.RedirectStandardInput  = true;
                this.lispProcess.StartInfo.CreateNoWindow         = true;
                this.lispProcess.EnableRaisingEvents = true;
                this.lispProcess.Exited            += new EventHandler(lispProcess_Exited);
                this.lispProcess.ErrorDataReceived += new DataReceivedEventHandler(lispProcess_ErrorDataReceived);
                this.lispProcess.StartInfo.FileName = this.LispPath;

                // Start the child process.
                this.lispProcess.Start();

                this.stdInWriter  = this.lispProcess.StandardInput;
                this.stdOutReader = this.lispProcess.StandardOutput;

                this.output = new AsyncStreamReader(this.lispProcess, this.stdOutReader.BaseStream,
                                                    new UserCallBack(this.SetTextCallback), this.stdOutReader.CurrentEncoding);

                this.output.BeginRead();

                this.lispProcess.BeginErrorReadLine();

                started = true;
            }
            catch (Exception e)
            {
                this.Scintilla.InsertText("\r\nError starting REPL process.\r\n");
                this.Scintilla.InsertText(e.Message);

                throw e;
            }
        }
Beispiel #7
0
        private void btnBuildBackend_Click(object sender, EventArgs e)
        {
            Process          process = new Process();
            ProcessStartInfo psi     = new ProcessStartInfo {
                FileName               = "cmd.exe",
                Arguments              = "/C dotnet publish -c release -r ubuntu.18.04-x64",
                WorkingDirectory       = Program.config.BackendSourceDirectory,
                WindowStyle            = ProcessWindowStyle.Hidden,
                CreateNoWindow         = true,
                UseShellExecute        = false,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
            };

            process.StartInfo           = psi;
            process.EnableRaisingEvents = true;

            process.Exited += delegate {
                CleanWriteToLog("\n============================================================\n");
            };

            CleanWriteToLog("\n============================================================\r\nStarting Backend Build\r\n============================================================\n");

            process.Start();

            AsyncStreamReader standardOutput = new AsyncStreamReader(process.StandardOutput);
            AsyncStreamReader standardError  = new AsyncStreamReader(process.StandardError);

            standardOutput.DataReceived += (send, data) => {
                if (data != null)
                {
                    CleanWriteToLog(data);
                }
            };

            standardError.DataReceived += (send, data) => {
                if (data != null)
                {
                    CleanWriteToLog(data);
                }
            };


            standardOutput.Start();
            standardError.Start();
        }
Beispiel #8
0
        internal CouchContinuousChanges(DreamMessage aMessage, CouchChangeDelegate aCallback)
        {
            if (aMessage == null)
            {
                throw new ArgumentNullException("aMessage");
            }
            if (aCallback == null)
            {
                throw new ArgumentNullException("aCallback");
            }

            theReader = new AsyncStreamReader(aMessage.ToStream(), (x, y) => {
                if (!String.IsNullOrEmpty(y.Line))
                {
                    CouchChangeResult result = theSerializer.Deserialize(y.Line);
                    aCallback(this, result);
                }
            });
        }
Beispiel #9
0
            public AsyncServerStreamingCall <SimpleResponse> ServerStreamingMethodSync(SimpleRequest request, CallSettings callSettings)
            {
                CallTimes.Add(_scheduler.Clock.GetCurrentDateTimeUtc());
                CallSettingsReceived.Add(callSettings);
                var responseStream = new AsyncStreamReader <SimpleResponse>(new SimpleResponse {
                    Name = request.Name
                });
                var responseHeaders = Task.Run(async() =>
                {
                    await _scheduler.Delay(_callDuration, callSettings.CancellationToken.GetValueOrDefault());
                    if (_failuresToReturn > 0)
                    {
                        _failuresToReturn--;
                        throw new RpcException(new Status(_failureCode, "Bang"));
                    }
                    return(Metadata.Empty);
                });
                var response = new AsyncServerStreamingCall <SimpleResponse>(responseStream, responseHeaders, null, null, null);

                return(response);
            }
Beispiel #10
0
        private static void CallCLI(string name, string args)
        {
            UpdateConsoleOut($"> Starting {name} with {args}");
            UpdateConsoleOut($"{Environment.NewLine}");
            var procStartInfo = new ProcessStartInfo(name)
            {
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true,
                UseShellExecute        = false,
                Arguments = args
            };

            var proc = Process.Start(procStartInfo);

            var standardOutput = new AsyncStreamReader(proc.StandardOutput);
            var standardError  = new AsyncStreamReader(proc.StandardError);

            standardOutput.DataReceived += (sender, data) =>
            {
                UpdateConsoleOut(data);
            };

            standardError.DataReceived += (sender, data) =>
            {
                Log.StaticLog.AddEntry(LogEntry.ErrorEntry("CallCLI", $"Command [{name} {args}] resulted in ERROR"));
                UpdateConsoleOut(data);
            };

            standardOutput.Start();
            standardError.Start();

            Log.StaticLog.AddEntry(LogEntry.TraceEntry("CallCLI", $"command: {name} {args}"));
            proc.WaitForExit();
            proc.Close();
            UpdateConsoleOut($"{Environment.NewLine}");

            standardOutput.Stop();
            standardError.Stop();
        }
Beispiel #11
0
        /// <summary>
        /// Execute a command line tool.
        /// </summary>
        /// <param name="toolPath">Tool to execute.  On Windows, if the path to this tool contains
        /// single quotes (apostrophes) the tool will be executed via the shell.</param>
        /// <param name="arguments">String to pass to the tools' command line.</param>
        /// <param name="workingDirectory">Directory to execute the tool from.</param>
        /// <param name="envVars">Additional environment variables to set for the command.</param>
        /// <param name="ioHandler">Allows a caller to provide interactive input and also handle
        /// both output and error streams from a single delegate.  NOTE: This is ignored if
        /// shell execution is enabled.</param>
        /// <param name="useShellExecution">Execute the command via the shell.  This disables
        /// I/O redirection and causes a window to be popped up when the command is executed.
        /// This uses file redirection to retrieve the standard output stream.
        /// </param>
        /// <param name="stdoutRedirectionInShellMode">Enables stdout and stderr redirection when
        /// executing a command via the shell.  This requires:
        /// * cmd.exe (on Windows) or bash (on OSX / Linux) are in the path.
        /// * Arguments containing whitespace are quoted.</param>
        /// <returns>CommandLineTool result if successful, raises an exception if it's not
        /// possible to execute the tool.</returns>
        public static Result RunViaShell(
            string toolPath, string arguments, string workingDirectory = null,
            Dictionary <string, string> envVars = null,
            IOHandler ioHandler = null, bool useShellExecution = false,
            bool stdoutRedirectionInShellMode = true)
        {
            System.Text.Encoding inputEncoding  = Console.InputEncoding;
            System.Text.Encoding outputEncoding = Console.OutputEncoding;
            Console.InputEncoding  = System.Text.Encoding.UTF8;
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            // Mono 3.x on Windows can't execute tools with single quotes (apostrophes) in the path.
            // The following checks for this condition and forces shell execution of tools in these
            // paths which works fine as the shell tool should be in the system PATH.
            if (UnityEngine.RuntimePlatform.WindowsEditor == UnityEngine.Application.platform &&
                toolPath.Contains("\'"))
            {
                useShellExecution            = true;
                stdoutRedirectionInShellMode = true;
            }

            string stdoutFileName = null;
            string stderrFileName = null;

            if (useShellExecution && stdoutRedirectionInShellMode)
            {
                stdoutFileName = Path.GetTempFileName();
                stderrFileName = Path.GetTempFileName();
                string shellCmd;
                string shellArgPrefix;
                string shellArgPostfix;
                string escapedToolPath = toolPath;
                if (UnityEngine.RuntimePlatform.WindowsEditor == UnityEngine.Application.platform)
                {
                    shellCmd        = "cmd.exe";
                    shellArgPrefix  = "/c \"";
                    shellArgPostfix = "\"";
                }
                else
                {
                    shellCmd        = "bash";
                    shellArgPrefix  = "-l -c '";
                    shellArgPostfix = "'";
                    escapedToolPath = toolPath.Replace("'", "'\\''");
                }
                arguments = String.Format("{0}\"{1}\" {2} 1> {3} 2> {4}{5}", shellArgPrefix,
                                          escapedToolPath, arguments, stdoutFileName,
                                          stderrFileName, shellArgPostfix);
                toolPath = shellCmd;
            }

            Process process = new Process();

            process.StartInfo.UseShellExecute = useShellExecution;
            process.StartInfo.Arguments       = arguments;
            if (useShellExecution)
            {
                process.StartInfo.CreateNoWindow         = false;
                process.StartInfo.RedirectStandardOutput = false;
                process.StartInfo.RedirectStandardError  = false;
            }
            else
            {
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                if (envVars != null)
                {
                    foreach (var env in envVars)
                    {
                        process.StartInfo.EnvironmentVariables[env.Key] = env.Value;
                    }
                }
            }
            process.StartInfo.RedirectStandardInput = !useShellExecution && (ioHandler != null);
            process.StartInfo.FileName         = toolPath;
            process.StartInfo.WorkingDirectory = workingDirectory ?? Environment.CurrentDirectory;

            process.Start();

            // If an I/O handler was specified, call it with no data to provide a process and stdin
            // handle before output data is sent to it.
            if (ioHandler != null)
            {
                ioHandler(process, process.StandardInput, StreamData.Empty);
            }

            List <string>[] stdouterr = new List <string>[] {
                new List <string>(), new List <string>()
            };

            if (useShellExecution)
            {
                process.WaitForExit();
                if (stdoutRedirectionInShellMode)
                {
                    stdouterr[0].Add(File.ReadAllText(stdoutFileName));
                    stdouterr[1].Add(File.ReadAllText(stderrFileName));
                    File.Delete(stdoutFileName);
                    File.Delete(stderrFileName);
                }
            }
            else
            {
                AutoResetEvent complete = new AutoResetEvent(false);
                // Read raw output from the process.
                AsyncStreamReader[] readers = AsyncStreamReader.CreateFromStreams(
                    new Stream[] { process.StandardOutput.BaseStream,
                                   process.StandardError.BaseStream }, 1);
                new AsyncStreamReaderMultiplexer(
                    readers,
                    (StreamData data) => {
                    stdouterr[data.handle].Add(data.text);
                    if (ioHandler != null)
                    {
                        ioHandler(process, process.StandardInput, data);
                    }
                },
                    complete: () => { complete.Set(); });
                foreach (AsyncStreamReader reader in readers)
                {
                    reader.Start();
                }

                process.WaitForExit();
                // Wait for the reading threads to complete.
                complete.WaitOne();
            }

            Result result = new Result();

            result.stdout   = String.Join("", stdouterr[0].ToArray());
            result.stderr   = String.Join("", stdouterr[1].ToArray());
            result.exitCode = process.ExitCode;
            result.message  = FormatResultMessage(toolPath, arguments, result.stdout,
                                                  result.stderr, result.exitCode);
            Console.InputEncoding  = inputEncoding;
            Console.OutputEncoding = outputEncoding;
            return(result);
        }
        private void OpenConnection(Connection connection, string data, Action initializeCallback, Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnect = initializeCallback == null;

            var url = (reconnect ? connection.Url : connection.Url + "connect") + GetReceiveQueryString(connection, data);

            Action<HttpWebRequest> prepareRequest = PrepareRequest(connection);

            HttpHelper.GetAsync(url, request =>
            {
                prepareRequest(request);

                request.Accept = "text/event-stream";

            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    var exception = task.Exception.GetBaseException();
                    if (!IsRequestAborted(exception) &&
                        Interlocked.CompareExchange(ref connection._initializedCalled, 0, 0) == 0)
                    {
                        if (errorCallback != null)
                        {
                            errorCallback(exception);
                        }
                        else
                        {
                            // Raise the error event if we failed to reconnect
                            connection.OnError(exception);
                        }
                    }
                }
                else
                {
                    // Get the reseponse stream and read it for messages
                    var stream = task.Result.GetResponseStream();
                    var reader = new AsyncStreamReader(stream,
                                                       connection,
                                                       () =>
                                                       {
                                                           if (Interlocked.CompareExchange(ref connection._initializedCalled, 1, 0) == 0)
                                                           {
                                                               initializeCallback();
                                                           }
                                                       },
                                                       () =>
                                                       {
                                                           // Wait for a bit before reconnecting
                                                           Thread.Sleep(ReconnectDelay);

                                                           // Now attempt a reconnect
                                                           OpenConnection(connection, data, initializeCallback: null, errorCallback: null);
                                                       });
                    reader.StartReading();

                    // Set the reader for this connection
                    connection.Items[ReaderKey] = reader;
                }
            });

            if (initializeCallback != null)
            {
                TaskAsyncHelper.Delay(ConnectionTimeout).Then(() =>
                {
                    if (Interlocked.CompareExchange(ref connection._initializedCalled, 1, 0) == 0)
                    {
                        // Stop the connection
                        Stop(connection);

                        // Connection timeout occured
                        errorCallback(new TimeoutException());
                    }
                });
            }
        }
        /// <summary>
        /// Execute a command line tool.
        /// </summary>
        /// <param name="toolPath">Tool to execute.  On Windows, if the path to this tool contains
        /// single quotes (apostrophes) the tool will be executed via the shell.</param>
        /// <param name="arguments">String to pass to the tools' command line.</param>
        /// <param name="workingDirectory">Directory to execute the tool from.</param>
        /// <param name="envVars">Additional environment variables to set for the command.</param>
        /// <param name="ioHandler">Allows a caller to provide interactive input and also handle
        /// both output and error streams from a single delegate.  NOTE: This is ignored if
        /// shell execution is enabled.</param>
        /// <param name="useShellExecution">Execute the command via the shell.  This disables
        /// I/O redirection and causes a window to be popped up when the command is executed.
        /// This uses file redirection to retrieve the standard output stream.
        /// </param>
        /// <param name="stdoutRedirectionInShellMode">Enables stdout and stderr redirection when
        /// executing a command via the shell.  This requires:
        /// * cmd.exe (on Windows) or bash (on OSX / Linux) are in the path.
        /// * Arguments containing whitespace are quoted.</param>
        /// <returns>CommandLineTool result if successful, raises an exception if it's not
        /// possible to execute the tool.</returns>
        public static Result RunViaShell(
            string toolPath, string arguments, string workingDirectory = null,
            Dictionary <string, string> envVars = null,
            IOHandler ioHandler = null, bool useShellExecution = false,
            bool stdoutRedirectionInShellMode = true)
        {
            bool     consoleConfigurationWarning = false;
            Encoding inputEncoding  = Console.InputEncoding;
            Encoding outputEncoding = Console.OutputEncoding;

            // Android SDK manager requires the input encoding to be set to
            // UFT8 to pipe data to the tool.
            // Cocoapods requires the output encoding to be set to UTF8 to
            // retrieve output.
            try {
                var utf8Type = Encoding.UTF8.GetType();
                // Only compare the type of the encoding class since the configuration shouldn't
                // matter.
                if (inputEncoding.GetType() != utf8Type)
                {
                    Console.InputEncoding = Encoding.UTF8;
                }
                if (outputEncoding.GetType() != utf8Type)
                {
                    Console.OutputEncoding = Encoding.UTF8;
                }
            } catch (Exception e) {
                if (!displayedConsoleConfigurationWarning)
                {
                    UnityEngine.Debug.LogWarning(String.Format(
                                                     "Unable to set console input / output encoding from {0} & {1} to {2} " +
                                                     "(e.g en_US.UTF8-8). Some commands may fail. {3}",
                                                     inputEncoding, outputEncoding, Encoding.UTF8, e));
                    consoleConfigurationWarning = true;
                }
            }

            // Mono 3.x on Windows can't execute tools with single quotes (apostrophes) in the path.
            // The following checks for this condition and forces shell execution of tools in these
            // paths which works fine as the shell tool should be in the system PATH.
            if (UnityEngine.RuntimePlatform.WindowsEditor == UnityEngine.Application.platform &&
                toolPath.Contains("\'"))
            {
                useShellExecution            = true;
                stdoutRedirectionInShellMode = true;
            }
            else if (!(toolPath.StartsWith("\"") || toolPath.StartsWith("'")))
            {
                // If the path isn't quoted normalize separators.
                // Windows can't execute commands using POSIX paths.
                toolPath = FileUtils.NormalizePathSeparators(toolPath);
            }

            string stdoutFileName = null;
            string stderrFileName = null;

            if (useShellExecution && stdoutRedirectionInShellMode)
            {
                stdoutFileName = Path.GetTempFileName();
                stderrFileName = Path.GetTempFileName();
                string shellCmd;
                string shellArgPrefix;
                string shellArgPostfix;
                string escapedToolPath = toolPath;
                if (UnityEngine.RuntimePlatform.WindowsEditor == UnityEngine.Application.platform)
                {
                    shellCmd        = "cmd.exe";
                    shellArgPrefix  = "/c \"";
                    shellArgPostfix = "\"";
                }
                else
                {
                    shellCmd        = "bash";
                    shellArgPrefix  = "-l -c '";
                    shellArgPostfix = "'";
                    escapedToolPath = toolPath.Replace("'", "'\\''");
                }
                arguments = String.Format("{0}\"{1}\" {2} 1> {3} 2> {4}{5}", shellArgPrefix,
                                          escapedToolPath, arguments, stdoutFileName,
                                          stderrFileName, shellArgPostfix);
                toolPath = shellCmd;
            }

            Process process = new Process();

            process.StartInfo.UseShellExecute = useShellExecution;
            process.StartInfo.Arguments       = arguments;
            if (useShellExecution)
            {
                process.StartInfo.CreateNoWindow         = false;
                process.StartInfo.RedirectStandardOutput = false;
                process.StartInfo.RedirectStandardError  = false;
            }
            else
            {
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                if (envVars != null)
                {
                    foreach (var env in envVars)
                    {
                        process.StartInfo.EnvironmentVariables[env.Key] = env.Value;
                    }
                }
            }
            process.StartInfo.RedirectStandardInput = !useShellExecution && (ioHandler != null);
            process.StartInfo.FileName         = toolPath;
            process.StartInfo.WorkingDirectory = workingDirectory ?? Environment.CurrentDirectory;

            process.Start();

            // If an I/O handler was specified, call it with no data to provide a process and stdin
            // handle before output data is sent to it.
            if (ioHandler != null)
            {
                ioHandler(process, process.StandardInput, StreamData.Empty);
            }

            List <string>[] stdouterr = new List <string>[] {
                new List <string>(), new List <string>()
            };

            if (useShellExecution)
            {
                process.WaitForExit();
                if (stdoutRedirectionInShellMode)
                {
                    stdouterr[0].Add(File.ReadAllText(stdoutFileName));
                    stdouterr[1].Add(File.ReadAllText(stderrFileName));
                    File.Delete(stdoutFileName);
                    File.Delete(stderrFileName);
                }
            }
            else
            {
                AutoResetEvent complete = new AutoResetEvent(false);
                // Read raw output from the process.
                AsyncStreamReader[] readers = AsyncStreamReader.CreateFromStreams(
                    new Stream[] { process.StandardOutput.BaseStream,
                                   process.StandardError.BaseStream }, 1);
                new AsyncStreamReaderMultiplexer(
                    readers,
                    (StreamData data) => {
                    stdouterr[data.handle].Add(data.text);
                    if (ioHandler != null)
                    {
                        ioHandler(process, process.StandardInput, data);
                    }
                },
                    complete: () => { complete.Set(); });
                foreach (AsyncStreamReader reader in readers)
                {
                    reader.Start();
                }

                process.WaitForExit();
                // Wait for the reading threads to complete.
                complete.WaitOne();
            }

            Result result = new Result();

            result.stdout   = String.Join("", stdouterr[0].ToArray());
            result.stderr   = String.Join("", stdouterr[1].ToArray());
            result.exitCode = process.ExitCode;
            result.message  = FormatResultMessage(toolPath, arguments, result.stdout,
                                                  result.stderr, result.exitCode);
            try {
                if (Console.InputEncoding != inputEncoding)
                {
                    Console.InputEncoding = inputEncoding;
                }
                if (Console.OutputEncoding != outputEncoding)
                {
                    Console.OutputEncoding = outputEncoding;
                }
            } catch (Exception e) {
                if (!displayedConsoleConfigurationWarning)
                {
                    UnityEngine.Debug.LogWarning(String.Format(
                                                     "Unable to restore console input / output  encoding to {0} & {1}. {2}",
                                                     inputEncoding, outputEncoding, e));
                    consoleConfigurationWarning = true;
                }
            }
            if (consoleConfigurationWarning)
            {
                displayedConsoleConfigurationWarning = true;
            }
            return(result);
        }
        private void OpenConnection(IConnection connection, string data, bool reconnecting)
        {
            // If we're reconnecting add /connect to the url
            var url = reconnecting
                ? connection.Url
                : connection.Url + "connect";

            url += GetReceiveQueryStringWithGroups(connection, data);
            Debug.WriteLine(string.Format("SSE: GET {0}", url));

            HttpClient.Get(url, request =>
            {
                connection.PrepareRequest(request);
                request.Accept = "text/event-stream";
            }, true)
                .ContinueWith(task =>
                {
                    var response = task.Result;

                    if (response.Exception != null)
                    {
                        var exception = response.Exception.GetBaseException();

                        if (!IsRequestAborted(exception))
                        {
                            if (reconnecting)
                            {
                                // Only raise the error event if we failed to reconnect
                                connection.OnError(exception);
                            }
                        }

                        if (reconnecting)
                        {
                            // Retry
                            Reconnect(connection, data);
                        }
                    }
                    else
                    {
                        // Get the response stream and read it for messages
                        var stream = response.GetResponseStream();
                        var reader = new AsyncStreamReader(stream, connection, () =>
                        {
                            response.Close();
                            Reconnect(connection, data);
                        });

                        if (reconnecting)
                            // Raise the reconnect event if the connection comes back up
                            connection.OnReconnected();

                        reader.StartReading();

                        // Set the reader for this connection
                        connection.Items[ReaderKey] = reader;
                    }
                });
        }
Beispiel #15
0
        /// <summary>
        /// Execute a command line tool.
        /// </summary>
        /// <param name="toolPath">Tool to execute.</param>
        /// <param name="arguments">String to pass to the tools' command line.</param>
        /// <param name="workingDirectory">Directory to execute the tool from.</param>
        /// <param name="envVars">Additional environment variables to set for the command.</param>
        /// <param name="ioHandler">Allows a caller to provide interactive input and also handle
        /// both output and error streams from a single delegate.</param>
        /// <returns>CommandLineTool result if successful, raises an exception if it's not
        /// possible to execute the tool.</returns>
        public static Result Run(string toolPath, string arguments, string workingDirectory = null,
                                 Dictionary <string, string> envVars = null,
                                 IOHandler ioHandler = null)
        {
            System.Text.Encoding inputEncoding  = Console.InputEncoding;
            System.Text.Encoding outputEncoding = Console.OutputEncoding;
            Console.InputEncoding  = System.Text.Encoding.UTF8;
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            Process process = new Process();

            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.Arguments              = arguments;
            process.StartInfo.CreateNoWindow         = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            if (envVars != null)
            {
                foreach (var env in envVars)
                {
                    process.StartInfo.EnvironmentVariables[env.Key] = env.Value;
                }
            }
            process.StartInfo.RedirectStandardInput = (ioHandler != null);
            process.StartInfo.FileName         = toolPath;
            process.StartInfo.WorkingDirectory = workingDirectory ?? Environment.CurrentDirectory;

            process.Start();

            // If an I/O handler was specified, call it with no data to provide a process and stdin
            // handle before output data is sent to it.
            if (ioHandler != null)
            {
                ioHandler(process, process.StandardInput, StreamData.Empty);
            }

            AutoResetEvent complete = new AutoResetEvent(false);

            List <string>[] stdouterr = new List <string>[] { new List <string>(),
                                                              new List <string>() };
            // Read raw output from the process.
            AsyncStreamReader[] readers = AsyncStreamReader.CreateFromStreams(
                new Stream[] { process.StandardOutput.BaseStream,
                               process.StandardError.BaseStream }, 1);
            new AsyncStreamReaderMultiplexer(
                readers,
                (StreamData data) => {
                stdouterr[data.handle].Add(data.text);
                if (ioHandler != null)
                {
                    ioHandler(process, process.StandardInput, data);
                }
            },
                complete: () => { complete.Set(); });
            foreach (AsyncStreamReader reader in readers)
            {
                reader.Start();
            }

            process.WaitForExit();
            // Wait for the reading threads to complete.
            complete.WaitOne();

            Result result = new Result();

            result.stdout          = String.Join("", stdouterr[0].ToArray());
            result.stderr          = String.Join("", stdouterr[1].ToArray());
            result.exitCode        = process.ExitCode;
            Console.InputEncoding  = inputEncoding;
            Console.OutputEncoding = outputEncoding;
            return(result);
        }
Beispiel #16
0
        private static ProcessReturn ExecuteCommand(string args, string dir = "", string exe = "git.exe")
        {
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
              exe = Util.PathCombine(appPath, "Libraries", "git", "bin", exe);

              var startInfo = new ProcessStartInfo {
            FileName = exe,
            Arguments = args,
            CreateNoWindow = true,
            RedirectStandardError = true,
            RedirectStandardOutput = true,
            UseShellExecute = false,
            WorkingDirectory = dir
              };
              startInfo.EnvironmentVariables["HOME"] = Util.PathCombine(GetAppDataPath(), RestClient.Username);
              for (int i = 0; i < 3; i++) {
            var process = new Process {StartInfo = startInfo};
            process.Start();
            AsyncStreamReader stdout = new AsyncStreamReader(process.StandardOutput.BaseStream),
                          stderr = new AsyncStreamReader(process.StandardError.BaseStream);
            if (!process.WaitForExit(ProcessTimeout)) {
              return new ProcessReturn(-1, "", "Process timed out.");
            }
            string stdoutStr = stdout.GetData(), stderrStr = stderr.GetData();
            // Retry if the lock is in use.
            if (i == 2 || !stderrStr.Contains("index.lock")) {
              return new ProcessReturn(process.ExitCode, stdoutStr, stderrStr);
            }
            Thread.Sleep(100);
              }

              // should never actually happen
              return new ProcessReturn(-1, "", "");
        }
Beispiel #17
0
        static void Main(string[] args)
        {
            Console.WriteLine("FortniteLauncher made by ElLondiuh");
            if (!File.Exists(launcherExe) | !File.Exists(shippingExe) | !File.Exists(eacShippingExe))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[ERROR] Something is wrong with your Fortnite installation or can't find your installation");
                Thread.Sleep(3000);
                Environment.Exit(2);
            }
            Console.WriteLine("Do you want to authenticate? Y | N");
            if (Console.ReadKey().Key == ConsoleKey.Y)
            {
                Console.WriteLine("Authorization requiered:");
                token    = Auth.GetToken(Console.ReadLine());
                exchange = Auth.GetExchange(token);
                authType = "exchangecode";
            }

            //You don't really need to use the args for the launcher and the eac shipping but the EGL does that
            var launchArgs = $"-obfuscationid={obfuscationid} -AUTH_LOGIN=unused -AUTH_PASSWORD={exchange} -AUTH_TYPE={authType} -epicapp=Fortnite -epicenv=Prod -EpicPortal -noeac -nobe -fltoken=fdd9g715h4i20110dd40d7d3";

            // I launch FortniteLauncher and FortniteClient-Win64-Shipping_EAC and freeze them to bypass the protection
            _fnLauncher = new Process
            {
                StartInfo =
                {
                    FileName  = launcherExe,
                    Arguments = launchArgs
                }
            };
            _fnLauncher.Start();
            foreach (ProcessThread thread in _fnLauncher.Threads)
            {
                Win32.SuspendThread(Win32.OpenThread(0x0002, false, thread.Id));
            }

            _fnEacProcess = new Process
            {
                StartInfo =
                {
                    FileName  = eacShippingExe,
                    Arguments = launchArgs
                }
            };
            _fnEacProcess.Start();
            foreach (ProcessThread thread in _fnEacProcess.Threads)
            {
                Win32.SuspendThread(Win32.OpenThread(0x0002, false, thread.Id));
            }

            //AsyncStreamReaders and RedirectStandardOutput to have fortnite output in the console
            _fnProcess = new Process
            {
                StartInfo =
                {
                    FileName               = shippingExe,
                    Arguments              = launchArgs,
                    UseShellExecute        = false,
                    RedirectStandardOutput = true
                }
            };
            _fnProcess.Start();
            AsyncStreamReader asyncOutputReader = new AsyncStreamReader(_fnProcess.StandardOutput);

            asyncOutputReader.DataReceived += delegate(object sender, string data)
            {
                Console.WriteLine(data);
            };

            asyncOutputReader.Start();

            Injector.InjectDll(_fnProcess.Id, sslBypassDLL);

            //If the game is closed kill the launcher and the eac shipping
            _fnProcess.WaitForExit();
            _fnLauncher.Kill();
            _fnEacProcess.Kill();
        }
Beispiel #18
0
        public void Start()
        {
            if (IsRunning)
                throw new ApplicationException("already running.");

            _wasClosed = false;

            _process = new Process();
            _process.StartInfo.FileName = this.AppFileName;
            if (Arguments != null)
                _process.StartInfo.Arguments = Arguments;
            if (WorkingDirectory != null)
                _process.StartInfo.WorkingDirectory = WorkingDirectory;
            _process.StartInfo.RedirectStandardInput = true;
            _process.StartInfo.RedirectStandardOutput = ModeStdout != CommunicationMode.None;
            _process.StartInfo.RedirectStandardError = ModeStderr != CommunicationMode.None;
            _process.StartInfo.UseShellExecute = false;
            _process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            _process.StartInfo.CreateNoWindow = true;


            if (ModeStderr == CommunicationMode.None && ModeStdout == CommunicationMode.None)
            {
                _process.Exited += _process_Exited;
                _process.EnableRaisingEvents = true;
            }


            _process.Start();
            ProcessId = _process.Id;
            try { _process.PriorityClass = PriorityClass; }
            catch
            {
            }


            // Stderr
            if (ModeStderr != CommunicationMode.None)
            {
                _stderrReader = new AsyncStreamReader(_process.StandardError.BaseStream, BufferSizeStderr);
                _stderrReader.DataRead += _stderrReader_DataRead;
            }
            if (ModeStderr == CommunicationMode.Line)
            {
                _stderrLineReader = new AsyncLineReader(_stderrReader);
                if (Encoding != null) _stderrLineReader.Encoding = Encoding;
                _stderrLineReader.LineRead += _stderrLineReader_LineRead;
            }
            
            // Stdout
            if (ModeStdout != CommunicationMode.None)
            {
                _stdoutReader = new AsyncStreamReader(_process.StandardOutput.BaseStream, BufferSizeStdout);
                _stdoutReader.DataRead += _stdoutReader_DataRead;
            }
            if (ModeStdout == CommunicationMode.Line)
            {
                _stdoutLineReader = new AsyncLineReader(_stdoutReader);
                if (Encoding != null) _stdoutLineReader.Encoding = Encoding;
                _stdoutLineReader.LineRead += _stdoutLineReader_LineRead;
            }

            if (ModeStderr != CommunicationMode.None)
                _stderrReader.Begin();
            if (ModeStdout != CommunicationMode.None)
                _stdoutReader.Begin();

        }
Beispiel #19
0
        private void materialRaisedButtonLaunch_Click(object sender, EventArgs e)
        {
#if ONLINE
            if (CheckUpdates("Launch"))
            {
                // Check if we previously showed that we required an update.
                if (!_showedUpdate)
                {
                    var result = MessageBox.Show("You must update Aurora Launcher to launch Fortnite.", string.Empty,
                                                 MessageBoxButtons.OKCancel);

                    if (result == DialogResult.Cancel)
                    {
                        _showedUpdate = true;
                        return;
                    }
                }

                Process.Start(Build.LauncherUri);
                return;
            }
#endif

            if (string.IsNullOrEmpty(materialSingleLineTextFieldEmail.Text) || materialSingleLineTextFieldEmail.Text.Length < 3)
            {
                MessageBox.Show("Email cannot be empty or below 3 characters.", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!IsValidEmail(materialSingleLineTextFieldEmail.Text))
            {
                MessageBox.Show("Invalid Email, are you sure it's correct?", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(materialSingleLineTextFieldPassword.Text) || materialSingleLineTextFieldPassword.Text.Length < 3)
            {
                MessageBox.Show("Password cannot be empty or below 3 characters.", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // TODO: Fix this?
            if (materialSingleLineTextFieldPassword.Text.Contains(" "))
            {
                MessageBox.Show("Invalid Password, are you sure it's correct?", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Sigh...
            try
            {
                if (!IsValidPath(Configuration.InstallLocation))
                {
                    MessageBox.Show("Invalid installation path.", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch
            {
                MessageBox.Show("Invalid installation path.", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var clientPath = Path.Combine(Configuration.InstallLocation, $"FortniteGame\\Binaries\\Win64\\{Build.ClientExecutable}");
            if (!File.Exists(clientPath))
            {
                var text =
                    $"\"{clientPath}\" was not found, please make sure it exists." + "\n\n" +
                    "Did you set the Install Location correctly?" + "\n\n" +
                    "TIP: The Install Location must be set to a folder that contains 2 folders named \"Engine\" and \"FortniteGame\".";

                MessageBox.Show(text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var nativePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Build.LauncherNative);
            if (!File.Exists(nativePath))
            {
                var text =
                    $"\"{nativePath}\" was not found, please make sure it exists." + "\n\n" +
                    "Did you extract all files from the ZIP when you downloaded Aurora Launcher?" + "\n\n" +
                    $"TIP: \"{Build.LauncherNative}\" must be in the same directory as Aurora Launcher.";

                MessageBox.Show(text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var arguments = $"-AUTH_LOGIN={Configuration.Email} -AUTH_PASSWORD={Configuration.Password} -AUTH_TYPE=epic {Configuration.Arguments}";

            if (_clientAnticheat == 0) // None
            {
                arguments += $" {Build.ClientArguments} -noeac -nobe -fltoken=none";
            }
            else if (_clientAnticheat == 1) // BattlEye
            {
                arguments += $" {Build.ClientArguments} -noeac -fromfl=be -fltoken={Build.BeToken}";
            }
            else if (_clientAnticheat == 2) // EasyAntiCheat
            {
                arguments += $" {Build.ClientArguments} -nobe -fromfl=eac -fltoken={Build.EacToken}";
            }

            _clientProcess = new Process
            {
                StartInfo = new ProcessStartInfo(clientPath, arguments)
                {
                    UseShellExecute = false,

                    RedirectStandardOutput = true,

                    CreateNoWindow = false
                }
            };

            _clientProcess.Start();

#if !NATIVE
            // Allocate the console, for standard output.
            Win32.AllocConsole();

            // Setup an AsyncStreamReader, for standard output.
            var reader = new AsyncStreamReader(_clientProcess.StandardOutput);

            reader.ValueRecieved += delegate(object sender, string value)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write(value);
                Console.ForegroundColor = ConsoleColor.Gray;
            };

            reader.Start();
#else
            Helper.InjectDll(_clientProcess.Id, nativePath);
#endif // NATIVE
        }
        private void OpenConnection(IConnection connection,
            string data,
            Action initializeCallback,
            Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool _reconnecting = initializeCallback == null;
            string _url = (_reconnecting ? connection.Url : connection.Url + "connect");
            Action<IRequest> _prepareRequest = PrepareRequest(connection);
            EventSignal<IResponse> _signal;

            if (shouldUsePost(connection))
            {
                _url += GetReceiveQueryString(connection, data);
                Debug.WriteLine("ServerSentEventsTransport: POST {0}", _url);

                _signal = m_httpClient.PostAsync(
                    _url,
                    request =>
                    {
                        _prepareRequest(request);
                        request.Accept = "text/event-stream";
                    },
                    new Dictionary<string, string> { 
                    {
                        "groups", GetSerializedGroups(connection) } 
                    });
            }
            else
            {
                _url += GetReceiveQueryStringWithGroups(connection, data);
                Debug.WriteLine("ServerSentEventsTransport: GET {0}", _url);

                _signal = m_httpClient.GetAsync(
                    _url,
                    request =>
                    {
                        _prepareRequest(request);
                        request.Accept = "text/event-stream";
                    });
            }

            _signal.Finished += (sender, e) =>
            {
                if (e.Result.IsFaulted)
                {
                    Exception _exception = e.Result.Exception.GetBaseException();

                    if (!HttpBasedTransport.IsRequestAborted(_exception))
                    {
                        if (errorCallback != null &&
                            Interlocked.Exchange(ref m_initializedCalled, 1) == 0)
                            errorCallback(_exception);
                        else if (_reconnecting)
                            // Only raise the error event if we failed to reconnect
                            connection.OnError(_exception);
                    }

                    if (_reconnecting)
                    {
                        // Retry
                        Reconnect(connection, data);
                        return;
                    }
                }
                else
                {
                    // Get the reseponse stream and read it for messages
                    IResponse _response = e.Result;
                    Stream _stream = _response.GetResponseStream();
                    AsyncStreamReader _reader = new AsyncStreamReader(
                        _stream,
                        connection,
                        () =>
                        {
                            if (Interlocked.CompareExchange(ref m_initializedCalled, 1, 0) == 0)
                                initializeCallback();
                        },
                        () =>
                        {
                            _response.Close();
                            Reconnect(connection, data);
                        });

                    if (_reconnecting)
                        // Raise the reconnect event if the connection comes back up
                        connection.OnReconnected();

                    _reader.StartReading();

                    // Set the reader for this connection
                    connection.Items[m_readerKey] = _reader;
                }
            };

            if (initializeCallback != null)
            {
                int _tryed = 0;
                while (true)
                {
                    _tryed++;
                    Debug.WriteLine("Checking if connection initialized for the {0} time: ", _tryed.ToString());

                    Thread.Sleep(m_connectionTimeout);
                    if (Interlocked.CompareExchange(ref m_initializedCalled, 1, 0) == 0)
                    {
                        if (_tryed < m_connectionRetry)
                        {
                            Debug.WriteLine("Connection initialized failed after {0} times.", _tryed.ToString());
                            continue;
                        }

                        Debug.WriteLine("Giving up on connection initializing.");

                        // Stop the connection
                        Stop(connection);

                        // Connection timeout occurred
                        errorCallback(new TimeoutException());

                        break;
                    }
                    else
                    {
                        Debug.WriteLine("Connection initialized succeed.");
                        break;
                    }
                }
            }
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            string joinedArgs = string.Join(" ", args);

            // Check if -FORCECONSOLE exists in args (regardless of case) to force console (due to Epic Games Launcher by default hiding it)
            if (joinedArgs.ToUpper().Contains("-FORCECONSOLE"))
            {
                joinedArgs = Regex.Replace(joinedArgs, "-FORCECONSOLE", string.Empty, RegexOptions.IgnoreCase);
                new Process
                {
                    StartInfo =
                    {
                        FileName        = Path.GetFileName(Assembly.GetEntryAssembly().Location),
                        Arguments       = joinedArgs,
                        UseShellExecute = false
                    }
                }.Start();

                Environment.Exit(0);
            }

            // Check if the Fortnite client exists in the current work path.
            if (!File.Exists(FORTNITE_EXECUTABLE))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"\"{FORTNITE_EXECUTABLE}\" is missing!");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Check if -NOSSLPINNING exists in args (regardless of case) to disable SSL pinning
            if (joinedArgs.ToUpper().Contains("-NOSSLPINNING"))
            {
                joinedArgs           = Regex.Replace(joinedArgs, "-NOSSLPINNING", string.Empty, RegexOptions.IgnoreCase);
                Patcher.noSslPinning = true;
            }

            // Setup a process exit event handler
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);

            // Initialize Fortnite process with start info
            _fnProcess = new Process
            {
                StartInfo =
                {
                    FileName  = FORTNITE_EXECUTABLE,
                    Arguments = $"{joinedArgs} -noeac -nobe -fltoken=none",
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false
                }
            };

            _fnProcess.Start(); // Start Fortnite client process

            // Set up our async readers
            AsyncStreamReader asyncOutputReader = new AsyncStreamReader(_fnProcess.StandardOutput);
            AsyncStreamReader asyncErrorReader  = new AsyncStreamReader(_fnProcess.StandardError);

            asyncOutputReader.DataReceived += delegate(object sender, string data)
            {
                Console.ForegroundColor = ConsoleColor.White;

                string formattedData = data.ToUpper().Replace(" ", "_"); // Convert data to all uppercase characters and replace spaces with "_"

                // Check if formatted data contains "ASYNC_LOADING_INITIALIZED", if so, initalize the patcher (because we have to wait for Fortnite to be fully loaded into memory)
                if (formattedData.Contains("ASYNC_LOADING_INITIALIZED") && _fnPatcher == null)
                {
                    _fnPatcher = new Patcher(_fnProcess);
                }

                // Check if formatted data contains "STARTING_UPDATE_CHECK", if so, run the patcher (because Fortnite internal AC sucks!)
                if (formattedData.Contains("STARTING_UPDATE_CHECK") && _fnPatcher != null)
                {
                    _fnPatcher.Run();
                }

                Console.WriteLine(data);
            };

            asyncErrorReader.DataReceived += delegate(object sender, string data)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(data);
            };

            // Start our async readers
            asyncOutputReader.Start();
            asyncErrorReader.Start();

            _fnProcess.WaitForExit(); // We'll wait for the Fortnite process to exit, otherwise our launcher will just close instantly
        }
Beispiel #22
0
 /// <summary>
 /// Constructor for a STOMP 1.2 frame reader.
 /// </summary>
 /// <param name="stream">The stream to read from.</param>
 /// <param name="bufferCapacity">The read buffer size.</param>
 public Stomp12FrameReader(Stream stream, int? bufferCapacity = null)
 {
     _reader = new AsyncStreamReader(stream, Encoding.UTF8, bufferCapacity);
     _readerOwner = true;
 }
        private void OpenConnection(IConnection connection, string data, Action initializeCallback, Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnecting = initializeCallback == null;

            var url = (reconnecting ? connection.Url : connection.Url + "connect") + GetReceiveQueryString(connection, data);

            Action<IRequest> prepareRequest = PrepareRequest(connection);

            _httpClient.GetAsync(url, request =>
            {
                prepareRequest(request);

                request.Accept = "text/event-stream";

            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    var exception = task.Exception.GetBaseException();
                    if (!IsRequestAborted(exception))
                    {
                        if (errorCallback != null &&
                            Interlocked.Exchange(ref _initializedCalled, 1) == 0)
                        {
                            errorCallback(exception);
                        }
                        else if (reconnecting)
                        {
                            // Only raise the error event if we failed to reconnect
                            connection.OnError(exception);
                        }
                    }

                    if (reconnecting)
                    {
                        // Retry
                        Reconnect(connection, data);
                        return;
                    }
                }
                else
                {
                    // Get the reseponse stream and read it for messages
                    var response = task.Result;
                    var stream = response.GetResponseStream();
                    var reader = new AsyncStreamReader(stream,
                                                       connection,
                                                       () =>
                                                       {
                                                           if (Interlocked.CompareExchange(ref _initializedCalled, 1, 0) == 0)
                                                           {
                                                               initializeCallback();
                                                           }
                                                       },
                                                       () =>
                                                       {
                                                           response.Close();

                                                           Reconnect(connection, data);
                                                       });

                    if (reconnecting)
                    {
                        // Raise the reconnect event if the connection comes back up
                        connection.OnReconnected();
                    }

                    reader.StartReading();

                    // Set the reader for this connection
                    connection.Items[ReaderKey] = reader;
                }
            });

            if (initializeCallback != null)
            {
                TaskAsyncHelper.Delay(ConnectionTimeout).Then(() =>
                {
                    if (Interlocked.CompareExchange(ref _initializedCalled, 1, 0) == 0)
                    {
                        // Stop the connection
                        Stop(connection);

                        // Connection timeout occured
                        errorCallback(new TimeoutException());
                    }
                });
            }
        }
        private void OpenConnection(Connection connection, string data, Action initializeCallback, Action <Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnect = initializeCallback == null;

            var url = (reconnect ? connection.Url : connection.Url + "connect") + GetReceiveQueryString(connection, data);

            Action <HttpWebRequest> prepareRequest = PrepareRequest(connection);

            HttpHelper.GetAsync(url, request =>
            {
                prepareRequest(request);

                request.Accept = "text/event-stream";
            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    var exception = task.Exception.GetBaseException();
                    if (!IsRequestAborted(exception) &&
                        Interlocked.CompareExchange(ref connection._initializedCalled, 0, 0) == 0)
                    {
                        if (errorCallback != null)
                        {
                            errorCallback(exception);
                        }
                        else
                        {
                            // Raise the error event if we failed to reconnect
                            connection.OnError(exception);
                        }
                    }
                }
                else
                {
                    // Get the reseponse stream and read it for messages
                    var stream = task.Result.GetResponseStream();
                    var reader = new AsyncStreamReader(stream,
                                                       connection,
                                                       () =>
                    {
                        if (Interlocked.CompareExchange(ref connection._initializedCalled, 1, 0) == 0)
                        {
                            initializeCallback();
                        }
                    },
                                                       () =>
                    {
                        // Wait for a bit before reconnecting
                        Thread.Sleep(ReconnectDelay);

                        // Now attempt a reconnect
                        OpenConnection(connection, data, initializeCallback: null, errorCallback: null);
                    });
                    reader.StartReading();

                    // Set the reader for this connection
                    connection.Items[ReaderKey] = reader;
                }
            });

            if (initializeCallback != null)
            {
                TaskAsyncHelper.Delay(ConnectionTimeout).Then(() =>
                {
                    if (Interlocked.CompareExchange(ref connection._initializedCalled, 1, 0) == 0)
                    {
                        // Stop the connection
                        Stop(connection);

                        // Connection timeout occured
                        errorCallback(new TimeoutException());
                    }
                });
            }
        }
Beispiel #25
0
        /// <summary>
        /// Run Pscp synchronously
        /// </summary>
        /// <param name="result">Result object where results </param>
        /// <param name="args">The args to send to pscp</param>
        /// <param name="argsToLog">The args that are logged or can be returned in status messages</param>
        /// <param name="inlineOutHandler">Inline handler for output</param>
        /// <param name="inlineErrHandler">Inline handler for error</param>
        /// <param name="successOutHandler">Handler for output of successful operation</param>
        private void RunPscp(
            PscpResult result,
            string args,
            string argsToLog,
            Func <string, bool> inlineOutHandler,
            Func <string, bool> inlineErrHandler,
            Action <string[]> successOutHandler)
        {
            if (!File.Exists(this.Options.PscpLocation))
            {
                result.SetError(string.Format("Pscp missing, path={0}.", this.Options.PscpLocation), null);
            }
            else if (this.Session.Username == null)
            {
                result.SetError("UserName is null", null);
            }
            else if (this.Session.Host == null)
            {
                result.SetError("Host is null", null);
            }
            else if (this.Session.Port < 0)
            {
                result.SetError("Invalid port: " + this.Session.Port, null);
            }
            else
            {
                Process           proc         = NewProcess(this.Options.PscpLocation, args);
                Timer             timeoutTimer = null;
                AsyncStreamReader outReader    = null;
                AsyncStreamReader errReader    = null;
                try
                {
                    // Start pscp
                    Log.InfoFormat("Starting process: file={0}, args={1}", this.Options.PscpLocation, argsToLog);
                    proc.Start();

                    // Timeout when no output is received
                    timeoutTimer = new Timer(
                        (x) =>
                    {
                        // timeout
                        SafeKill(proc);
                        result.SetErrorFormat("Process timed out, args={0}", argsToLog);
                    },
                        null, this.Options.TimeoutMs, Timeout.Infinite);

                    // Async read output/err.  Inline actions to quick kill the process when pscp prompts user.
                    // NOTE: Using BeginReadOutput/ErrorReadLine doesn't work here.  Calls to read an empty stream
                    //       will block (e.g. "user's password:"******"OUT",
                        proc.StandardOutput,
                        strOut =>
                    {
                        bool keepReading = true;
                        bool completed   = false;
                        if (strOut == PUTTY_INTERACTIVE_AUTH || strOut.Contains("assword:"))
                        {
                            result.StatusCode = ResultStatusCode.RetryAuthentication;
                            Log.Debug("Username/Password invalid or not sent");
                            SafeKill(proc);
                            keepReading = false;
                        }
                        else if (inlineOutHandler != null)
                        {
                            completed = inlineOutHandler(strOut);
                        }
                        timeoutTimer.Change(completed ? Timeout.Infinite : this.Options.TimeoutMs, Timeout.Infinite);
                        return(keepReading);
                    });
                    errReader = new AsyncStreamReader(
                        "ERR",
                        proc.StandardError,
                        strErr =>
                    {
                        bool keepReading = true;
                        bool completed   = false;
                        if (strErr != null && strErr.Contains(PUTTY_NO_KEY))
                        {
                            result.SetError("Host key not cached.  Connect via putty to cache key then try again", null);
                            SafeKill(proc);
                            keepReading = false;
                        }
                        else if (inlineErrHandler != null)
                        {
                            completed = inlineErrHandler(strErr);
                        }
                        timeoutTimer.Change(completed ? Timeout.Infinite : this.Options.TimeoutMs, Timeout.Infinite);
                        return(keepReading);
                    });

                    // start process and wait for results
                    Log.DebugFormat("WaitingForExit");
                    proc.WaitForExit();

                    Log.InfoFormat("Process exited, pid={0}, exitCode={1}", proc.Id, proc.ExitCode);
                    timeoutTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    string[] output = outReader.StopAndGetData();
                    string[] err    = errReader.StopAndGetData();

                    string outputStr = String.Join("\r\n", output);
                    if (proc.ExitCode == 0 && outputStr.Contains(PUTTY_UNABLE_TO_OPEN))
                    {
                        // bad path
                        int idx = outputStr.IndexOf(PUTTY_UNABLE_TO_OPEN);
                        result.SetErrorFormat(outputStr.Substring(idx));
                    }
                    else if (proc.ExitCode == 0)
                    {
                        // successful operation
                        if (successOutHandler != null)
                        {
                            successOutHandler(output);
                        }
                    }
                    else
                    {
                        // some kind of error
                        if (result.StatusCode != ResultStatusCode.Success)
                        {
                            Log.Debug("Skipping output check since proactively killed process.");
                        }
                        else if (output.Contains(PUTTY_ARGUMENTS_HELP_HEADER))
                        {
                            result.SetErrorFormat("Invalid arguments sent to pscp, args={0}, output={1}", args, output);
                        }
                        else if (err.Contains(PUTTY_HOST_DOES_NOT_EXIST))
                        {
                            result.SetErrorFormat("Host does not exist.  {0}:{1}", this.Session.Host, this.Session.Port);
                        }
                        else
                        {
                            result.SetErrorFormat("Unknown error.  exitCode={0}, out='{1}', err='{2}'", proc.ExitCode, String.Join("|", output), String.Join("|", err));
                        }
                    }
                }
                finally
                {
                    SafeKill(proc);
                    SafeDispose(timeoutTimer, proc, outReader, errReader);
                }
            }
        }
Beispiel #26
0
 internal Stomp12FrameReader(AsyncStreamReader reader)
 {
     _reader = reader;
     _readerOwner = false;
 }
Beispiel #27
0
        public static RunOutput RunAndGetOutput([NotNull] string execName, string arguments, RunSettingsBase settings, WaitHandle awaitableHandle)
        {
            settings ??= RunSettingsBase.Default;
            settings.RedirectOutput = true;
            settings.RedirectError  = true;

            RunOutput output = new RunOutput();

            using (Process process = CreateForRun(execName, arguments, settings))
            {
                bool processReallyExited = false;

                process.Exited += (sender, _) =>
                {
                    Process p = (Process)sender;

                    if (p.IsAssociated())
                    {
                        try
                        {
                            output.ExitTime = p.ExitTime;
                            output.ExitCode = p.ExitCode;
                        }
                        catch
                        {
                            // ignored
                        }
                    }

                    processReallyExited = true;
                    settings.OnExit?.Invoke(execName, output.ExitTime, output.ExitCode);
                };

                try
                {
                    bool result = process.Start();
                    if (!result)
                    {
                        return(null);
                    }
                    if (!settings.JobHandle.IsInvalidHandle())
                    {
                        ProcessJob.AddProcess(settings.JobHandle, process);
                    }
                    output.StartTime = process.StartTime;
                    settings.OnStart?.Invoke(execName, output.StartTime);

                    AsyncStreamReader outputReader = new AsyncStreamReader(process, process.StandardOutput.BaseStream, data =>
                    {
                        if (data == null)
                        {
                            return;
                        }
                        output.Output.Append(data);
                        output.OutputBuilder.Append(data);
                    }, process.StandardOutput.CurrentEncoding);
                    outputReader.BeginRead();

                    AsyncStreamReader errorReader = new AsyncStreamReader(process, process.StandardError.BaseStream, data =>
                    {
                        if (data == null)
                        {
                            return;
                        }
                        output.Error.Append(data);
                        output.OutputBuilder.Append(data);
                    }, process.StandardOutput.CurrentEncoding);
                    errorReader.BeginRead();

                    if (!awaitableHandle.IsAwaitable())
                    {
                        process.WaitForExit();
                        return(output);
                    }

                    SafeWaitHandle   waitHandle           = null;
                    ManualResetEvent processFinishedEvent = null;

                    try
                    {
                        waitHandle = new SafeWaitHandle(process.Handle, false);
                        if (!waitHandle.IsAwaitable())
                        {
                            return(null);
                        }
                        processFinishedEvent = new ManualResetEvent(false)
                        {
                            SafeWaitHandle = waitHandle
                        };
                        if (!awaitableHandle.IsAwaitable())
                        {
                            return(null);
                        }

                        WaitHandle[] waitHandles =
                        {
                            processFinishedEvent,
                            awaitableHandle
                        };

                        int ndx = waitHandles.WaitAny();
                        if (ndx != 0)
                        {
                            return(null);
                        }

                        if (!processReallyExited && process.IsAwaitable())
                        {
                            if (!process.WaitForExit(TimeSpanHelper.HALF))
                            {
                                ndx = -1;
                            }
                        }

                        process.Die();
                        return(ndx != 0 ? null : output);
                    }
                    finally
                    {
                        processFinishedEvent?.Close();
                        ObjectHelper.Dispose(ref processFinishedEvent);
                        waitHandle?.Close();
                        ObjectHelper.Dispose(ref waitHandle);
                    }
                }
                catch (Win32Exception e)
                {
                    throw new InvalidOperationException(e.CollectMessages(), e);
                }
            }
        }
Beispiel #28
0
        static void Main(string[] args)
        {
            var formattedArguments = string.Join(" ", args);

#if GUI
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Gui(formattedArguments));
#else
            // Check if -FORCEBE exists in args (regardless of case) to force BattlEye.
            if (formattedArguments.ToUpper().Contains("-FORCEBE"))
            {
                formattedArguments = Regex.Replace(formattedArguments, "-FORCEBE", string.Empty, RegexOptions.IgnoreCase);

                _clientAnticheat = 1;
            }

            // Check if -FORCEEAC exists in args (regardless of case) to force EasyAntiCheat.
            if (formattedArguments.ToUpper().Contains("-FORCEEAC"))
            {
                formattedArguments = Regex.Replace(formattedArguments, "-FORCEEAC", string.Empty, RegexOptions.IgnoreCase);

                _clientAnticheat = 2;
            }

            if (_clientAnticheat == 0) // None
            {
                formattedArguments += $" {Build.ClientArguments} -noeac -nobe -fltoken=none";
            }
            else if (_clientAnticheat == 1) // BattlEye
            {
                formattedArguments += $" {Build.ClientArguments} -noeac -fromfl=be -fltoken={Build.BeToken}";
            }
            else if (_clientAnticheat == 2) // EasyAntiCheat
            {
                formattedArguments += $" {Build.ClientArguments} -nobe -fromfl=eac -fltoken={Build.EacToken}";
            }

#if !NATIVE
            Win32.AllocConsole();
#endif // NATIVE

            // Check if the client exists in the current work path, if it doesn't, just exit.
            if (!File.Exists(Build.ClientExecutable))
            {
#if NATIVE
                Win32.AllocConsole();
#endif // NATIVE

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"\"{Build.ClientExecutable}\" was not found, please make sure it exists.");
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.ReadKey();

                return;
            }

#if NATIVE
            // Check if the native exists in the current work path, if it doesn't, just exit.
            if (!File.Exists(Build.ClientNative))
            {
                Win32.AllocConsole();

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"\"{Build.ClientNative}\" was not found, please make sure it exists.");
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.ReadKey();

                return;
            }
#endif // NATIVE

#if !NATIVE
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("Aurora, made with <3 by Cyuubi and Slushia.");
            Console.WriteLine("Discord: https://discord.gg/aurorafn\n");
            Console.ForegroundColor = ConsoleColor.Gray;
#endif // NATIVE

            _clientProcess = new Process
            {
                StartInfo = new ProcessStartInfo(Build.ClientExecutable, formattedArguments)
                {
                    UseShellExecute = false,

                    RedirectStandardOutput = true,

                    CreateNoWindow = false
                }
            };

#if !NO_EGL
            Swap(); // Swap the launcher, to prevent Fortnite from detecting it.
#endif // NO_EGL

            _clientProcess.Start();

#if !NATIVE
            // Setup a HandlerRoutine, for detecting when the console closes.
            Win32.SetConsoleCtrlHandler(new Win32.HandlerRoutine(Routine), true);

            // Setup an AsyncStreamReader, for standard output.
            var reader = new AsyncStreamReader(_clientProcess.StandardOutput);

            reader.ValueRecieved += delegate(object sender, string value)
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write(value);
                Console.ForegroundColor = ConsoleColor.Gray;
            };

            reader.Start();
#else
            Helper.InjectDll(_clientProcess.Id, Build.ClientNative);
#endif // NATIVE

            _clientProcess.WaitForExit(); // Wait for the client process to exit.

#if !NO_EGL
            Swap(); // Before exiting... Swap the launcher, again.
#endif // NO_EGL
#endif // GUI
        }
Beispiel #29
0
        /// <summary>
        /// Run Pscp synchronously
        /// </summary>
        /// <param name="result">Result object where results </param>
        /// <param name="args">The args to send to pscp</param>
        /// <param name="argsToLog">The args that are logged or can be returned in status messages</param>
        /// <param name="inlineOutHandler">Inline handler for output</param>
        /// <param name="inlineErrHandler">Inline handler for error</param>
        /// <param name="successOutHandler">Handler for output of successful operation</param>
        private void RunPscp(
            PscpResult result,
            string args,
            string argsToLog,
            Func <string, bool> inlineOutHandler,
            Func <string, bool> inlineErrHandler,
            Action <string[]> successOutHandler)
        {
            if (!File.Exists(Options.PscpLocation))
            {
                result.SetError(string.Format(LocalizedText.PscpClient_RunPscp_Pscp_missing, Options.PscpLocation), null);
            }
            else if (Session.Username == null)
            {
                result.SetError(LocalizedText.PscpClient_RunPscp_UserName_is_null, null);
            }
            else if (Session.Host == null)
            {
                result.SetError(LocalizedText.PscpClient_RunPscp_Host_is_null, null);
            }
            else if (Session.Port < 0)
            {
                result.SetError(string.Format(LocalizedText.PscpClient_RunPscp_Invalid_port, Session.Port), null);
            }
            else
            {
                Process           proc         = NewProcess(Options.PscpLocation, args);
                Timer             timeoutTimer = null;
                AsyncStreamReader outReader    = null;
                AsyncStreamReader errReader    = null;
                try
                {
                    // Start pscp
                    Log.InfoFormat("Starting process: file={0}, args={1}", Options.PscpLocation, argsToLog);
                    proc.Start();

                    // Timeout when no output is received
                    timeoutTimer = new Timer(
                        (x) =>
                    {
                        // timeout
                        SafeKill(proc);
                        result.SetErrorFormat(LocalizedText.PscpClient_RunPscp_Process_timed_out, argsToLog);
                    },
                        null, Options.TimeoutMs, Timeout.Infinite);

                    // Async read output/err.  Inline actions to quick kill the process when pscp prompts user.
                    // NOTE: Using BeginReadOutput/ErrorReadLine doesn't work here.  Calls to read an empty stream
                    //       will block (e.g. "user's password:"******"OUT",
                        proc.StandardOutput,
                        strOut =>
                    {
                        bool keepReading = true;
                        bool completed   = false;
                        if (strOut == PuttyInteractiveAuth || strOut.Contains("assword:"))
                        {
                            result.StatusCode = ResultStatusCode.RetryAuthentication;
                            Log.Debug("Username/Password invalid or not sent");
                            SafeKill(proc);
                            keepReading = false;
                        }
                        else if (inlineOutHandler != null)
                        {
                            completed = inlineOutHandler(strOut);
                        }
                        timeoutTimer.Change(completed ? Timeout.Infinite : Options.TimeoutMs, Timeout.Infinite);
                        return(keepReading);
                    });
                    errReader = new AsyncStreamReader(
                        "ERR",
                        proc.StandardError,
                        strErr =>
                    {
                        bool keepReading = true;
                        bool completed   = false;
                        if (strErr != null && strErr.Contains(PuttyNoKey))
                        {
                            result.SetError("Host key not cached.  Connect via putty to cache key then try again", null);
                            SafeKill(proc);
                            keepReading = false;
                        }
                        else if (inlineErrHandler != null)
                        {
                            completed = inlineErrHandler(strErr);
                        }
                        timeoutTimer.Change(completed ? Timeout.Infinite : Options.TimeoutMs, Timeout.Infinite);
                        return(keepReading);
                    });

                    // start process and wait for results
                    Log.DebugFormat("WaitingForExit");
                    proc.WaitForExit();

                    Log.InfoFormat("Process exited, pid={0}, exitCode={1}", proc.Id, proc.ExitCode);
                    timeoutTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    string[] output = outReader.StopAndGetData();
                    string[] err    = errReader.StopAndGetData();

                    string outputStr = String.Join("\r\n", output);
                    if (proc.ExitCode == 0 && outputStr.Contains(PuttyUnableToOpen))
                    {
                        // bad path
                        int idx = outputStr.IndexOf(PuttyUnableToOpen, StringComparison.Ordinal);
                        result.SetErrorFormat(outputStr.Substring(idx));
                    }
                    else if (proc.ExitCode == 0)
                    {
                        // successful operation
                        successOutHandler?.Invoke(output);
                    }
                    else
                    {
                        // some kind of error
                        if (result.StatusCode != ResultStatusCode.Success)
                        {
                            Log.Debug("Skipping output check since proactively killed process.");
                        }
                        else if (output.Contains(PuttyArgumentsHelpHeader))
                        {
                            result.SetErrorFormat("Invalid arguments sent to pscp, args={0}, output={1}", args, output);
                        }
                        else if (err.Contains(PuttyHostDoesNotExist))
                        {
                            result.SetErrorFormat("Host does not exist.  {0}:{1}", Session.Host, Session.Port);
                        }
                        else
                        {
                            result.SetErrorFormat("Unknown error.  exitCode={0}, out='{1}', err='{2}'", proc.ExitCode, String.Join("|", output), String.Join("|", err));
                        }
                    }
                }
                finally
                {
                    SafeKill(proc);
                    SafeDispose(timeoutTimer, proc, outReader, errReader);
                }
            }
        }
        private void OpenConnection(IConnection connection, string data, dotnet2::System.Action initializeCallback, Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnecting = initializeCallback == null;

            var url = (reconnecting ? connection.Url : connection.Url + "connect");

            Action<IRequest> prepareRequest = PrepareRequest(connection);

            EventSignal<IResponse> signal;

            if (shouldUsePost(connection))
            {
                url += GetReceiveQueryString(connection, data);

                Debug.WriteLine(string.Format("SSE: POST {0}", url));

                signal = _httpClient.PostAsync(url, request =>
                                                        {
                                                            prepareRequest(request);
                                                            request.Accept = "text/event-stream";
                                                        }, new Dictionary<string, string> {{"groups", GetSerializedGroups(connection)}});
            }
            else
            {
                url += GetReceiveQueryStringWithGroups(connection, data);

                Debug.WriteLine(string.Format("SSE: GET {0}", url));

                signal = _httpClient.GetAsync(url, request =>
                {
                    prepareRequest(request);

                    request.Accept = "text/event-stream";
                });
            }

            signal.Finished += (sender,e)=> {
                if (e.Result.IsFaulted)
                {
                    var exception = e.Result.Exception.GetBaseException();
                    if (!IsRequestAborted(exception))
                    {
                        if (errorCallback != null &&
                            Interlocked.Exchange(ref _initializedCalled, 1) == 0)
                        {
                            errorCallback(exception);
                        }
                        else if (reconnecting)
                        {
                            // Only raise the error event if we failed to reconnect
                            connection.OnError(exception);
                        }
                    }

                    if (reconnecting)
                    {
                        // Retry
                        Reconnect(connection, data);
                        return;
                    }
                }
                else
                {
                    // Get the reseponse stream and read it for messages
                    var response = e.Result;
                    var stream = response.GetResponseStream();
                    var reader = new AsyncStreamReader(stream,
                                                       connection,
                                                       () =>
                                                       {
                                                           if (Interlocked.CompareExchange(ref _initializedCalled, 1, 0) == 0)
                                                           {
                                                               initializeCallback();
                                                           }
                                                       },
                                                       () =>
                                                       {
                                                           response.Close();

                                                           Reconnect(connection, data);
                                                       });

                    if (reconnecting)
                    {
                        // Raise the reconnect event if the connection comes back up
                        connection.OnReconnected();
                    }

                    reader.StartReading();

                    // Set the reader for this connection
                    connection.Items[ReaderKey] = reader;
                }
            };

            if (initializeCallback != null)
            {
                Thread.Sleep(ConnectionTimeout);
                if (Interlocked.CompareExchange(ref _initializedCalled, 1, 0) == 0)
                {
                    // Stop the connection
                    Stop(connection);

                    // Connection timeout occured
                    errorCallback(new TimeoutException());
                }
            }
        }