Exemple #1
0
        /// <summary>
        /// Async method to write pending data to the standard input stream of the command line.
        /// </summary>
        private async void WriteToClientTask()
        {
            while (ShouldRun)
            {
                Thread.Sleep(1);
                if (!PendingMessages.IsEmpty) // AND if it is a good time to write to client
                {
                    byte[] msgByte = new byte[MaxLen];
                    string peekMsg = string.Empty;
                    PendingMessages.TryPeek(out peekMsg);
                    byte[] strBuf = Encoding.UTF8.GetBytes(peekMsg);
                    Buffer.BlockCopy(strBuf, 0, msgByte, 0, strBuf.Length);
                    await server.WriteAsync(msgByte, 0, MaxLen);

                    Thread.Sleep(1);
                    await server.FlushAsync();

                    lock (threadLock)
                    {
                        PendingMessages.TryDequeue(out var result);
                    }
                }
            }
            KillPipes();
        }
Exemple #2
0
        private void EncodeThreadInit(int _camNumber, string _encodePipeName, string _sessionPath, int _count, ConcurrentQueue <byte[]> _encodeQueue)
        {
            int    camNumber      = _camNumber;
            string pipeName       = _encodePipeName;
            string sessionPath    = _sessionPath;
            int    count          = _count;
            int    nFramesWritten = 0;
            ConcurrentQueue <byte[]> encodeQueue = _encodeQueue;

            NamedPipeServerStream pipe = new NamedPipeServerStream(pipeName: pipeName, direction: PipeDirection.Out, maxNumberOfServerInstances: 1,
                                                                   transmissionMode: PipeTransmissionMode.Byte, options: PipeOptions.Asynchronous, inBufferSize: 7057600, outBufferSize: 7057600);

            string    videoFileName = sessionPath + @"\" + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + ".mp4";
            FFProcess ffProcess     = new FFProcess(pipeName: pipeName, videoFileName: videoFileName);

            ffProcess.OpenWithStartInfo();
            pipe.WaitForConnection();
            Console.WriteLine("Pipe connected to ffProcess for camera {0} on thread {1}", camNumber.ToString(), Thread.CurrentThread.ManagedThreadId.ToString());

            bool goEncode = true;
            bool isDequeueSuccess;

            while (goEncode)
            {
                isDequeueSuccess = encodeQueue.TryDequeue(out byte[] result);
                if (isDequeueSuccess)
                {
                    pipe.Write(buffer: result, offset: 0, count: count);
                    nFramesWritten++;

                    if (nFramesWritten % 1000 == 0)
                    {
                        Console.WriteLine("nFramesWritten for cam number {0}:   {1}", camNumber.ToString(), nFramesWritten.ToString());
                    }
                }
                else
                {
                    Thread.Sleep(10);
                    if (encodeQueue.Count == 0)
                    {
                        goEncode = false;
                    }
                }
            }

            pipe.FlushAsync();
            pipe.WaitForPipeDrain();
            pipe.Close();
            ffProcess.process.WaitForExit();
            ffProcess.process.Close();
            Console.WriteLine("EncodeThread for camera {0}: Pipe flushed, drained, and closed. FFProcess exited and closed.", camNumber.ToString());

            if (camNumber == 0)
            {
                GC.Collect();
                Console.WriteLine("Garbage collected on camera 1 EncodeThread. Now exiting.");
            }
        }
Exemple #3
0
        private static async Task SendResponceToClient(NamedPipeServerStream stream, string serverResponce)
        {
            byte[] responceData = Encoding.Unicode.GetBytes(serverResponce);
            await stream.WriteAsync(responceData, 0, responceData.Length);

            await stream.FlushAsync();

            stream.WaitForPipeDrain();
        }
        private static async Task WaitForConnectionAsync(NamedPipeServerStream pipeServerStream)
        {
#if CoreCLR
            await pipeServerStream.WaitForConnectionAsync();
#else
            await Task.Factory.FromAsync(pipeServerStream.BeginWaitForConnection, pipeServerStream.EndWaitForConnection, null);
#endif
            await pipeServerStream.FlushAsync();
        }
Exemple #5
0
        private async Task WriteToPipe(byte[] buffer, NamedPipeServerStream pipe)
        {
            if (IsDisposed)
            {
                return;
            }
            try {
                await pipe.WriteAsync(buffer, 0, buffer.Length);

                await pipe.FlushAsync();
            } catch {}
        }
