Exemplo n.º 1
0
        public void SendUserEvent(string data)
        {
            if (RemoteSession.State != RemoteSessionState.Connected)
                return;

            try
            {
                var rdpData = string.Empty;

                var entries = data.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var entry in entries)
                {
                    if (!string.IsNullOrEmpty(entry))
                    {
                        // keyboard scancode (non character key)
                        if (entry.Substring(0, 1).Equals("K"))
                        {
                            var keyEntry = entry.Remove(0, 1);
                            var keyCodeAndState = keyEntry.Split(new[] { "-" }, StringSplitOptions.None);
                            
                            var jsKeyCode = int.Parse(keyCodeAndState[0]);
                            var keyState = keyCodeAndState[1];

                            var rdpScanCode = JsKeyCodeToRdpScanCodeMapping.MapTable[jsKeyCode];
                            if (rdpScanCode != null && (int)rdpScanCode != 0)
                            {
                                rdpData += (string.IsNullOrEmpty(rdpData) ? "K" : ",K") + (int)rdpScanCode + "-" + keyState;
                            }
                        }

                        // keyboard unicode (character key)
                        else if (entry.Substring(0, 1).Equals("U"))
                        {
                            // same format as scancode (key code and state), if parsing is needed
                            rdpData += (string.IsNullOrEmpty(rdpData) ? entry : "," + entry);
                        }

                        // mouse
                        else if (entry.Substring(0, 1).Equals("M"))
                        {
                            rdpData += (string.IsNullOrEmpty(rdpData) ? entry : "," + entry);
                        }
                    }
                }

                if (!string.IsNullOrEmpty(rdpData) && rdpData.Length <= RemoteSessionPipes.InputsPipeBufferSize)
                {
                    Trace.TraceInformation("Forwarding user input(s) {0}, remote session {1}", rdpData, RemoteSession.Id);

                    PipeHelper.WritePipeMessage(
                        RemoteSessionPipes.InputsPipe,
                        "remotesession_" + RemoteSession.Id + "_inputs",
                        rdpData + ",");
                }
            }
            catch (Exception exc)
            {
                Trace.TraceError("Failed to send user input {0}, remote session {1} ({2})", data, RemoteSession.Id, exc);
            }
        }
Exemplo n.º 2
0
        public bool SendCommand(RemoteSessionCommand command, string args = "")
        {
            if (RemoteSession.State != RemoteSessionState.Connected && RemoteSession.State != RemoteSessionState.Disconnecting)
            {
                return(false);
            }

            try
            {
                Trace.TraceInformation("Sending rdp command {0}, remote session {1}", "C" + (int)command + "-" + args, RemoteSession.Id);

                if (command == RemoteSessionCommand.SendFullscreenUpdate)
                {
                    Trace.TraceInformation("Fullscreen update requested, all image(s) will now be discarded while waiting for it, remote session {0}", RemoteSession.Id);
                    _fullscreenPending = true;
                }

                PipeHelper.WritePipeMessage(
                    Pipes.InputsPipe,
                    "remotesession_" + RemoteSession.Id + "_inputs",
                    "C" + (int)command + "-" + args + ",");
            }
            catch (Exception exc)
            {
                Trace.TraceError("Failed to send command {0}, remote session {1} ({2})", command, RemoteSession.Id, exc);
                return(false);
            }

            return(true);
        }
Exemplo n.º 3
0
        private void ProcessImagesPipeMessage(byte[] msg)
        {
            try
            {
                var message = Encoding.UTF8.GetString(msg);

                // simple handshaking
                if (message.Equals("Hello server"))
                {
                    PipeHelper.WritePipeMessage(
                        RemoteSessionPipes.InputsPipe,
                        "remotesession_" + RemoteSession.Id + "_inputs",
                        "Hello client");
                    
                    // remote session is now connected
                    RemoteSession.State = RemoteSessionState.Connected;
                }
                // new image
                else
                {
                    ProcessUpdate(message);
                }
            }
            catch (Exception exc)
            {
                Trace.TraceError("Failed to process images pipe message, remote session {0} ({1})", RemoteSession.Id, exc);
            }
        }
Exemplo n.º 4
0
 public void SendUpdatesPipeMessage(string msg)
 {
     PipeHelper.WritePipeMessage(
         _updatesPipe,
         "remotesession_" + _remotesessionID + "_updates",
         msg);
 }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            var pipe = PipeHelper.CreateClient(PipeNames.Reciever);

            var reader = new StreamReader(pipe);

            while (true)
            {
                Console.Write("How many messages to recieve: ");

                var input = Console.ReadLine();

                if (!int.TryParse(input, out int messageCount))
                {
                    Console.Write("Thats not a number, dummy...");
                    continue;
                }

                for (var x = 0; x < messageCount; x++)
                {
                    var message = reader.ReadLine();
                    Console.WriteLine($"Message {x + 1}: {message}");
                }
            }
        }
