public void StopService(int stopTimeout)
        {
            HiveData.SyncWithStorage(HiveSyncFlags.LoadFromFile, true);

            long pid = HiveData.ManagedData.Pid;

            if (pid != 0)
            {
                if (Env.IsWindows == false)
                {
                    if (UnixApi.Kill((int)pid, UnixApi.Signals.SIGTERM) == 0)
                    {
                        Con.WriteLine($"Shutting down the daemon \"{Name}\" (pid = {pid}) ...");

                        if (UnixApi.WaitProcessExit((int)pid, stopTimeout) == false)
                        {
                            Con.WriteLine($"Shutting down the daemon \"{Name}\" (pid = {pid}) timed out.");

                            throw new ApplicationException($"Shutting down the daemon \"{Name}\" (pid = {pid}) timed out.");
                        }
                    }
                    else
                    {
                        Con.WriteLine($"The daemon \"{Name}\" is not running.");
                    }
                }
                else
                {
                    if (ManualResetEvent.TryOpenExisting(HiveData.ManagedData.EventName !, out EventWaitHandle? eventHandle))
                    {
                        try
                        {
                            Con.WriteLine($"Stopping the daemon \"{Name}\" (pid = {pid}) ...");

                            eventHandle.Set();

                            if (Win32ApiUtil.WaitProcessExit((int)pid, stopTimeout) == false)
                            {
                                Con.WriteLine($"Stopping the daemon \"{Name}\" (pid = {pid}) timed out.");

                                throw new ApplicationException($"Stopping the daemon \"{Name}\" (pid = {pid}) timed out.");
                            }
                        }
                        finally
                        {
                            eventHandle._DisposeSafe();
                        }
                    }
                    else
                    {
                        Con.WriteLine($"The daemon \"{Name}\" is not running.");
                    }
                }
        void UnixSigTermHandler(System.Runtime.Loader.AssemblyLoadContext obj)
        {
            if (SigTermOnce.IsFirstCall())
            {
                // Stop the service
                Con.WriteLine($"The daemon \"{Name}\" received the SIGTERM signal. Shutting down the daemon...");

                InternalStop();

                Con.WriteLine($"The daemon \"{Name}\" completed the SIGTERM handler.");
            }
        }
        void Win32PipeRecvHandler()
        {
            if (PipeRecvOnce.IsFirstCall())
            {
                // Stop the service
                Con.WriteLine($"The daemon \"{Name}\" received the shutdown command. Shutting down the daemon...");

                InternalStop();

                Con.WriteLine($"The daemon \"{Name}\" completed the shutdown command handler.");
            }
        }
Exemplo n.º 4
0
        public async Task <IReadOnlyList <SslCertCollectorItem> > ExecuteAsync(CancellationToken cancel = default)
        {
            int totalCount = Queue.Count;

            StartFlag.FirstCallOrThrowException();

            List <Task> taskList = new List <Task>();

            for (int i = 0; i < this.MaxConcurrentTasks; i++)
            {
                Task t = WorkerTaskAsync(cancel);

                taskList.Add(t);
            }

            CancellationTokenSource done = new CancellationTokenSource();

            TaskUtil.StartAsyncTaskAsync(async() =>
            {
                CancellationToken doneCancel = done.Token;

                while (doneCancel.IsCancellationRequested == false)
                {
                    await doneCancel._WaitUntilCanceledAsync(250);

                    int completed = totalCount - Queue.Count;

                    Con.WriteLine("{0} / {1}", completed._ToString3(), totalCount._ToString3());
                }
            })._LaissezFaire(true);

            foreach (Task t in taskList)
            {
                await t._TryWaitAsync(true);
            }

            done._TryCancelNoBlock();

            return(ResultList.ToList());
        }
Exemplo n.º 5
0
        async Task EasyPrintRealTimeRecvDataPrintCallbackAsync(PipeStream st)
        {
            var r = new BinaryLineReader(st);

            while (true)
            {
                List <Tuple <Memory <byte>, bool> >?lines = await r.ReadLinesWithTimeoutAsync(1000);

                if (lines == null)
                {
                    break;
                }

                foreach (var line in lines)
                {
                    string tagStr = "";
                    if (this.Options.PrintTag._IsFilled())
                    {
                        tagStr = $"{this.Options.PrintTag}: ";
                    }

                    string lineDecoded = line.Item1._GetString(this.OutputEncoding);

                    string str = tagStr + lineDecoded;

                    if (line.Item2 == false)
                    {
                        str += " [...!!pending!!...]";
                    }

                    using (await WriteLineLocker.LockWithAwait())
                    {
                        Con.WriteLine(str);
                    }
                }
            }
        }
Exemplo n.º 6
0
        public static void Aead_ChaCha20Poly1305_Ietf_Test()
        {
            string nonce_hex     = "07 00 00 00 40 41 42 43 44 45 46 47";
            string plaintext_hex =
                "4c 61 64 69 65 73 20 61 6e 64 20 47 65 6e 74 6c " +
                "65 6d 65 6e 20 6f 66 20 74 68 65 20 63 6c 61 73 " +
                "73 20 6f 66 20 27 39 39 3a 20 49 66 20 49 20 63 " +
                "6f 75 6c 64 20 6f 66 66 65 72 20 79 6f 75 20 6f " +
                "6e 6c 79 20 6f 6e 65 20 74 69 70 20 66 6f 72 20 " +
                "74 68 65 20 66 75 74 75 72 65 2c 20 73 75 6e 73 " +
                "63 72 65 65 6e 20 77 6f 75 6c 64 20 62 65 20 69 " +
                "74 2e";
            string aad_hex = "50 51 52 53 c0 c1 c2 c3 c4 c5 c6 c7";
            string key_hex = "80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f " +
                             "90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f";

            string rfc_mac = "1a:e1:0b:59:4f:09:e2:6a:7e:90:2e:cb:d0:60:06:91".Replace(':', ' ');
            string rfc_enc = "d3 1a 8d 34 64 8e 60 db 7b 86 af bc 53 ef 7e c2 " +
                             "a4 ad ed 51 29 6e 08 fe a9 e2 b5 a7 36 ee 62 d6 " +
                             "3d be a4 5e 8c a9 67 12 82 fa fb 69 da 92 72 8b " +
                             "1a 71 de 0a 9e 06 0b 29 05 d6 a5 b6 7e cd 3b 36 " +
                             "92 dd bd 7f 2d 77 8b 8c 98 03 ae e3 28 09 1b 58 " +
                             "fa b3 24 e4 fa d6 75 94 55 85 80 8b 48 31 d7 bc " +
                             "3f f4 de f0 8e 4b 7a 9d e5 76 d2 65 86 ce c6 4b " +
                             "61 16";

            var nonce     = nonce_hex._GetHexBytes().AsMemory();
            var plaintext = plaintext_hex._GetHexBytes().AsMemory();
            var aad       = aad_hex._GetHexBytes().AsMemory();
            var key       = key_hex._GetHexBytes().AsMemory();
            var encrypted = new byte[plaintext.Length + AeadChaCha20Poly1305MacSize].AsMemory();
            var decrypted = new byte[plaintext.Length].AsMemory();

            Con.WriteLine("Aead_ChaCha20Poly1305_Ietf_Test()");

            Aead_ChaCha20Poly1305_Ietf_Encrypt(encrypted, plaintext, key, nonce, aad);

            string encrypted_hex = encrypted.Slice(0, plaintext.Length).ToArray()._GetHexString(" ");
            string mac_hex       = encrypted.Slice(plaintext.Length, AeadChaCha20Poly1305MacSize).ToArray()._GetHexString(" ");

            Con.WriteLine($"Encrypted:\n{encrypted_hex}\n");

            Con.WriteLine($"MAC:\n{mac_hex}\n");

            var a = rfc_enc._GetHexBytes();

            if (encrypted.Slice(0, plaintext.Length).Span.SequenceEqual(a) == false)
            {
                throw new ApplicationException("encrypted != rfc_enc");
            }

            Con.WriteLine("Check OK.");

            if (Aead_ChaCha20Poly1305_Ietf_Decrypt(decrypted, encrypted, key, nonce, aad) == false)
            {
                throw new ApplicationException("Decrypt failed.");
            }
            else
            {
                Con.WriteLine("Decrypt OK.");

                if (plaintext.Span.SequenceEqual(decrypted.Span))
                {
                    Con.WriteLine("Same OK.");
                }
                else
                {
                    throw new ApplicationException("Different !!!");
                }
            }
        }
Exemplo n.º 7
0
        async Task ServerMainLoop(CancellationToken mainLoopCancel)
        {
            if (Once.IsFirstCall() == false)
            {
                throw new ApplicationException("You cannot reuse the object.");
            }

            using (var sessions = new GroupManager <ulong, SessionData>(
                       onNewGroup: (key, state) =>
            {
                Dbg.Where($"New session: {key}");
                return(new SessionData());
            },
                       onDeleteGroup: (key, ctx, state) =>
            {
                Dbg.Where($"Delete session: {key}");
            }))
            {
                var listener = System.CreateListener(new TcpListenParam(async(lx, sock) =>
                {
                    Con.WriteLine($"Connected {sock.Info.Tcp.RemoteIPAddress}:{sock.Info.Tcp.RemotePort} -> {sock.Info.Tcp.LocalIPAddress}:{sock.Info.Tcp.LocalPort}");

                    var app = sock.GetNetAppProtocolStub();

                    var st = app.GetStream();

                    var attachHandle = app.AttachHandle;

                    attachHandle.SetStreamReceiveTimeout(RecvTimeout);

                    await st.SendAsync("TrafficServer\r\n\0"._GetBytes_Ascii());

                    ReadOnlyMemoryBuffer <byte> buf = await st.ReceiveAsync(17);

                    Direction dir   = buf.ReadBool8() ? Direction.Send : Direction.Recv;
                    ulong sessionId = 0;
                    long timespan   = 0;

                    try
                    {
                        sessionId = buf.ReadUInt64();
                        timespan  = buf.ReadSInt64();
                    }
                    catch { }

                    long recvEndTick = FastTick64.Now + timespan;
                    if (timespan == 0)
                    {
                        recvEndTick = long.MaxValue;
                    }

                    using (var session = sessions.Enter(sessionId))
                    {
                        using (var delay = new DelayAction((int)(Math.Min(timespan * 3 + 180 * 1000, int.MaxValue)), x => app._CancelSafe(new TimeoutException())))
                        {
                            if (dir == Direction.Recv)
                            {
                                RefInt refTmp  = new RefInt();
                                long totalSize = 0;

                                while (true)
                                {
                                    var ret = await st.FastReceiveAsync(totalRecvSize: refTmp);
                                    if (ret.Count == 0)
                                    {
                                        break;
                                    }
                                    totalSize += refTmp;

                                    if (ret[0].Span[0] == (byte)'!')
                                    {
                                        break;
                                    }

                                    if (FastTick64.Now >= recvEndTick)
                                    {
                                        break;
                                    }
                                }

                                attachHandle.SetStreamReceiveTimeout(Timeout.Infinite);
                                attachHandle.SetStreamSendTimeout(60 * 5 * 1000);

                                session.Context.NoMoreData = true;

                                while (true)
                                {
                                    MemoryBuffer <byte> sendBuf = new MemoryBuffer <byte>();
                                    sendBuf.WriteSInt64(totalSize);

                                    await st.SendAsync(sendBuf);

                                    await Task.Delay(100);
                                }
                            }
                            else
                            {
                                attachHandle.SetStreamReceiveTimeout(Timeout.Infinite);
                                attachHandle.SetStreamSendTimeout(Timeout.Infinite);

                                while (true)
                                {
                                    if (sessionId == 0 || session.Context.NoMoreData == false)
                                    {
                                        await st.SendAsync(SendData);
                                    }
                                    else
                                    {
                                        var recvMemory = await st.ReceiveAsync();

                                        if (recvMemory.Length == 0)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                                                                        "SpeedTest",
                                                                        this.ServerPorts));

                try
                {
                    Con.WriteLine("Listening.");

                    await TaskUtil.WaitObjectsAsync(cancels : mainLoopCancel._SingleArray());
                }
                finally
                {
                    await listener._DisposeWithCleanupSafeAsync();
                }
            }
        }
Exemplo n.º 8
0
        public async Task <Result?> RunClientAsync()
        {
            CurrentCount.Increment();

            try
            {
                if (Once.IsFirstCall() == false)
                {
                    throw new ApplicationException("You cannot reuse the object.");
                }

                Con.WriteLine("Client mode start");

                ExceptionQueue = new ExceptionQueue();
                SessionId      = Util.RandUInt64();

                List <Task <Result> >        tasks       = new List <Task <Result> >();
                List <AsyncManualResetEvent> readyEvents = new List <AsyncManualResetEvent>();

                using (CancelWatcher cancelWatcher = new CancelWatcher(this.Cancel))
                {
                    for (int i = 0; i < NumConnection; i++)
                    {
                        Direction dir;
                        if (Mode == SpeedTestModeFlag.Download)
                        {
                            dir = Direction.Recv;
                        }
                        else if (Mode == SpeedTestModeFlag.Upload)
                        {
                            dir = Direction.Send;
                        }
                        else
                        {
                            dir = ((i % 2) == 0) ? Direction.Recv : Direction.Send;
                        }

                        AsyncManualResetEvent readyEvent = new AsyncManualResetEvent();
                        var t = ClientSingleConnectionAsync(dir, readyEvent, cancelWatcher.CancelToken);
                        ExceptionQueue.RegisterWatchedTask(t);
                        tasks.Add(t);
                        readyEvents.Add(readyEvent);
                    }

                    try
                    {
                        using (var whenAllReady = new WhenAll(readyEvents.Select(x => x.WaitAsync())))
                        {
                            await TaskUtil.WaitObjectsAsync(
                                tasks : tasks.Append(whenAllReady.WaitMe).ToArray(),
                                cancels : cancelWatcher.CancelToken._SingleArray(),
                                manualEvents : ExceptionQueue.WhenExceptionAdded._SingleArray());
                        }

                        Cancel.ThrowIfCancellationRequested();
                        ExceptionQueue.ThrowFirstExceptionIfExists();

                        ExceptionQueue.WhenExceptionAdded.CallbackList.AddSoftCallback(x =>
                        {
                            cancelWatcher.Cancel();
                        });

                        using (new DelayAction(TimeSpan * 3 + 180 * 1000, x =>
                        {
                            cancelWatcher.Cancel();
                        }, doNotBlockOnDispose: true))
                        {
                            ClientStartEvent.Set(true);

                            using (var whenAllCompleted = new WhenAll(tasks))
                            {
                                await TaskUtil.WaitObjectsAsync(
                                    tasks : whenAllCompleted.WaitMe._SingleArray(),
                                    cancels : cancelWatcher.CancelToken._SingleArray()
                                    );

                                await whenAllCompleted.WaitMe;
                            }
                        }

                        Result ret = new Result();

                        ret.Span = TimeSpan;

                        foreach (var r in tasks.Select(x => x._GetResult()))
                        {
                            ret.NumBytesDownload += r.NumBytesDownload;
                            ret.NumBytesUpload   += r.NumBytesUpload;
                        }

                        ret.NumBytesTotal = ret.NumBytesUpload + ret.NumBytesDownload;

                        ret.BpsUpload   = (long)((double)ret.NumBytesUpload * 1000.0 * 8.0 / (double)ret.Span * 1514.0 / 1460.0);
                        ret.BpsDownload = (long)((double)ret.NumBytesDownload * 1000.0 * 8.0 / (double)ret.Span * 1514.0 / 1460.0);
                        ret.BpsTotal    = ret.BpsUpload + ret.BpsDownload;

                        return(ret);
                    }
                    catch (Exception ex)
                    {
                        await Task.Yield();

                        ExceptionQueue.Add(ex);
                    }
                    finally
                    {
                        cancelWatcher.Cancel();
                        try
                        {
                            await Task.WhenAll(tasks);
                        }
                        catch { }
                    }

                    ExceptionQueue.ThrowFirstExceptionIfExists();
                }

                return(null);
            }
            finally
            {
                CurrentCount.Decrement();
            }
        }
Exemplo n.º 9
0
 public static void WriteJsonLine(object?obj, bool includeNull = false, bool escapeHtml = false, int?maxDepth = Json.DefaultMaxDepth, bool compact = false, bool referenceHandling = false, Type?type = null)
 => Con.WriteLine(obj._ObjectToJson(includeNull, escapeHtml, maxDepth, compact, referenceHandling, type: type));
        public void Show()
        {
            HiveData.SyncWithStorage(HiveSyncFlags.LoadFromFile, true);

            long pid  = HiveData.ManagedData.Pid;
            int  port = HiveData.ManagedData.LocalLogWatchPort;

            if (pid != 0 && port != 0)
            {
                Con.WriteLine("Starting the real-time log session.");
                Con.WriteLine("Pressing Ctrl + D or Ctrl + Q to disconnect the session.");
                Con.WriteLine();

                Con.WriteLine($"Connecting to localhost:{port} ...");

                CancellationTokenSource cancelSource = new CancellationTokenSource();
                CancellationToken       cancel       = cancelSource.Token;

                Task task = TaskUtil.StartAsyncTaskAsync(async() =>
                {
                    try
                    {
                        using (var sock = await LocalNet.ConnectAsync(new TcpConnectParam(IPAddress.Loopback, port), cancel))
                            using (var stream = sock.GetStream())
                                using (MemoryHelper.FastAllocMemoryWithUsing(65536, out Memory <byte> tmp))
                                {
                                    Con.WriteLine("The real-time log session is connected.");
                                    Con.WriteLine();
                                    try
                                    {
                                        while (true)
                                        {
                                            int r = await stream.ReadAsync(tmp, cancel);
                                            if (r <= 0)
                                            {
                                                break;
                                            }
                                            ReadOnlyMemory <byte> data = tmp.Slice(0, r);
                                            string s = Str.Utf8Encoding.GetString(data.Span);
                                            Console.Write(s);
                                        }
                                    }
                                    catch { }

                                    Con.WriteLine();
                                    Con.WriteLine("The real-time log session is disconnected.");
                                }
                    }
                    catch (Exception ex)
                    {
                        Con.WriteError(ex.Message);
                    }
                });

                try
                {
                    while (true)
                    {
                        var key = Console.ReadKey();
                        if ((key.Key == ConsoleKey.D || key.Key == ConsoleKey.Q) && key.Modifiers == ConsoleModifiers.Control)
                        {
                            break;
                        }
                    }
                }
                catch { }

                cancelSource._TryCancelNoBlock();

                task._TryWait(true);
            }
            else
            {
                Con.WriteLine($"The daemon \"{Name}\" is not running.");
            }
        }