Exemple #6
0
        async Task CreateProfileWorkerAsync(CancellationToken ct)
        {
            while (!ct.IsCancellationRequested)
            {
                PipeSecurity       ps  = new PipeSecurity();
                SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                PipeAccessRule     par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                ps.AddAccessRule(par);
                using (NamedPipeServerStream server = new NamedPipeServerStream("Microsoft.R.Host.UserProfile.Creator{b101cc2d-156e-472e-8d98-b9d999a93c7a}", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps)) {
                    try {
                        await server.WaitForConnectionAsync(ct);

                        byte[] requestRaw = new byte[1024];
                        int    bytesRead  = 0;

                        while (bytesRead == 0 && !ct.IsCancellationRequested)
                        {
                            bytesRead = await server.ReadAsync(requestRaw, 0, requestRaw.Length, ct);
                        }

                        string json = Encoding.Unicode.GetString(requestRaw, 0, bytesRead);

                        var requestData = JsonConvert.DeserializeObject <RUserProfileCreateRequest>(json);

                        var result = RUserProfileCreator.Create(requestData, _logger);

                        string jsonResp = JsonConvert.SerializeObject(result);
                        byte[] respData = Encoding.Unicode.GetBytes(jsonResp);

                        await server.WriteAsync(respData, 0, respData.Length, ct);

                        await server.FlushAsync(ct);

                        // Waiting here to allow client to finish reading
                        // client should disconnect after reading.
                        while (bytesRead == 0 && !ct.IsCancellationRequested)
                        {
                            bytesRead = await server.ReadAsync(requestRaw, 0, requestRaw.Length, ct);
                        }

                        // if there was an attempt to write, disconnect.
                        server.Disconnect();
                    } catch (Exception ex) when(!ex.IsCriticalException())
                    {
                        _logger?.LogError(Resources.Error_UserProfileCreationError, ex.Message);
                    }
                }
            }
            _workerdone.Set();
        }