Exemplo n.º 6
0
        private static void CheckClientFree()
        {
            if (StateCenter.Instance.HasRepalced && StateCenter.Instance.HasRunDynCoded)
            {
                MinimizedDelegate();
                return;
            }
            if (_isZiping)
            {
                MonitorDelegate("【保护线程】 正在安装客户端");
                return;
            }
            _isZiping = true;
            var res = PipeHelper.Communication("Are you Free?");

            bool.TryParse(res, out _isFree);
            MonitorDelegate($"【保护线程】 检查空闲, 空闲状态:{_isFree}");
            if (!string.IsNullOrEmpty(res) && !_isFree)
            {
                MonitorDelegate("【保护线程】 当前客户端忙碌,不允许更新");
            }
            else
            {
                //关闭客户端,文件替换,重启客户端
                MonitorDelegate("【保护线程】 更新开始 ");
                KillProcess();
                MaxmizedDelegate();
                if (!StateCenter.Instance.HasRepalced)
                {
                    if (!string.IsNullOrEmpty(Modifier.VersionResponse.Data.BlackList) ||
                        !string.IsNullOrEmpty(Modifier.VersionResponse.Data.ExistSoIgnoreList))
                    {
                        if (ZipHelper.UnZipPath(ConstFile.PackagePath, ConstFile.TempPath))
                        {
                            BatchFiles();
                            Finish();
                        }
                        else
                        {
                            MonitorDelegate($"【保护线程】 安装客户端失败 解压失败");
                            return;
                        }
                    }
                    else
                    {
                        if (ZipHelper.UnZipPath(ConstFile.PackagePath, ConstFile.DefaultClientDirectory))
                        {
                            Finish();
                        }
                        else
                        {
                            MonitorDelegate($"【保护线程】 安装客户端失败 解压失败");
                            return;
                        }
                    }
                }
            }
            _isZiping = false;
        }
Exemplo n.º 7
0
        private void ProcessUpdatesPipeMessage(byte[] msg)
        {
            try
            {
                var message = Encoding.UTF8.GetString(msg);

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    // simple handshaking
                    if (message.Equals("Hello server"))
                    {
                        PipeHelper.WritePipeMessage(
                            Pipes.InputsPipe,
                            "remotesession_" + RemoteSession.Id + "_inputs",
                            "Hello client");

                        // remote session is now connected
                        RemoteSession.State = RemoteSessionState.Connected;
                    }
                }
                // remote clipboard
                else if (message.StartsWith("clipboard|"))
                {
                    // if using a websocket, send the clipboard directly
                    if (WebSocket != null)
                    {
                        if (WebSocket.IsAvailable)
                        {
                            Trace.TraceInformation("Sending clipboard content {0} on websocket, remote session {1}", message, RemoteSession.Id);
                            WebSocket.Send(message);
                        }
                        else
                        {
                            Trace.TraceInformation("Websocket is unavailable (connection closed by client?), remote session {0}, status: {1}", RemoteSession.Id, RemoteSession.State);
                        }
                    }
                    // otherwise store it (will be retrieved later)
                    else
                    {
                        ClipboardText      = message.Remove(0, 10);
                        ClipboardRequested = true;
                    }
                }
                // new image
                else
                {
                    ProcessUpdate(message);
                }
            }
            catch (Exception exc)
            {
                Trace.TraceError("Failed to process updates pipe message, remote session {0} ({1})", RemoteSession.Id, exc);
            }
        }
Exemplo n.º 8
0
 public void ReadInputsPipe()
 {
     while (_inputsPipe != null && _inputsPipe.IsConnected)
     {
         var msg = PipeHelper.ReadPipeData(_inputsPipe, "remotesession_" + _remotesessionID + "_inputs", false);
         if (msg != null && msg.Length > 0)
         {
             ProcessInputsPipeMessage(msg);
         }
     }
 }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            var pipe = PipeHelper.CreateClient(PipeNames.Sender);

            var writer = new StreamWriter(pipe);

            while (true)
            {
                Console.Write("Type your message: ");
                var message = Console.ReadLine();

                Console.WriteLine($"Sending: {message}");

                writer.WriteLine(message);
                writer.Flush();

                Console.WriteLine($"Message Sent!");
            }
        }
