Beispiel #1
0
        public async Task SendMessage(string senderName,
                                      string message,
                                      string orgName,
                                      bool disconnected,
                                      string senderConnectionID,
                                      HubConnection hubConnection)
        {
            if (!await MessageLock.WaitAsync(30000))
            {
                Logger.Write("Timed out waiting for chat message lock.", Shared.Enums.EventType.Warning);
                return;
            }

            try
            {
                ChatSession chatSession;
                if (!ChatClients.Contains(senderConnectionID))
                {
                    if (disconnected)
                    {
                        // Don't start a new session just to show a disconnected message.
                        return;
                    }

                    var procID = await AppLauncher.LaunchChatService(orgName, senderConnectionID, hubConnection);

                    if (procID > 0)
                    {
                        Logger.Write($"Chat app started.  Process ID: {procID}");
                    }
                    else
                    {
                        Logger.Write($"Chat app did not start successfully.");
                        return;
                    }
                    var serverStream = new NamedPipeServerStream("Remotely_Chat" + senderConnectionID,
                                                                 PipeDirection.InOut,
                                                                 NamedPipeServerStream.MaxAllowedServerInstances,
                                                                 PipeTransmissionMode.Byte,
                                                                 PipeOptions.Asynchronous);

                    var cts = new CancellationTokenSource(15000);
                    await serverStream.WaitForConnectionAsync(cts.Token);

                    if (!serverStream.IsConnected)
                    {
                        Logger.Write("Failed to connect to chat client.");
                        return;
                    }
                    chatSession = new ChatSession()
                    {
                        PipeStream = serverStream, ProcessID = procID
                    };
                    _ = Task.Run(async() => { await ReadFromStream(chatSession.PipeStream, senderConnectionID, hubConnection); });
                    ChatClients.Add(senderConnectionID, chatSession, CacheItemPolicy);
                }

                chatSession = (ChatSession)ChatClients.Get(senderConnectionID);

                if (!chatSession.PipeStream.IsConnected)
                {
                    ChatClients.Remove(senderConnectionID);
                    await hubConnection.SendAsync("DisplayMessage", "Chat disconnected.  Please try again.", "Chat disconnected.", senderConnectionID);

                    return;
                }

                using var sw = new StreamWriter(chatSession.PipeStream, leaveOpen: true);
                var chatMessage = new ChatMessage(senderName, message, disconnected);
                await sw.WriteLineAsync(JsonSerializer.Serialize(chatMessage));

                await sw.FlushAsync();
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
            finally
            {
                MessageLock.Release();
            }
        }
Beispiel #2
0
        public async Task SendMessage(string senderName,
                                      string message,
                                      string orgName,
                                      bool disconnected,
                                      string senderConnectionID,
                                      HubConnection hubConnection)
        {
            if (!await MessageLock.WaitAsync(30000))
            {
                Logger.Write("Timed out waiting for chat message lock.", Shared.Enums.EventType.Warning);
                return;
            }

            try
            {
                ChatSession chatSession;
                if (!ChatClients.Contains(senderConnectionID))
                {
                    if (disconnected)
                    {
                        // Don't start a new session just to show a disconnected message.
                        return;
                    }

                    var procID = await AppLauncher.LaunchChatService(orgName, senderConnectionID, hubConnection);

                    var clientPipe = new NamedPipeClientStream(".", "Remotely_Chat" + senderConnectionID, PipeDirection.InOut, PipeOptions.Asynchronous);
                    clientPipe.Connect(15000);
                    if (!clientPipe.IsConnected)
                    {
                        Logger.Write("Failed to connect to chat host.");
                        return;
                    }
                    chatSession = new ChatSession()
                    {
                        PipeStream = clientPipe, ProcessID = procID
                    };
                    _ = Task.Run(async() => { await ReadFromStream(chatSession.PipeStream, senderConnectionID, hubConnection); });
                    ChatClients.Add(senderConnectionID, chatSession, CacheItemPolicy);
                }

                chatSession = (ChatSession)ChatClients.Get(senderConnectionID);

                if (!chatSession.PipeStream.IsConnected)
                {
                    ChatClients.Remove(senderConnectionID);
                    await hubConnection.SendAsync("DisplayMessage", "Chat disconnected.  Please try again.", "Chat disconnected.", senderConnectionID);

                    return;
                }

                using (var sw = new StreamWriter(chatSession.PipeStream, leaveOpen: true))
                {
                    var chatMessage = new ChatMessage(senderName, message, disconnected);
                    await sw.WriteLineAsync(JsonSerializer.Serialize(chatMessage));

                    await sw.FlushAsync();
                }
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
            finally
            {
                MessageLock.Release();
            }
        }
        private void RegisterMessageHandlers()
        {
            // TODO: Remove possibility for circular dependencies in the future
            // by emitting these events so other services can listen for them.

            HubConnection.On("Chat", async(string senderName, string message, string orgName, bool disconnected, string senderConnectionID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Chat attempted before server was verified.", EventType.Warning);
                    return;
                }

                await ChatService.SendMessage(senderName, message, orgName, disconnected, senderConnectionID, HubConnection);
            });
            HubConnection.On("DownloadFile", async(string filePath, string senderConnectionID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("File download attempted before server was verified.", EventType.Warning);
                    return;
                }

                filePath = filePath.Replace("\"", "");
                if (!File.Exists(filePath))
                {
                    await HubConnection.SendAsync("DisplayMessage", "File not found on remote device.", "File not found.", senderConnectionID);
                    return;
                }

                using var wc              = new WebClient();
                var lastProgressPercent   = 0;
                wc.UploadProgressChanged += async(sender, args) =>
                {
                    if (args.ProgressPercentage > lastProgressPercent)
                    {
                        lastProgressPercent = args.ProgressPercentage;
                        await HubConnection.SendAsync("DownloadFileProgress", lastProgressPercent, senderConnectionID);
                    }
                };

                try
                {
                    var response = await wc.UploadFileTaskAsync($"{ConnectionInfo.Host}/API/FileSharing/", filePath);
                    var fileIDs  = JsonSerializer.Deserialize <string[]>(Encoding.UTF8.GetString(response));
                    await HubConnection.SendAsync("DownloadFile", fileIDs[0], senderConnectionID);
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                    await HubConnection.SendAsync("DisplayMessage", "Error occurred while uploading file from remote computer.", "Upload error.", senderConnectionID);
                }
            });
            HubConnection.On("ChangeWindowsSession", async(string serviceID, string viewerID, int targetSessionID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Session change attempted before server was verified.", EventType.Warning);
                    return;
                }

                await AppLauncher.RestartScreenCaster(new List <string>()
                {
                    viewerID
                }, serviceID, viewerID, HubConnection, targetSessionID);
            });
            HubConnection.On("ExecuteCommand", (async(string mode, string command, string commandID, string senderConnectionID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Command attempted before server was verified.  Mode: {mode}.  Command: {command}.  Sender: {senderConnectionID}", EventType.Warning);
                    return;
                }

                await CommandExecutor.ExecuteCommand(mode, command, commandID, senderConnectionID, HubConnection);
            }));
            HubConnection.On("ExecuteCommandFromApi", (async(string mode, string requestID, string command, string commandID, string senderUserName) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Command attempted before server was verified.  Mode: {mode}.  Command: {command}.  Sender: {senderUserName}", EventType.Warning);
                    return;
                }

                await CommandExecutor.ExecuteCommandFromApi(mode, requestID, command, commandID, senderUserName, HubConnection);
            }));
            HubConnection.On("UploadFiles", async(string transferID, List <string> fileIDs, string requesterID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("File upload attempted before server was verified.", EventType.Warning);
                    return;
                }

                Logger.Write($"File upload started by {requesterID}.");
                var sharedFilePath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "RemotelySharedFiles")).FullName;

                foreach (var fileID in fileIDs)
                {
                    var url            = $"{ConnectionInfo.Host}/API/FileSharing/{fileID}";
                    var wr             = WebRequest.CreateHttp(url);
                    using var response = await wr.GetResponseAsync();
                    var cd             = response.Headers["Content-Disposition"];
                    var filename       = cd
                                         .Split(";")
                                         .FirstOrDefault(x => x.Trim()
                                                         .StartsWith("filename"))
                                         .Split("=")[1];

                    var legalChars = filename.ToCharArray().Where(x => !Path.GetInvalidFileNameChars().Any(y => x == y));

                    filename = new string(legalChars.ToArray());

                    using var rs = response.GetResponseStream();
                    using var fs = new FileStream(Path.Combine(sharedFilePath, filename), FileMode.Create);
                    rs.CopyTo(fs);
                }
                await HubConnection.SendAsync("TransferCompleted", transferID, requesterID);
            });
            HubConnection.On("DeployScript", async(string mode, string fileID, string commandResultID, string requesterID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Script deploy attempted before server was verified.  Mode: {mode}.  File ID: {fileID}.  Sender: {requesterID}", EventType.Warning);
                    return;
                }

                await ScriptRunner.RunScript(mode, fileID, commandResultID, requesterID, HubConnection);
            });

            HubConnection.On("UninstallAgent", () =>
            {
                Uninstaller.UninstallAgent();
            });

            HubConnection.On("RemoteControl", async(string requesterID, string serviceID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Remote control attempted before server was verified.", EventType.Warning);
                    return;
                }
                await AppLauncher.LaunchRemoteControl(-1, requesterID, serviceID, HubConnection);
            });
            HubConnection.On("RestartScreenCaster", async(List <string> viewerIDs, string serviceID, string requesterID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Remote control attempted before server was verified.", EventType.Warning);
                    return;
                }
                await AppLauncher.RestartScreenCaster(viewerIDs, serviceID, requesterID, HubConnection);
            });
            HubConnection.On("CtrlAltDel", () =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("CtrlAltDel attempted before server was verified.", EventType.Warning);
                    return;
                }
                User32.SendSAS(false);
            });

            HubConnection.On("ServerVerificationToken", (string verificationToken) =>
            {
                if (verificationToken == ConnectionInfo.ServerVerificationToken)
                {
                    IsServerVerified = true;
                }
                else
                {
                    Logger.Write($"Server sent an incorrect verification token.  Token Sent: {verificationToken}.", EventType.Warning);
                    return;
                }
            });
        }