Exemple #7
0
 private static void StartMonitor(string name)
 {
     try
     {
         while (!mIsClosed)
         {
             using (var server = new NamedPipeServerStream(name + "h", PipeDirection.InOut))
             {
                 server.WaitForConnection();
                 while (!mIsClosed)
                 {
                     try
                     {
                         if (!server.IsConnected)
                         {
                             break;
                         }
                         var cmd = server.ReadByte();
                         if (cmd == 0)
                         {
                             if (Runner.Instance.IsStarted)
                             {
                                 Runner.Instance.Stop();
                             }
                             mIsClosed = true;
                             server.WriteByte(1);
                             server.FlushAsync();
                             Console.WriteLine(Res.Get("AnyKeyToExit"));
                             break;
                             //退出系统
                         }
                         else
                         {
                         }
                     }
                     catch
                     {
                         break;
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Exemple #8
0
        private void CreateServer()
        {
            try
            {
                using (pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut))
                {
                    Logger.Info("Wait Client connect PipeName:" + pipeName);
                    pipeServer.WaitForConnection();
                    Logger.Info("Client is connected PipeName:" + pipeName);
                    this.isConnected = true;

                    while (true)
                    {
                        Thread.Sleep(1);
                        bool isSuccess = sendMsgQueue.TryDequeue(out sendMsg);
                        if (isSuccess)
                        {
                            byte[] arrByte = Encoding.UTF8.GetBytes(sendMsg.sendContent);
                            pipeServer.Write(arrByte, 0, arrByte.Length);
                            byte[] data = new byte[PipeBufferSize];
                            int    read = pipeServer.Read(data, 0, data.Length);
                            sendMsg.resContent = Encoding.UTF8.GetString(data, 0, read);
                            pipeServer.FlushAsync();
                            sendMsg.areReceive.Set();
                            if (string.IsNullOrEmpty(sendMsg.resContent) && !pipeServer.IsConnected)
                            {
                                this.isConnected = false;
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("CreateServer err:" + ex);
                this.isConnected = false;
                sendMsg.areReceive.Set();
            }
            Thread.Sleep(1);
            CreateServer();
        }
 internal static void ProcesClientMessage(ApplicationMessage applicationMessage, NamedPipeServerStream namedPipeServer)
 {
     if (applicationMessage != null)
     {
         var printMessage = $"Sync Time:{applicationMessage.SyncTime}\n" +
                            $"Sync ID's received:{String.Join<int>(",", applicationMessage.SyncIDs)}";
         Console.WriteLine($"Message from client:\n{printMessage}");
         var    serialized   = JsonConvert.SerializeObject(printMessage);
         byte[] messageBytes = Encoding.UTF8.GetBytes(serialized);
         if (!namedPipeServer.IsConnected)
         {
             namedPipeServer.WaitForConnection();
             Console.WriteLine("Client connected");
         }
         Task.Run(async() =>
         {
             await namedPipeServer.WriteAsync(messageBytes, 0, messageBytes.Length);
             await namedPipeServer.FlushAsync();
         }
                  ).Wait();
     }
 }
        private static async Task WaitForConnectionAsync(NamedPipeServerStream pipeServerStream)
        {
            await pipeServerStream.WaitForConnectionAsync();

            await pipeServerStream.FlushAsync();
        }
Exemple #11
0
        public async Task Listen()
        {
            var ps = new PipeSecurity();

            ps.AddAccessRule(new PipeAccessRule(
                                 new SecurityIdentifier(_allowedSid),
                                 PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance,
                                 AccessControlType.Allow));

            var pipeName = GetPipeName(_allowedSid, _allowedPid);

            Logger.Instance.Log($"Using named pipe {pipeName}.", LogLevel.Debug);

            Logger.Instance.Log($"Access allowed only for ProcessID {_allowedPid} and childs", LogLevel.Debug);

            while (!cancellationTokenSource.IsCancellationRequested)
            {
                using (NamedPipeServerStream dataPipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, MAX_SERVER_INSTANCES,
                                                                                  PipeTransmissionMode.Message, PipeOptions.Asynchronous, GlobalSettings.BufferSize, GlobalSettings.BufferSize, ps))
                {
                    using (NamedPipeServerStream controlPipe = new NamedPipeServerStream(pipeName + "_control", PipeDirection.InOut, MAX_SERVER_INSTANCES,
                                                                                         PipeTransmissionMode.Message, PipeOptions.Asynchronous, GlobalSettings.BufferSize, GlobalSettings.BufferSize, ps))
                    {
                        Logger.Instance.Log("NamedPipeServer listening.", LogLevel.Debug);
                        Task.WaitAll(
                            new Task[]
                        {
                            dataPipe.WaitForConnectionAsync(cancellationTokenSource.Token),
                            controlPipe.WaitForConnectionAsync(cancellationTokenSource.Token),
                        },
                            cancellationTokenSource.Token
                            );

                        if (dataPipe.IsConnected && controlPipe.IsConnected && !cancellationTokenSource.IsCancellationRequested)
                        {
                            var connection = new Connection()
                            {
                                ControlStream = controlPipe, DataStream = dataPipe
                            };

                            ConnectionKeepAliveThread.Start(connection);

                            Logger.Instance.Log("Incoming Connection.", LogLevel.Info);

                            var clientPid = dataPipe.GetClientProcessId();

                            if (!IsAuthorized(clientPid, _allowedPid))
                            {
                                Logger.Instance.Log($"Unauthorized access from PID {clientPid}", LogLevel.Warning);

                                await controlPipe.WriteAsync($"{Constants.TOKEN_ERROR}Unauthorized.{Constants.TOKEN_ERROR}").ConfigureAwait(false);

                                await controlPipe.FlushAsync().ConfigureAwait(false);

                                controlPipe.WaitForPipeDrain();

                                dataPipe.Disconnect();
                                controlPipe.Disconnect();

                                // kill the server.
                                return;
                            }

                            ConnectionAccepted?.Invoke(this, connection);

                            while (connection.IsAlive)
                            {
                                await Task.Delay(10).ConfigureAwait(false);
                            }

                            ConnectionClosed?.Invoke(this, connection);
                        }

                        Logger.Instance.Log("Listener Closed.", LogLevel.Debug);
                    }
                }
            }
        }
 public Task FlushAsync(CancellationToken cancellationToken)
 {
     return(stream.FlushAsync(cancellationToken));
 }
Exemple #13
0
    public async static Task OpenServer()
    {
        ApiCredentials = new ClientSecrets();
        string CustomCredentials = Path.Combine(AppDataDirectory, "credentials.json");

        if (System.IO.File.Exists(CustomCredentials))
        {
            using (var Stream = new MemoryStream(System.IO.File.ReadAllBytes(CustomCredentials)))
                ApiCredentials = GoogleClientSecrets.Load(Stream).Secrets;
        }
        else
        {
            ApiCredentials.ClientId     = "1028112365169-3iss4ffrp626a31lc96pn3c3cujkbdg2.apps.googleusercontent.com";
            ApiCredentials.ClientSecret = "lDb5KUCJt6gLrOtHNScZ6QYm";
        }

        if (ServerInstance == null)
        {
            Message("Null server instance", "dbg", MessageType.Other, ButtonsType.Ok);
            return;
        }

        using (NamedPipeServerStream Server = new NamedPipeServerStream(ServerName + (ServerInstance ?? "GLOBAL")))
        {
            while (true)
            {
                try
                {
                    if (!Server.IsConnected)
                    {
                        await Server.WaitForConnectionAsync();
                    }
                    var Cmd = (Commands)await Server.ReadU16();

                    switch (Cmd)
                    {
                    case Commands.PING:
                        await Server.WriteBool(true);

                        break;

                    case Commands.InterAccounts:
                        await Server.WriteBool(UserInfoA.EmailAddress != UserInfoB.EmailAddress);

                        break;

                    case Commands.CloseServer:
                        Server.Close();
                        return;

                    case Commands.ConnectA:
                        CredentialsA = await GoogleWebAuthorizationBroker.AuthorizeAsync(ApiCredentials, Scopes, UserA, System.Threading.CancellationToken.None);

                        ServiceA = new DriveService(new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = CredentialsA,
                            ApplicationName       = "DriveMirror"
                        });
                        UserInfoA = await ServiceA.GetUserInfo();

                        break;

                    case Commands.ConnectB:
                        CredentialsB = await GoogleWebAuthorizationBroker.AuthorizeAsync(ApiCredentials, Scopes, UserB, System.Threading.CancellationToken.None);

                        ServiceB = new DriveService(new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = CredentialsB,
                            ApplicationName       = "DriveMirror"
                        });
                        UserInfoB = await ServiceB.GetUserInfo();

                        break;

                    case Commands.Disconnect:
                        await CredentialsA.RevokeTokenAsync(CancellationToken.None);

                        await CredentialsB.RevokeTokenAsync(CancellationToken.None);

                        break;

                    case Commands.EnumDrivesA:
                        var DrivesA = await ServiceA.EnumDrives().ToListAsync();

                        await Server.WriteU32((uint)DrivesA.Count);

                        foreach (var Drive in DrivesA)
                        {
                            await Server.WriteString(Drive.Name);

                            await Server.WriteString(Drive.Id);
                        }
                        break;

                    case Commands.EnumDrivesB:
                        var DrivesB = await ServiceB.EnumDrives().ToListAsync();

                        await Server.WriteU32((uint)DrivesB.Count);

                        foreach (var Drive in DrivesB)
                        {
                            await Server.WriteString(Drive.Name);

                            await Server.WriteString(Drive.Id);
                        }
                        break;

                    case Commands.GetFileByIdA:
                        var FileAID = await Server.ReadString();

                        var AInfo = await ServiceA.GetFileById(FileAID);

                        await Server.WriteFileInfo(AInfo);

                        break;

                    case Commands.GetFileByIdB:
                        var FileBID = await Server.ReadString();

                        var BInfo = await ServiceB.GetFileById(FileBID);

                        await Server.WriteFileInfo(BInfo);

                        break;

                    case Commands.ParsePathA:
                        var APath = await Server.ReadString();

                        var AFInfo = await ServiceA.TranslatePath(APath, DriveA, true);

                        await Server.WriteFileInfo(AFInfo);

                        break;

                    case Commands.ParsePathB:
                        var BPath = await Server.ReadString();

                        var BFInfo = await ServiceB.TranslatePath(BPath, DriveB, true);

                        await Server.WriteFileInfo(BFInfo);

                        break;

                    case Commands.EnumFilesA:
                        var AEFID = await Server.ReadString();

                        var ATrashed = await Server.ReadBool();

                        if (AEFID.StartsWith("/"))
                        {
                            AEFID = (await ServiceA.TranslatePath(AEFID)).Id;
                        }
                        await ServiceA.EnumFiles(AEFID, DriveA, true, ATrashed).ForEachAsync(async x =>
                        {
                            await Server.WriteBool(true);
                            await Server.WriteFileInfo(x);
                        });

                        await Server.WriteBool(false);

                        break;

                    case Commands.EnumFilesB:
                        var BEFID = await Server.ReadString();

                        var BTrashed = await Server.ReadBool();

                        if (BEFID.StartsWith("/"))
                        {
                            BEFID = (await ServiceB.TranslatePath(BEFID)).Id;
                        }
                        await ServiceB.EnumFiles(BEFID, DriveB, true, BTrashed).ForEachAsync(async x =>
                        {
                            await Server.WriteBool(true);
                            await Server.WriteFileInfo(x);
                        });

                        await Server.WriteBool(false);

                        break;

                    case Commands.EnumFoldersA:
                        var AEDID = await Server.ReadString();

                        var ADTrashed = await Server.ReadBool();

                        if (AEDID.StartsWith("/"))
                        {
                            AEDID = (await ServiceA.TranslatePath(AEDID)).Id;
                        }
                        await ServiceA.EnumFolders(AEDID, DriveA, ADTrashed).ForEachAsync(async x =>
                        {
                            await Server.WriteBool(true);
                            await Server.WriteFileInfo(x);
                        });

                        await Server.WriteBool(false);

                        break;

                    case Commands.EnumFoldersB:
                        var BEDID = await Server.ReadString();

                        var BDTrashed = await Server.ReadBool();

                        if (BEDID.StartsWith("/"))
                        {
                            BEDID = (await ServiceB.TranslatePath(BEDID)).Id;
                        }
                        await ServiceB.EnumFolders(BEDID, DriveB, BDTrashed).ForEachAsync(async x =>
                        {
                            await Server.WriteBool(true);
                            await Server.WriteFileInfo(x);
                        });

                        await Server.WriteBool(false);

                        break;

                    case Commands.CopyFileA:
                        string ACPYID = await Server.ReadString();

                        string ACPYNM = await Server.ReadString();

                        string ACPYDR = await Server.ReadString();

                        var ACPYNF = await ServiceA.CopyFile(ACPYID, ACPYNM, ACPYDR);

                        await Server.WriteFileInfo(ACPYNF);

                        break;

                    case Commands.CopyFileB:
                        string BCPYID = await Server.ReadString();

                        string BCPYNM = await Server.ReadString();

                        string BCPYDR = await Server.ReadString();

                        var BCPYNF = await ServiceB.CopyFile(BCPYID, BCPYNM, BCPYDR);

                        await Server.WriteFileInfo(BCPYNF);

                        break;

                    case Commands.DeleteFileA:
                        string ADELID = await Server.ReadString();

                        await ServiceA.Delete(await ServiceA.GetFileById(ADELID));

                        break;

                    case Commands.DeleteFileB:
                        string BDELID = await Server.ReadString();

                        await ServiceB.Delete(await ServiceB.GetFileById(BDELID));

                        break;

                    case Commands.CreateDirectoryA:
                        string NewDirPathA = await Server.ReadString();

                        var NDirA = await ServiceA.CreateDirectory(NewDirPathA, DriveA);

                        await Server.WriteFileInfo(NDirA);

                        break;

                    case Commands.CreateDirectoryB:
                        string NewDirPathB = await Server.ReadString();

                        var NDirB = await ServiceB.CreateDirectory(NewDirPathB, DriveB);

                        await Server.WriteFileInfo(NDirB);

                        break;

                    case Commands.SelectDriveA:
                        string ADriveID = await Server.ReadString();

                        DriveA = new Drive()
                        {
                            Id = ADriveID
                        };
                        break;

                    case Commands.SelectDriveB:
                        string BDriveID = await Server.ReadString();

                        DriveB = new Drive()
                        {
                            Id = BDriveID
                        };
                        break;

                    case Commands.ShareFileA:
                        string ASFID = await Server.ReadString();

                        var ASFInfo = await ServiceA.ShareFile(ASFID, ServiceB);

                        await Server.WriteFileInfo(ASFInfo);

                        break;

                    case Commands.ShareFileB:
                        string BSFID = await Server.ReadString();

                        var BSFInfo = await ServiceB.ShareFile(BSFID, ServiceA);

                        await Server.WriteFileInfo(BSFInfo);

                        break;

                    case Commands.StopShareA:
                        var StpFileInfA = await Server.ReadFileInfo();

                        var NWFileInfA = await ServiceA.StopSharing(StpFileInfA);

                        await Server.WriteFileInfo(NWFileInfA);

                        break;

                    case Commands.StopShareB:
                        var StpFileInfB = await Server.ReadFileInfo();

                        var NWFileInfB = await ServiceB.StopSharing(StpFileInfB);

                        await Server.WriteFileInfo(NWFileInfB);

                        break;
                    }
                    await Server.FlushAsync();
                }
                catch (Exception ex) {
                    if (!Client.IsConnected)
                    {
                        return;
                    }

                    Message(ex.ToString(), "DriveMirror Service", MessageType.Error, ButtonsType.Ok);
                }
            }
        }
    }
Exemple #14
0
        public async Task Listen()
        {
            var ps = new PipeSecurity();

            ps.AddAccessRule(new PipeAccessRule(
                                 new SecurityIdentifier(_allowedSid),
                                 PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance,
                                 AccessControlType.Allow));

            var networkSid = new SecurityIdentifier("S-1-5-2");

            // deny remote connections.
            ps.AddAccessRule(new PipeAccessRule(
                                 networkSid,
                                 PipeAccessRights.FullControl,
                                 System.Security.AccessControl.AccessControlType.Deny));

            var pipeName = NamedPipeNameFactory.GetPipeName(_allowedSid, _allowedPid);

            Logger.Instance.Log($"Listening on named pipe {pipeName}.", LogLevel.Debug);

            Logger.Instance.Log($"Access allowed only for ProcessID {_allowedPid} and children", LogLevel.Debug);

            _ = Task.Factory.StartNew(CancelIfAllowedProcessEnds, _cancellationTokenSource.Token,
                                      TaskCreationOptions.LongRunning, TaskScheduler.Current);

            do
            {
                using (NamedPipeServerStream dataPipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, MAX_SERVER_INSTANCES,
                                                                                  PipeTransmissionMode.Message, PipeOptions.Asynchronous, Settings.BufferSize, Settings.BufferSize, ps))
                {
                    using (NamedPipeServerStream controlPipe = new NamedPipeServerStream(pipeName + "_control", PipeDirection.InOut, MAX_SERVER_INSTANCES,
                                                                                         PipeTransmissionMode.Message, PipeOptions.Asynchronous, Settings.BufferSize, Settings.BufferSize, ps))
                    {
                        Logger.Instance.Log("NamedPipeServer listening.", LogLevel.Debug);
                        Task.WaitAll(
                            new Task[]
                        {
                            dataPipe.WaitForConnectionAsync(_cancellationTokenSource.Token),
                            controlPipe.WaitForConnectionAsync(_cancellationTokenSource.Token),
                        },
                            _cancellationTokenSource.Token
                            );

                        if (dataPipe.IsConnected && controlPipe.IsConnected && !_cancellationTokenSource.IsCancellationRequested)
                        {
                            var connection = new Connection()
                            {
                                ControlStream = controlPipe, DataStream = dataPipe
                            };

                            ConnectionKeepAliveThread.Start(connection);

                            Logger.Instance.Log("Incoming Connection.", LogLevel.Info);

                            var clientPid = dataPipe.GetClientProcessId();

                            if (!IsAuthorized(clientPid, _allowedPid))
                            {
                                Logger.Instance.Log($"Unauthorized access from PID {clientPid}", LogLevel.Warning);

                                await controlPipe.WriteAsync($"{Constants.TOKEN_ERROR}Unauthorized.{Constants.TOKEN_ERROR}").ConfigureAwait(false);

                                await controlPipe.FlushAsync().ConfigureAwait(false);

                                controlPipe.WaitForPipeDrain();

                                dataPipe.Disconnect();
                                controlPipe.Disconnect();

                                // kill the server.
                                return;
                            }

                            ConnectionAccepted?.Invoke(this, connection);

                            while (connection.IsAlive)
                            {
                                await Task.Delay(10).ConfigureAwait(false);
                            }

                            ConnectionClosed?.Invoke(this, connection);
                            Logger.Instance.Log("Connection Closed.", LogLevel.Info);
                        }
                    }
                }
            } while (!_singleUse && !_cancellationTokenSource.IsCancellationRequested);
            Logger.Instance.Log("Listener Closed.", LogLevel.Debug);
            _exeLock?.Close();
        }
Exemple #15
0
        private static async Task ProfileServiceOperationAsync(Func <IUserCredentials, ILogger, IUserProfileServiceResult> operation, string name, IUserProfileNamedPipeFactory pipeFactory, int serverTimeOutms = 0, int clientTimeOutms = 0, CancellationToken ct = default(CancellationToken), ILogger logger = null)
        {
            using (NamedPipeServerStream server = pipeFactory.CreatePipe(name)) {
                await server.WaitForConnectionAsync(ct);

                ManualResetEventSlim forceDisconnect = new ManualResetEventSlim(false);
                try {
                    if (serverTimeOutms + clientTimeOutms > 0)
                    {
                        Task.Run(() => {
                            // This handles Empty string input cases. This is usually the case were client is connected and writes a empty string.
                            // on the server side this blocks the ReadAsync indefinitely (even with the cancellation set). The code below protects
                            // the server from being indefinitely blocked by a malicious client.
                            forceDisconnect.Wait(serverTimeOutms + clientTimeOutms);
                            if (server.IsConnected)
                            {
                                server.Disconnect();
                                logger?.LogError(Resources.Error_ClientTimedOut);
                            }
                        }).DoNotWait();
                    }

                    using (var cts = CancellationTokenSource.CreateLinkedTokenSource(ct)) {
                        if (serverTimeOutms > 0)
                        {
                            cts.CancelAfter(serverTimeOutms);
                        }

                        byte[] requestRaw = new byte[1024];
                        int    bytesRead  = 0;

                        while (bytesRead == 0 && !cts.IsCancellationRequested)
                        {
                            bytesRead = await server.ReadAsync(requestRaw, 0, requestRaw.Length, cts.Token);
                        }

                        string json = Encoding.Unicode.GetString(requestRaw, 0, bytesRead);

                        var requestData = Json.DeserializeObject <RUserProfileServiceRequest>(json);

                        var result = operation?.Invoke(requestData, logger);

                        string jsonResp = JsonConvert.SerializeObject(result);
                        byte[] respData = Encoding.Unicode.GetBytes(jsonResp);

                        await server.WriteAsync(respData, 0, respData.Length, cts.Token);

                        await server.FlushAsync(cts.Token);
                    }

                    using (var cts = CancellationTokenSource.CreateLinkedTokenSource(ct)) {
                        if (clientTimeOutms > 0)
                        {
                            cts.CancelAfter(clientTimeOutms);
                        }

                        // Waiting here to allow client to finish reading client should disconnect after reading.
                        byte[] requestRaw = new byte[1024];
                        int    bytesRead  = 0;
                        while (bytesRead == 0 && !cts.Token.IsCancellationRequested)
                        {
                            bytesRead = await server.ReadAsync(requestRaw, 0, requestRaw.Length, cts.Token);
                        }

                        // if there was an attempt to write, disconnect.
                        server.Disconnect();
                    }
                } finally {
                    // server work is done.
                    forceDisconnect.Set();
                }
            }
        }
Exemple #16
0
        private static async Task RunServer()
        {
            Console.WriteLine("Initiating server, waiting for client...");
            // Start up our named pipe in message mode and close the pipe
            // when done.
            using (NamedPipeServerStream serverPipe = new
                                                      NamedPipeServerStream("mypipe", PipeDirection.InOut, 1,
                                                                            PipeTransmissionMode.Message, PipeOptions.None))
            {
                // wait for a client...
                serverPipe.WaitForConnection();

                // process messages until the client goes away
                while (serverPipe.IsConnected)
                {
                    int    bytesRead    = 0;
                    byte[] messageBytes = new byte[256];
                    // read until we have the message then respond
                    do
                    {
                        // build up the client message
                        StringBuilder message = new StringBuilder();

                        // check that we can read the pipe
                        if (serverPipe.CanRead)
                        {
                            // loop until the entire message is read
                            do
                            {
                                bytesRead =
                                    await serverPipe.ReadAsync(messageBytes, 0,
                                                               messageBytes.Length);

                                // got bytes from the stream so add them to the message
                                if (bytesRead > 0)
                                {
                                    message.Append(
                                        Encoding.Unicode.GetString(messageBytes, 0, bytesRead));
                                    Array.Clear(messageBytes, 0, messageBytes.Length);
                                }
                            }while (!serverPipe.IsMessageComplete);
                        }

                        // if we got a message, write it out and respond
                        if (message.Length > 0)
                        {
                            // set to zero as we have read the whole message
                            bytesRead = 0;
                            Console.WriteLine($"Received message: {message.ToString()}");

                            // return the message text we got from the
                            // client in reverse
                            char[] messageChars =
                                message.ToString().Trim().ToCharArray();
                            Array.Reverse(messageChars);
                            string reversedMessageText = new string(messageChars);

                            // show the return message
                            Console.WriteLine($"    Returning Message: {reversedMessageText}");

                            // write the response
                            messageBytes = Encoding.Unicode.GetBytes(messageChars);
                            if (serverPipe.CanWrite)
                            {
                                // write the message
                                await serverPipe.WriteAsync(messageBytes, 0, messageBytes.Length);

                                // flush the buffer
                                await serverPipe.FlushAsync();

                                // wait till read by client
                                serverPipe.WaitForPipeDrain();
                            }
                        }
                    }while (bytesRead != 0);
                }
            }
        }
Exemple #17
0
 private static void StartMonitor(string name)
 {
     try
     {
         while (!mIsClosed)
         {
             try
             {
                 using (var server = new NamedPipeServerStream(name, PipeDirection.InOut))
                 {
                     server.WaitForConnection();
                     while (!mIsClosed)
                     {
                         try
                         {
                             if (!server.IsConnected)
                             {
                                 break;
                             }
                             var cmd = server.ReadByte();
                             if (cmd == 0)
                             {
                                 if (Cdy.Tag.Runner3.RunInstance.IsStarted)
                                 {
                                     Cdy.Tag.Runner3.RunInstance.Stop();
                                 }
                                 mIsClosed = true;
                                 server.WriteByte(1);
                                 server.FlushAsync();
                                 //server.WaitForPipeDrain();
                                 Console.WriteLine(Res.Get("AnyKeyToExit") + ".....");
                                 break;
                                 //退出系统
                             }
                             else if (cmd == 1)
                             {
                                 Console.WriteLine("Start to restart database.......");
                                 Task.Run(() =>
                                 {
                                     Cdy.Tag.Runner3.RunInstance.ReStartDatabase();
                                 });
                                 server.WriteByte(1);
                                 server.FlushAsync();
                                 // server.WaitForPipeDrain();
                             }
                             else
                             {
                             }
                         }
                         catch (Exception eex)
                         {
                             break;
                         }
                     }
                 }
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.Message);
             }
         }
     }
     catch (Exception ex)
     {
         LoggerService.Service.Info("Programe", ex.Message);
         //Console.WriteLine(ex.Message);
     }
 }
Exemple #18
0
        /// <summary>
        /// Server loop
        /// </summary>
        public async Task LoopAsync()
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync(Loop.Token);

            var DTE = await Package.GetServiceAsync(typeof(DTE)) as DTE2;

            await TaskScheduler.Default;

            var pipeName = string.Format("QtVSTest_{0}", Process.GetCurrentProcess().Id);

            while (!Loop.Token.IsCancellationRequested)
            {
                using (var pipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut)) {
                    await pipe.WaitForConnectionAsync(Loop.Token);

                    if (Loop.Token.IsCancellationRequested)
                    {
                        break;
                    }

                    while (!Loop.Token.IsCancellationRequested && pipe.IsConnected)
                    {
                        byte[] data = new byte[4];
                        await pipe.ReadAsync(data, 0, 4, Loop.Token);

                        if (Loop.Token.IsCancellationRequested)
                        {
                            break;
                        }

                        if (pipe.IsConnected)
                        {
                            int size = BitConverter.ToInt32(data, 0);
                            data = new byte[size];

                            await pipe.ReadAsync(data, 0, size, Loop.Token);

                            if (Loop.Token.IsCancellationRequested)
                            {
                                break;
                            }

                            var macro = new Macro(Package, DTE, JoinableTaskFactory, Loop.Token);
                            await macro.CompileAsync(Encoding.UTF8.GetString(data));

                            if (macro.AutoRun)
                            {
                                await macro.RunAsync();
                            }

                            data = Encoding.UTF8.GetBytes(macro.Result);
                            size = data.Length;

                            await pipe.WriteAsync(BitConverter.GetBytes(size), 0, 4, Loop.Token);

                            if (Loop.Token.IsCancellationRequested)
                            {
                                break;
                            }

                            await pipe.WriteAsync(data, 0, size, Loop.Token);

                            if (Loop.Token.IsCancellationRequested)
                            {
                                break;
                            }

                            await pipe.FlushAsync(Loop.Token);

                            if (Loop.Token.IsCancellationRequested)
                            {
                                break;
                            }

                            pipe.WaitForPipeDrain();

                            if (macro != null && macro.Ok && macro.AutoRun && macro.QuitWhenDone)
                            {
                                await JoinableTaskFactory.SwitchToMainThreadAsync(Loop.Token);

                                if (DTE != null)
                                {
                                    DTE.Solution.Close(false);
                                    DTE.Quit();
                                }
                                await TaskScheduler.Default;
                                Loop.Cancel();
                            }
                        }
                    }
                }
            }
        }
        public static async Task RunServer()
        {
            Console.WriteLine("Initiating server, waiting for client...");
            // Start up our named pipe in message mode and close the pipe
            // when done.

            using (NamedPipeServerStream serverStream =
                       new NamedPipeServerStream("mypipe", PipeDirection.InOut, 1,
                                                 PipeTransmissionMode.Message, PipeOptions.None))
            {
                // wait for a client…
                await serverStream.WaitForConnectionAsync();

                while (serverStream.IsConnected)
                {
                    int    bytesRead    = 0;
                    byte[] messageBytes = new byte[256];

                    // read until we have the message then respond
                    do
                    {
                        // build up the client message
                        StringBuilder message = new StringBuilder();
                        // check canRead
                        if (serverStream.CanRead)
                        {
                            do
                            {
                                // loop until the entire message is read
                                bytesRead = await serverStream.ReadAsync(messageBytes, 0,
                                                                         messageBytes.Length);

                                // get bytes from stream and add to message
                                if (bytesRead > 0)
                                {
                                    message.Append(Encoding.Unicode.GetString(messageBytes,
                                                                              0, bytesRead));
                                    Array.Clear(messageBytes, 0, messageBytes.Length);
                                }
                            } while (!serverStream.IsMessageComplete);
                        }
                        // write it out till it got message
                        if (message.Length > 0)
                        {
                            bytesRead = 0;
                            Console.WriteLine($"Received message: {message}");
                            // return message in reverse
                            char[] messageChars = message.ToString().Trim().ToCharArray();
                            Array.Reverse(messageChars);
                            string reversedMessageText = new string(messageChars);

                            Console.WriteLine($"   Returning Message: " +
                                              $"{reversedMessageText}");

                            messageBytes = Encoding.Unicode.GetBytes(messageChars);
                            if (serverStream.CanWrite)
                            {
                                // write the message
                                await serverStream.WriteAsync(messageBytes, 0,
                                                              messageBytes.Length);

                                // flush buffer
                                await serverStream.FlushAsync();

                                // wait till read by client
                                serverStream.WaitForPipeDrain();
                            }
                        }
                    } while (bytesRead != 0);
                }
            }
        }