Exemplo n.º 10
0
        private void ReadUpdatesPipe()
        {
            try
            {
                while (UpdatesPipe != null && UpdatesPipe.IsConnected)
                {
                    var msg = PipeHelper.ReadPipeMessage(UpdatesPipe, "remotesession_" + RemoteSession.Id + "_updates");
                    if (msg != null && msg.Length > 0)
                    {
                        ProcessUpdatesPipeMessage(msg);
                    }
                }
            }
            catch (Exception exc)
            {
                Trace.TraceError("Failed to read updates pipe, remote session {0} ({1})", RemoteSession.Id, exc);

                // there is a problem with the updates pipe, close the remote session in order to avoid it being stuck
                RemoteSession.Manager.SendCommand(RemoteSessionCommand.CloseRdpClient);
            }
        }
Exemplo n.º 11
0
        private void ReadAudioPipe()
        {
            try
            {
                while (AudioPipe != null && AudioPipe.IsConnected)
                {
                    var msg = PipeHelper.ReadPipeMessage(AudioPipe, "remotesession_" + RemoteSession.Id + "_audio", false, audioBufferSize);
                    if (msg != null && msg.Length > 0)
                    {
                        ProcessAudioPipeMessage(msg);
                    }
                }
            }
            catch (Exception exc)
            {
                Trace.TraceError("Failed to read audio pipe, remote session {0} ({1})", RemoteSession.Id, exc);

                // there is a problem with the audio pipe, close the remote session in order to avoid it being stuck
                RemoteSession.Manager.SendCommand(RemoteSessionCommand.CloseClient);
            }
        }
Exemplo n.º 12
0
        private void ReadUpdatesPipe()
        {
            try
            {
                byte[] data;

                while (UpdatesPipe != null && UpdatesPipe.IsConnected)
                {
                    data = PipeHelper.ReadPipeData(UpdatesPipe, "remotesession_" + RemoteSession.Id + "_updates");
                    if (data != null && data.Length > 0)
                    {
                        RemoteSession.Manager.ProcessUpdatesPipeData(data);
                    }
                }
            }
            catch (Exception exc)
            {
                Trace.TraceError("Failed to read updates pipe, remote session {0} ({1})", RemoteSession.Id, exc);

                // there is a problem with the updates pipe, close the remote session in order to avoid it being stuck
                RemoteSession.Manager.SendCommand(RemoteSessionCommand.CloseClient);
            }
        }