Beispiel #4
0
 public ChatClientService(AppLauncher appLauncher)
 {
     AppLauncher = appLauncher;
 }
Beispiel #5
0
        private void RegisterMessageHandlers()
        {
            HubConnection.On("Chat", async(string message, string orgName, string senderConnectionID) => {
                await ChatService.SendMessage(message, orgName, senderConnectionID, HubConnection);
            });
            HubConnection.On("DownloadFile", async(string filePath, string senderConnectionID) =>
            {
                filePath = filePath.Replace("\"", "");
                if (!File.Exists(filePath))
                {
                    await HubConnection.SendAsync("DisplayMessage", "File not found on remote device.", "File not found.", senderConnectionID);
                    return;
                }
                var wr       = WebRequest.CreateHttp($"{ConnectionInfo.Host}/API/FileSharing/");
                var wc       = new WebClient();
                var response = await wc.UploadFileTaskAsync($"{ConnectionInfo.Host}/API/FileSharing/", filePath);
                var fileIDs  = JsonSerializer.Deserialize <string[]>(Encoding.UTF8.GetString(response));
                await HubConnection.SendAsync("DownloadFile", fileIDs[0], senderConnectionID);
            });

            HubConnection.On("ExecuteCommand", (async(string mode, string command, string commandID, string senderConnectionID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Command attempted before server was verified.  Mode: {mode}.  Command: {command}.  Sender: {senderConnectionID}");
                    Uninstaller.UninstallAgent();
                    return;
                }

                await CommandExecutor.ExecuteCommand(mode, command, commandID, senderConnectionID, HubConnection);
            }));
            HubConnection.On("ExecuteCommandFromApi", (async(string mode, string requestID, string command, string commandID, string senderUserName) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write($"Command attempted before server was verified.  Mode: {mode}.  Command: {command}.  Sender: {senderUserName}");
                    Uninstaller.UninstallAgent();
                    return;
                }

                await CommandExecutor.ExecuteCommandFromApi(mode, requestID, command, commandID, senderUserName, HubConnection);
            }));
            HubConnection.On("UploadFiles", async(string transferID, List <string> fileIDs, string requesterID) =>
            {
                Logger.Write($"File upload started by {requesterID}.");
                var sharedFilePath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "RemotelySharedFiles")).FullName;

                foreach (var fileID in fileIDs)
                {
                    var url      = $"{ConnectionInfo.Host}/API/FileSharing/{fileID}";
                    var wr       = WebRequest.CreateHttp(url);
                    var response = await wr.GetResponseAsync();
                    var cd       = response.Headers["Content-Disposition"];
                    var filename = cd
                                   .Split(";")
                                   .FirstOrDefault(x => x.Trim()
                                                   .StartsWith("filename"))
                                   .Split("=")[1];

                    var legalChars = filename.ToCharArray().Where(x => !Path.GetInvalidFileNameChars().Any(y => x == y));

                    filename = new string(legalChars.ToArray());

                    using (var rs = response.GetResponseStream())
                    {
                        using (var fs = new FileStream(Path.Combine(sharedFilePath, filename), FileMode.Create))
                        {
                            rs.CopyTo(fs);
                        }
                    }
                }
                await this.HubConnection.InvokeAsync("TransferCompleted", transferID, requesterID);
            });
            HubConnection.On("DeployScript", async(string mode, string fileID, string commandResultID, string requesterID) => {
                if (!IsServerVerified)
                {
                    Logger.Write($"Script deploy attempted before server was verified.  Mode: {mode}.  File ID: {fileID}.  Sender: {requesterID}");
                    Uninstaller.UninstallAgent();
                    return;
                }

                await ScriptRunner.RunScript(mode, fileID, commandResultID, requesterID, HubConnection);
            });
            HubConnection.On("UninstallClient", () =>
            {
                Uninstaller.UninstallAgent();
            });

            HubConnection.On("RemoteControl", async(string requesterID, string serviceID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Remote control attempted before server was verified.");
                    Uninstaller.UninstallAgent();
                    return;
                }
                await AppLauncher.LaunchRemoteControl(requesterID, serviceID, HubConnection);
            });
            HubConnection.On("RestartScreenCaster", async(List <string> viewerIDs, string serviceID, string requesterID) =>
            {
                if (!IsServerVerified)
                {
                    Logger.Write("Remote control attempted before server was verified.");
                    Uninstaller.UninstallAgent();
                    return;
                }
                await AppLauncher.RestartScreenCaster(viewerIDs, serviceID, requesterID, HubConnection);
            });
            HubConnection.On("CtrlAltDel", () =>
            {
                User32.SendSAS(false);
            });

            HubConnection.On("ServerVerificationToken", (string verificationToken) =>
            {
                if (verificationToken == ConnectionInfo.ServerVerificationToken)
                {
                    IsServerVerified = true;
                }
                else
                {
                    Logger.Write($"Server sent an incorrect verification token.  Token Sent: {verificationToken}.");
                    Uninstaller.UninstallAgent();
                    return;
                }
            });
        }