Exemplo n.º 13
0
        public void SendCommand(RemoteSessionCommand command, string args = "")
        {
            if (RemoteSession.State == RemoteSessionState.NotConnected ||
                RemoteSession.State == RemoteSessionState.Disconnected)
            {
                return;
            }

            var commandWithArgs = string.Concat((string)RemoteSessionCommandMapping.ToPrefix[command], args);

            switch (command)
            {
            // as the process command line can be displayed into the task manager / process explorer, the connection settings (including user credentials) are now passed to the host client through the inputs pipe
            // their values are set from the login page (using http(s) get or post) and shouldn't be modified at this step
            case RemoteSessionCommand.SendServerAddress:
            case RemoteSessionCommand.SendVMGuid:
            case RemoteSessionCommand.SendUserDomain:
            case RemoteSessionCommand.SendUserName:
            case RemoteSessionCommand.SendUserPassword:
            case RemoteSessionCommand.SendStartProgram:

                if (RemoteSession.State != RemoteSessionState.Connecting)
                {
                    return;
                }

                break;

            // browser resize
            case RemoteSessionCommand.SendBrowserResize:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                if (_resizeDelayed)
                {
                    if (_resizeTimeout != null)
                    {
                        _resizeTimeout.Cancel();
                        _resizeTimeout.Dispose();
                    }
                    _resizeTimeout = new CancellationTokenSource();
                    Task.Delay(500, _resizeTimeout.Token).ContinueWith(task =>
                    {
                        var resolution = args.Split(new[] { "x" }, StringSplitOptions.None);
                        var width      = int.Parse(resolution[0]);
                        var height     = int.Parse(resolution[1]);

                        RemoteSession.ClientWidth  = width < 100 ? 100 : width;
                        RemoteSession.ClientHeight = height < 100 ? 100 : height;

                        if (RemoteSession.BrowserResize == BrowserResize.Reconnect)
                        {
                            RemoteSession.Reconnect = true;
                            SendCommand(RemoteSessionCommand.CloseClient);
                        }
                        else
                        {
                            _resizeDelayed = false;
                            SendCommand(RemoteSessionCommand.SendBrowserResize, args);
                        }
                    }, TaskContinuationOptions.NotOnCanceled);
                    return;
                }
                _resizeDelayed = true;
                break;

            // browser pulse
            case RemoteSessionCommand.SendBrowserPulse:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                break;

            // keyboard, mouse
            case RemoteSessionCommand.SendKeyUnicode:
            case RemoteSessionCommand.SendMouseMove:
            case RemoteSessionCommand.SendMouseLeftButton:
            case RemoteSessionCommand.SendMouseMiddleButton:
            case RemoteSessionCommand.SendMouseRightButton:
            case RemoteSessionCommand.SendMouseWheelUp:
            case RemoteSessionCommand.SendMouseWheelDown:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                break;

            case RemoteSessionCommand.SendKeyScancode:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                var keyCodeAndState = args.Split(new[] { "-" }, StringSplitOptions.None);

                var jsKeyCode = int.Parse(keyCodeAndState[0]);
                var keyState  = keyCodeAndState[1];

                var rdpScanCode = JsKeyCodeToRdpScanCodeMapping.MapTable[jsKeyCode] as RdpScanCode;
                if (rdpScanCode != null && rdpScanCode.Value != 0)
                {
                    commandWithArgs = string.Concat((string)RemoteSessionCommandMapping.ToPrefix[command], rdpScanCode.Value + "-" + keyState + "-" + (rdpScanCode.Extend ? "1" : "0"));
                }
                break;

            // control
            case RemoteSessionCommand.SetScaleDisplay:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Display scaling {0}, remote session {1}", args != "0" ? args : "OFF", RemoteSession.Id);
                RemoteSession.BrowserResize = args != "0" ? BrowserResize.Scale : BrowserResize.None;
                break;

            case RemoteSessionCommand.SetReconnectSession:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Session reconnect {0}, remote session {1}", args == "1" ? "ON" : "OFF", RemoteSession.Id);
                RemoteSession.BrowserResize = args == "1" ? BrowserResize.Reconnect : BrowserResize.None;
                break;

            case RemoteSessionCommand.SetImageEncoding:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Image encoding {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                RemoteSession.ImageEncoding = (ImageEncoding)int.Parse(args);
                break;

            case RemoteSessionCommand.SetImageQuality:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Image quality {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                RemoteSession.ImageQuality = int.Parse(args);
                break;

            case RemoteSessionCommand.SetImageQuantity:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Image quantity {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                RemoteSession.ImageQuantity = int.Parse(args);
                break;

            case RemoteSessionCommand.SetAudioFormat:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Audio format {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                RemoteSession.AudioFormat = (AudioFormat)int.Parse(args);
                break;

            case RemoteSessionCommand.SetAudioBitrate:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Audio bitrate {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                RemoteSession.AudioBitrate = int.Parse(args);
                break;

            case RemoteSessionCommand.SetScreenshotConfig:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                var config = args.Split(new[] { "|" }, StringSplitOptions.None);
                RemoteSession.ScreenshotIntervalSecs = int.Parse(config[0]);
                RemoteSession.ScreenshotFormat       = (CaptureFormat)int.Parse(config[1]);
                RemoteSession.ScreenshotPath         = config[2];

                Trace.TraceInformation("Screenshot config {0}, remote session {1}", args, RemoteSession.Id);
                break;

            case RemoteSessionCommand.StartTakingScreenshots:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                if (_screenshotTimeout != null)
                {
                    _screenshotTimeout.Cancel();
                    _screenshotTimeout.Dispose();
                }
                _screenshotTimeout = new CancellationTokenSource();
                SendCommand(RemoteSessionCommand.TakeScreenshot);

                Trace.TraceInformation("Starting taking screenshots {0}, remote session {1}", args, RemoteSession.Id);
                break;

            case RemoteSessionCommand.StopTakingScreenshots:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                if (_screenshotTimeout != null)
                {
                    _screenshotTimeout.Cancel();
                    _screenshotTimeout.Dispose();
                }
                _screenshotTimeout = null;

                Trace.TraceInformation("Stopping taking screenshots {0}, remote session {1}", args, RemoteSession.Id);
                break;

            case RemoteSessionCommand.TakeScreenshot:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                if (_screenshotTimeout != null)
                {
                    _screenshotTimeout.Cancel();
                    _screenshotTimeout.Dispose();
                    _screenshotTimeout = new CancellationTokenSource();
                    Task.Delay(RemoteSession.ScreenshotIntervalSecs * 1000, _screenshotTimeout.Token).ContinueWith(task =>
                    {
                        SendCommand(RemoteSessionCommand.TakeScreenshot);
                    }, TaskContinuationOptions.NotOnCanceled);
                }

                FullscreenEventPending = true;

                Trace.TraceInformation("Taking screenshot {0}, remote session {1}", args, RemoteSession.Id);
                break;

            case RemoteSessionCommand.RequestFullscreenUpdate:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                FullscreenEventPending = true;

                Trace.TraceInformation("Requesting fullscreen update, all image(s) will now be discarded while waiting for it, remote session {0}", RemoteSession.Id);
                break;

            case RemoteSessionCommand.SendLocalClipboard:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                var clipboardText = string.Empty;

                // read the clipboard text from unicode code points
                var charsCodes = args.Split(new[] { "-" }, StringSplitOptions.None);
                foreach (var charCode in charsCodes)
                {
                    clipboardText += char.ConvertFromUtf32(int.Parse(charCode));
                }

                // truncated above max length, which was normally already enforced client side; re-checking
                if (clipboardText.Length > _clipboardMaxLength)
                {
                    clipboardText = clipboardText.Substring(0, _clipboardMaxLength) + "--- TRUNCATED ---";
                }

                commandWithArgs = string.Concat((string)RemoteSessionCommandMapping.ToPrefix[command], clipboardText);

                Trace.TraceInformation("Sending local clipboard, remote session {0}", RemoteSession.Id);
                break;

            case RemoteSessionCommand.ConnectClient:

                if (RemoteSession.State != RemoteSessionState.Connecting)
                {
                    return;
                }

                Trace.TraceInformation("Connecting remote session, remote session {0}", RemoteSession.Id);
                break;

            case RemoteSessionCommand.CloseClient:

                if ((RemoteSession.State != RemoteSessionState.Connecting) &&
                    (RemoteSession.State != RemoteSessionState.Connected))
                {
                    return;
                }

                RemoteSession.State = RemoteSessionState.Disconnecting;

                Trace.TraceInformation("disconnecting remote session, remote session {0}", RemoteSession.Id);
                break;
            }

            Trace.TraceInformation("Sending command with args {0}, remote session {1}", commandWithArgs, RemoteSession.Id);

            try
            {
                PipeHelper.WritePipeData(
                    Pipes.InputsPipe,
                    "remotesession_" + RemoteSession.Id + "_inputs",
                    commandWithArgs);
            }
            catch (Exception exc)
            {
                Trace.TraceWarning("Failed to send command {0}, args {1}, remote session {2} ({3})", command, args, RemoteSession.Id, exc);

                // there is a problem with the inputs pipe, force close the remote session in order to avoid it being stuck
                // it's usually not a big deal, some inputs being sent while the pipes are being disconnected when the host client is closed (and thus before the remote session state is set to disconnected), but better take no risk...
                HostClient.StopProcess();
            }
        }
Exemplo n.º 14
0
        public void SendCommand(RemoteSessionCommand command, string args = "")
        {
            if (RemoteSession.State == RemoteSessionState.NotConnected || RemoteSession.State == RemoteSessionState.Disconnected)
            {
                return;
            }

            var commandWithArgs = string.Concat((string)RemoteSessionCommandMapping.ToPrefix[command], args);

            switch (command)
            {
            // as the process command line can be displayed into the task manager / process explorer, the connection settings (including user credentials) are now passed to the rdp client through the inputs pipe
            // their values are set from the login page (using http(s) post), they shouldn't be modified at this step
            case RemoteSessionCommand.SendServerAddress:
            case RemoteSessionCommand.SendUserDomain:
            case RemoteSessionCommand.SendUserName:
            case RemoteSessionCommand.SendUserPassword:
            case RemoteSessionCommand.SendStartProgram:
                // if needed
                break;

            // browser, keyboard, mouse, etc.
            case RemoteSessionCommand.SendBrowserResize:
            case RemoteSessionCommand.SendKeyUnicode:
            case RemoteSessionCommand.SendMouseMove:
            case RemoteSessionCommand.SendMouseLeftButton:
            case RemoteSessionCommand.SendMouseMiddleButton:
            case RemoteSessionCommand.SendMouseRightButton:
            case RemoteSessionCommand.SendMouseWheelUp:
            case RemoteSessionCommand.SendMouseWheelDown:
                // if needed
                break;

            case RemoteSessionCommand.SendKeyScancode:
                var keyCodeAndState = args.Split(new[] { "-" }, StringSplitOptions.None);

                var jsKeyCode = int.Parse(keyCodeAndState[0]);
                var keyState  = keyCodeAndState[1];

                var rdpScanCode = JsKeyCodeToRdpScanCodeMapping.MapTable[jsKeyCode];
                if (rdpScanCode != null && (int)rdpScanCode != 0)
                {
                    commandWithArgs = string.Concat((string)RemoteSessionCommandMapping.ToPrefix[command], (int)rdpScanCode + "-" + keyState);
                }
                break;

            // control
            case RemoteSessionCommand.SetStatMode:
                Trace.TraceInformation("Stat mode {0}, remote session {1}", args == "1" ? "ON" : "OFF", RemoteSession.Id);
                RemoteSession.StatMode = args == "1";
                break;

            case RemoteSessionCommand.SetDebugMode:
                Trace.TraceInformation("Debug mode {0}, remote session {1}", args == "1" ? "ON" : "OFF", RemoteSession.Id);
                RemoteSession.DebugMode = args == "1";
                break;

            case RemoteSessionCommand.SetCompatibilityMode:
                Trace.TraceInformation("Compatibility mode {0}, remote session {1}", args == "1" ? "ON" : "OFF", RemoteSession.Id);
                RemoteSession.CompatibilityMode = args == "1";
                break;

            case RemoteSessionCommand.SetScaleDisplay:
                Trace.TraceInformation("Display scaling {0}, remote session {1}", args != "0" ? args : "OFF", RemoteSession.Id);
                RemoteSession.ScaleDisplay = args != "0";
                break;

            case RemoteSessionCommand.SetImageEncoding:
                Trace.TraceInformation("Image encoding {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                RemoteSession.ImageEncoding = (ImageEncoding)int.Parse(args);
                break;

            case RemoteSessionCommand.SetImageQuality:
                Trace.TraceInformation("Image quality {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                RemoteSession.ImageQuality = int.Parse(args);
                break;

            case RemoteSessionCommand.SetImageQuantity:
                Trace.TraceInformation("Image quantity {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                RemoteSession.ImageQuantity = int.Parse(args);
                break;

            case RemoteSessionCommand.RequestFullscreenUpdate:
                Trace.TraceInformation("Requesting fullscreen update, all image(s) will now be discarded while waiting for it, remote session {0}", RemoteSession.Id);
                FullscreenEventPending = true;
                break;

            case RemoteSessionCommand.RequestRemoteClipboard:
                Trace.TraceInformation("Requesting remote clipboard, remote session {0}", RemoteSession.Id);
                break;

            case RemoteSessionCommand.ConnectRdpClient:
                Trace.TraceInformation("Connecting remote session, remote session {0}", RemoteSession.Id);
                break;

            case RemoteSessionCommand.CloseRdpClient:
                Trace.TraceInformation("Closing remote session, remote session {0}", RemoteSession.Id);
                break;
            }

            Trace.TraceInformation("Sending command with args {0}, remote session {1}", commandWithArgs, RemoteSession.Id);

            try
            {
                PipeHelper.WritePipeMessage(
                    Pipes.InputsPipe,
                    "remotesession_" + RemoteSession.Id + "_inputs",
                    commandWithArgs + "\t");
            }
            catch (Exception exc)
            {
                Trace.TraceError("Failed to send command {0}, args {1}, remote session {2} ({3})", command, args, RemoteSession.Id, exc);

                // there is a problem with the inputs pipe, force close the remote session in order to avoid it being stuck
                Client.StopProcess();
            }
        }
Exemplo n.º 15
0
        public void SendCommand(RemoteSessionCommand command, string args = "")
        {
            if (RemoteSession.State == RemoteSessionState.NotConnected ||
                RemoteSession.State == RemoteSessionState.Disconnected)
            {
                return;
            }

            var commandWithArgs = string.Concat((string)RemoteSessionCommandMapping.ToPrefix[command], args);

            switch (command)
            {
            // as the process command line can be displayed into the task manager / process explorer, the connection settings (including user credentials) are now passed to the host client through the inputs pipe
            // their values are set from the login page (using http(s) post), they shouldn't be modified at this step
            case RemoteSessionCommand.SendServerAddress:
            case RemoteSessionCommand.SendVMGuid:
            case RemoteSessionCommand.SendUserDomain:
            case RemoteSessionCommand.SendUserName:
            case RemoteSessionCommand.SendUserPassword:
            case RemoteSessionCommand.SendStartProgram:

                if (RemoteSession.State != RemoteSessionState.Connecting)
                {
                    return;
                }

                break;

            // browser
            case RemoteSessionCommand.SendBrowserResize:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                if (!_scaleOnResize)
                {
                    if (_reconnectTimeout != null)
                    {
                        _reconnectTimeout.Cancel();
                        _reconnectTimeout = new CancellationTokenSource();
                        Task.Delay(250, _reconnectTimeout.Token).ContinueWith(task =>
                        {
                            RemoteSession.Reconnect = true;

                            var resolution = args.Split(new[] { "x" }, StringSplitOptions.None);
                            var width      = int.Parse(resolution[0]);
                            var height     = int.Parse(resolution[1]);

                            RemoteSession.ClientWidth  = width;
                            RemoteSession.ClientHeight = height;

                            RemoteSession.State = RemoteSessionState.Disconnecting;
                            SendCommand(RemoteSessionCommand.CloseClient);
                        }, TaskContinuationOptions.NotOnCanceled);
                    }
                    return;
                }
                break;

            // keyboard, mouse
            case RemoteSessionCommand.SendKeyUnicode:
            case RemoteSessionCommand.SendMouseMove:
            case RemoteSessionCommand.SendMouseLeftButton:
            case RemoteSessionCommand.SendMouseMiddleButton:
            case RemoteSessionCommand.SendMouseRightButton:
            case RemoteSessionCommand.SendMouseWheelUp:
            case RemoteSessionCommand.SendMouseWheelDown:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                break;

            case RemoteSessionCommand.SendKeyScancode:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                var keyCodeAndState = args.Split(new[] { "-" }, StringSplitOptions.None);

                var jsKeyCode = int.Parse(keyCodeAndState[0]);
                var keyState  = keyCodeAndState[1];

                var rdpScanCode = JsKeyCodeToRdpScanCodeMapping.MapTable[jsKeyCode];
                if (rdpScanCode != null && (int)rdpScanCode != 0)
                {
                    commandWithArgs = string.Concat((string)RemoteSessionCommandMapping.ToPrefix[command], (int)rdpScanCode + "-" + keyState);
                }
                break;

            // control
            case RemoteSessionCommand.SetStatMode:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Stat mode {0}, remote session {1}", args == "1" ? "ON" : "OFF", RemoteSession.Id);
                RemoteSession.StatMode = args == "1";
                break;

            case RemoteSessionCommand.SetDebugMode:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Debug mode {0}, remote session {1}", args == "1" ? "ON" : "OFF", RemoteSession.Id);
                RemoteSession.DebugMode = args == "1";
                break;

            case RemoteSessionCommand.SetCompatibilityMode:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Compatibility mode {0}, remote session {1}", args == "1" ? "ON" : "OFF", RemoteSession.Id);
                RemoteSession.CompatibilityMode = args == "1";
                break;

            case RemoteSessionCommand.SetScaleDisplay:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Display scaling {0}, remote session {1}", args != "0" ? args : "OFF", RemoteSession.Id);
                if (_scaleOnResize || !RemoteSession.ScaleDisplay.HasValue)
                {
                    RemoteSession.ScaleDisplay = args != "0";
                }
                else
                {
                    return;
                }
                break;

            case RemoteSessionCommand.SetImageEncoding:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Image encoding {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                RemoteSession.ImageEncoding = (ImageEncoding)int.Parse(args);
                break;

            case RemoteSessionCommand.SetImageQuality:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Image quality {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                RemoteSession.ImageQuality = int.Parse(args);
                break;

            case RemoteSessionCommand.SetImageQuantity:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Image quantity {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                RemoteSession.ImageQuantity = int.Parse(args);
                break;

            case RemoteSessionCommand.RequestFullscreenUpdate:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Requesting fullscreen update, all image(s) will now be discarded while waiting for it, remote session {0}", RemoteSession.Id);
                if (!_scaleOnResize && args == "scale")
                {
                    return;
                }
                FullscreenEventPending = true;
                break;

            case RemoteSessionCommand.RequestRemoteClipboard:

                if (RemoteSession.State != RemoteSessionState.Connected)
                {
                    return;
                }

                Trace.TraceInformation("Requesting remote clipboard, remote session {0}", RemoteSession.Id);
                break;

            case RemoteSessionCommand.ConnectClient:

                if (RemoteSession.State != RemoteSessionState.Connecting)
                {
                    return;
                }

                Trace.TraceInformation("Connecting remote session, remote session {0}", RemoteSession.Id);
                break;

            case RemoteSessionCommand.CloseClient:

                if (RemoteSession.State != RemoteSessionState.Disconnecting)
                {
                    return;
                }

                Trace.TraceInformation("Closing remote session, remote session {0}", RemoteSession.Id);
                break;
            }

            Trace.TraceInformation("Sending command with args {0}, remote session {1}", commandWithArgs, RemoteSession.Id);

            try
            {
                PipeHelper.WritePipeMessage(
                    Pipes.InputsPipe,
                    "remotesession_" + RemoteSession.Id + "_inputs",
                    commandWithArgs + "\t");
            }
            catch (Exception exc)
            {
                Trace.TraceWarning("Failed to send command {0}, args {1}, remote session {2} ({3})", command, args, RemoteSession.Id, exc);

                // there is a problem with the inputs pipe, force close the remote session in order to avoid it being stuck
                // it's usually not a big deal, some inputs being sent while the pipes are being disconnected when the host client is closed (and thus before the remote session state is set to disconnected), but better take no risk...
                HostClient.StopProcess();
            }
        }
Exemplo n.º 16
0
        public bool SendCommand(RemoteSessionCommand command, string args = "")
        {
            try
            {
                var commandWithArgs = string.Concat((string)RemoteSessionCommandMapping.ToPrefix[command], args);

                switch (command)
                {
                // browser, keyboard, mouse, etc.
                case RemoteSessionCommand.SendBrowserResize:
                case RemoteSessionCommand.SendKeyUnicode:
                case RemoteSessionCommand.SendMouseMove:
                case RemoteSessionCommand.SendMouseLeftButton:
                case RemoteSessionCommand.SendMouseMiddleButton:
                case RemoteSessionCommand.SendMouseRightButton:
                case RemoteSessionCommand.SendMouseWheelUp:
                case RemoteSessionCommand.SendMouseWheelDown:
                    // if needed
                    break;

                case RemoteSessionCommand.SendKeyScancode:
                    var keyCodeAndState = args.Split(new[] { "-" }, StringSplitOptions.None);

                    var jsKeyCode = int.Parse(keyCodeAndState[0]);
                    var keyState  = keyCodeAndState[1];

                    var rdpScanCode = JsKeyCodeToRdpScanCodeMapping.MapTable[jsKeyCode];
                    if (rdpScanCode != null && (int)rdpScanCode != 0)
                    {
                        commandWithArgs = string.Concat((string)RemoteSessionCommandMapping.ToPrefix[command], (int)rdpScanCode + "-" + keyState);
                    }
                    break;

                // control
                case RemoteSessionCommand.SetStatMode:
                    Trace.TraceInformation("Stat mode {0}, remote session {1}", args == "1" ? "ON" : "OFF", RemoteSession.Id);
                    RemoteSession.StatMode = args == "1";
                    break;

                case RemoteSessionCommand.SetDebugMode:
                    Trace.TraceInformation("Debug mode {0}, remote session {1}", args == "1" ? "ON" : "OFF", RemoteSession.Id);
                    RemoteSession.DebugMode = args == "1";
                    break;

                case RemoteSessionCommand.SetCompatibilityMode:
                    Trace.TraceInformation("Compatibility mode {0}, remote session {1}", args == "1" ? "ON" : "OFF", RemoteSession.Id);
                    RemoteSession.CompatibilityMode = args == "1";
                    break;

                case RemoteSessionCommand.SetScaleDisplay:
                    Trace.TraceInformation("Display scaling {0}, remote session {1}", args != "0" ? args : "OFF", RemoteSession.Id);
                    RemoteSession.ScaleDisplay = args != "0";
                    break;

                case RemoteSessionCommand.SetImageEncoding:
                    Trace.TraceInformation("Image encoding {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                    RemoteSession.ImageEncoding = (ImageEncoding)int.Parse(args);
                    break;

                case RemoteSessionCommand.SetImageQuality:
                    Trace.TraceInformation("Image quality {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                    RemoteSession.ImageQuality = int.Parse(args);
                    break;

                case RemoteSessionCommand.SetImageQuantity:
                    Trace.TraceInformation("Image quantity {0}, remote session {1}", int.Parse(args), RemoteSession.Id);
                    RemoteSession.ImageQuantity = int.Parse(args);
                    break;

                case RemoteSessionCommand.RequestFullscreenUpdate:
                    Trace.TraceInformation("Requesting fullscreen update, all image(s) will now be discarded while waiting for it, remote session {0}", RemoteSession.Id);
                    FullscreenEventPending = true;
                    break;

                case RemoteSessionCommand.RequestRemoteClipboard:
                    Trace.TraceInformation("Requesting remote clipboard, remote session {0}", RemoteSession.Id);
                    break;

                case RemoteSessionCommand.CloseRdpClient:
                    Trace.TraceInformation("Closing remote session, remote session {0}", RemoteSession.Id);
                    break;
                }

                Trace.TraceInformation("Sending command with args {0}, remote session {1}", commandWithArgs, RemoteSession.Id);

                if (RemoteSession.State == RemoteSessionState.Connected ||
                    RemoteSession.State == RemoteSessionState.Disconnecting)
                {
                    PipeHelper.WritePipeMessage(
                        Pipes.InputsPipe,
                        "remotesession_" + RemoteSession.Id + "_inputs",
                        commandWithArgs + ",");
                }
            }
            catch (Exception exc)
            {
                Trace.TraceError("Failed to send command {0}, args {1}, remote session {2} ({3})", command, args, RemoteSession.Id, exc);
                return(false);
            }

            return(true);
        }