コード例 #1
0
ファイル: SEPinger.cs プロジェクト: IPA-CyberLab/IPA-DN-Cores
    static bool tcp_check_do(string host, int port, int timeout)
    {
        Sock s = Sock.Connect(host, port, timeout, true, true);

        try
        {
            byte[] d = new byte[1];
            d[0] = (byte)'a';

            int i;
            int num = 3;

            for (i = 0; i < num; i++)
            {
                if (s.SendAll(d) == false)
                {
                    return(false);
                }

                if (i <= (num - 1))
                {
                    ThreadObj.Sleep(300);
                }
            }

            return(true);
        }
        finally
        {
            s.Disconnect();
        }
    }
コード例 #2
0
    public static void RunStartupTest()
    {
        try
        {
            InternalTestClass c = new InternalTestClass();

            c.A = 123;
            c.B = "Hello";

            string s = c._ObjectToJson();

            if (s._InStri("Hello") == false)
            {
                throw new CoresException("s._InStri(\"Hello\") == false");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Json.RunTest Fatal Error: " + ex.ToString());
            ThreadObj.Sleep(1000);
            Environment.Exit(-1);
        }
    }
コード例 #3
0
        public static void SetManifest(string exe, string manifestName)
        {
            Mutex x = new Mutex(false, MutexName);

            x.WaitOne();

            try
            {
                // Manifest file name
                string filename = Path.Combine(Paths.ManifestsDir, manifestName);
                if (File.Exists(filename) == false)
                {
                    throw new FileNotFoundException(filename);
                }

                FileInfo fi = new FileInfo(exe);

                // Copy exe file to a temporary directory
                string exeTmp = IO.CreateTempFileNameByExt(".exe");
                IO.FileCopy(exe, exeTmp);

                // Create a batch file
                string       batFileName = Path.Combine(Paths.TmpDirName, "exec_mt.cmd");
                StreamWriter bat         = new StreamWriter(batFileName, false, Str.ShiftJisEncoding);
                bat.WriteLine("call \"{0}\"", Paths.VisualStudioVCBatchFileName);
                bat.WriteLine("echo on");
                bat.WriteLine("mt.exe -manifest \"{0}\" -outputresource:\"{1}\";1", filename, exeTmp);
                bat.WriteLine("EXIT /B %ERRORLEVEL%");
                bat.Close();

                Exception ex = null;

                int i;
                // Repeated 20 times in order to avoid locking the file by the anti-virus software
                for (i = 0; i < 20; i++)
                {
                    try
                    {
                        // Execute
                        Win32BuildUtil.ExecCommand(Paths.CmdFileName, string.Format("/C \"{0}\"", batFileName), true);
                        ex = null;

                        break;
                    }
                    catch (Exception ex2)
                    {
                        ex = ex2;
                    }

                    ThreadObj.Sleep(Secure.Rand31i() % 50);
                }

                if (ex != null)
                {
                    throw new ApplicationException("mt.exe Manifest Processing for '" + exe + "' Failed.");
                }

                // Revert to the original file
                IO.FileCopy(exeTmp, exe);

                // Restore the date and time
                File.SetCreationTime(exe, fi.CreationTime);
                File.SetLastAccessTime(exe, fi.LastAccessTime);
                File.SetLastWriteTime(exe, fi.LastWriteTime);
            }
            finally
            {
                x.ReleaseMutex();
            }
        }
コード例 #4
0
ファイル: PEUtil.cs プロジェクト: webstorage119/ThinVPN-Ultra
        public static void SetManifest(string exe, string manifestName)
        {
            Mutex x = new Mutex(false, MutexName);

            x.WaitOne();

            try
            {
                // Manifest file name
                string filename = Path.Combine(Paths.ManifestsDir, manifestName);
                if (File.Exists(filename) == false)
                {
                    throw new FileNotFoundException(filename);
                }

                FileInfo fi = new FileInfo(exe);

                // Copy exe file to a temporary directory
                string exeTmp = IO.CreateTempFileNameByExt(".exe");
                IO.FileCopy(exe, exeTmp);

                string mtFileName = Path.Combine(Paths.MicrosoftSDKBinDir, "mt.exe");
                string mtArgs     = string.Format("-nologo -manifest \"{0}\" -outputresource:\"{1}\";1", filename, exeTmp);

                Exception ex = null;

                int i;
                // Repeated 20 times in order to avoid locking the file by the anti-virus software
                for (i = 0; i < 20; i++)
                {
                    try
                    {
                        // Execute
                        Win32BuildTool.ExecCommand(mtFileName, mtArgs, false, true);
                        ex = null;

                        break;
                    }
                    catch (Exception ex2)
                    {
                        ex = ex2;
                    }

                    ThreadObj.Sleep(Secure.Rand31i() % 50);
                }

                if (ex != null)
                {
                    throw new ApplicationException("mt.exe Manifest Processing for '" + exe + "' Failed.");
                }

                ex = null;

                // Revert to the original file
                for (i = 0; i < 20; i++)
                {
                    try
                    {
                        IO.FileCopy(exeTmp, exe);
                        ex = null;

                        break;
                    }
                    catch (Exception ex2)
                    {
                        ex = ex2;
                    }

                    ThreadObj.Sleep(Secure.Rand31i() % 50);
                }

                // Restore the date and time
                File.SetCreationTime(exe, fi.CreationTime);
                File.SetLastAccessTime(exe, fi.LastAccessTime);
                File.SetLastWriteTime(exe, fi.LastWriteTime);
            }
            finally
            {
                x.ReleaseMutex();
            }
        }
コード例 #5
0
        static void Net_Test11_AcceptLoop()
        {
            if (test11_flag == false)
            {
                test11_flag = true;

                new ThreadObj(param =>
                {
                    ThreadObj.Current.Thread.Priority = System.Threading.ThreadPriority.Highest;
                    int last = 0;
                    while (true)
                    {
                        int value = Environment.TickCount;
                        int span  = value - last;
                        last      = value;
                        Console.WriteLine("tick: " + span);
                        ThreadObj.Sleep(100);
                    }
                });
            }

            using (var listener = LocalNet.CreateListener(new TcpListenParam(
                                                              async(listener2, sock) =>
            {
                while (true)
                {
                    var stream = sock.GetStream();
                    StreamReader r = new StreamReader(stream);

                    while (true)
                    {
                        string?line = await r.ReadLineAsync();

                        if (line._IsEmpty())
                        {
                            break;
                        }
                    }
                    int segmentSize = 400;
                    int numSegments = 1000;
                    int totalSize = segmentSize * numSegments;

                    string ret =
                        $@"HTTP/1.1 200 OK
Content-Length: {totalSize}

";

                    await stream.WriteAsync(ret._GetBytes_Ascii());

                    byte[] buf = Util.Rand(numSegments);
                    for (int i = 0; i < numSegments; i++)
                    {
                        await stream.WriteAsync(buf);
                    }
                }
            },
                                                              null,
                                                              80)))
            {
                Con.ReadLine(" > ");
            }
        }
コード例 #6
0
        static void Net_Test12_AcceptLoop2(int port = 80)
        {
            new ThreadObj(param =>
            {
                ThreadObj.Current.Thread.Priority = System.Threading.ThreadPriority.Highest;
                int last = 0;
                while (true)
                {
                    int value = Environment.TickCount;
                    int span  = value - last;
                    last      = value;
                    long mem  = mem = GC.GetTotalMemory(false);
                    try
                    {
                        Console.WriteLine("tick: " + span + "   mem = " + mem / 1024 / 1024 + "    sock = " + LocalNet.GetOpenedSockCount());
                    }
                    catch { }
                    ThreadObj.Sleep(100);
                }
            });

            if (true)
            {
                NetTcpListener listener = LocalNet.CreateListener(new TcpListenParam(
                                                                      async(listener2, sock) =>
                {
                    while (true)
                    {
                        var stream     = sock.GetStream();
                        StreamReader r = new StreamReader(stream);

                        while (true)
                        {
                            string?line = await r.ReadLineAsync();

                            if (line._IsEmpty())
                            {
                                break;
                            }
                        }
                        int segmentSize = 400;
                        int numSegments = 1000;
                        int totalSize   = segmentSize * numSegments;

                        string ret =
                            $@"HTTP/1.1 200 OK
Content-Length: {totalSize}

";

                        await stream.WriteAsync(ret._GetBytes_Ascii());

                        byte[] buf = Util.Rand(numSegments);
                        for (int i = 0; i < numSegments; i++)
                        {
                            await stream.WriteAsync(buf);
                        }
                    }
                },
                                                                      null,
                                                                      port));

                listener.HideAcceptProcError = true;

                ThreadObj.Sleep(-1);
            }
        }
コード例 #7
0
ファイル: UnixApi.cs プロジェクト: IPA-CyberLab/IPA-DN-Cores
    public static unsafe void Poll(IntPtr[] reads, IntPtr[] writes, int timeout)
    {
        if (timeout == 0)
        {
            return;
        }

        PollEvent[] p;
        int         num, n, num_read_total, num_write_total;

        num_read_total = num_write_total = 0;
        foreach (IntPtr fd in reads)
        {
            if ((int)fd != -1)
            {
                num_read_total++;
            }
        }
        foreach (IntPtr fd in writes)
        {
            if ((int)fd != -1)
            {
                num_write_total++;
            }
        }

        num = num_read_total + num_write_total;

        p = new PollEvent[num];

        n = 0;

        foreach (IntPtr fd in reads)
        {
            if ((int)fd != -1)
            {
                p[n].FileDescriptor = (int)fd;
                p[n].Events         = PollEvents.POLLIN | PollEvents.POLLPRI | PollEvents.POLLERR | PollEvents.POLLHUP;
                n++;
            }
        }

        foreach (IntPtr fd in writes)
        {
            if ((int)fd != -1)
            {
                p[n].FileDescriptor = (int)fd;
                p[n].Events         = PollEvents.POLLIN | PollEvents.POLLPRI | PollEvents.POLLERR | PollEvents.POLLHUP | PollEvents.POLLOUT;
                n++;
            }
        }

        if (num == 0)
        {
            ThreadObj.Sleep(timeout);
        }
        else
        {
            //Dbg.WriteLine("Poll Begin.");

            int ret = Poll(p, timeout);

            //Dbg.WriteLine($"Poll end: ret = {ret}, reads = {reads.Length}, writes = {writes.Length}, pfds = {p.Length}");

            //for (int i = 0; i < reads.Length; i++) Dbg.WriteLine($"reads[{i}] = {reads[i]}");
            //for (int i = 0; i < writes.Length; i++) Dbg.WriteLine($"writes[{i}] = {writes[i]}");
        }
    }
コード例 #8
0
ファイル: SEPinger.cs プロジェクト: IPA-CyberLab/IPA-DN-Cores
    // 実行スレッド
    void pingerThreadProc(object?param)
    {
        string optionsStr = this.DefaultOptions; // まずデフォルトのオプション文字列を読む

        string hostname = TargetHost;

        if (hostname._InStri("@"))
        {
            if (hostname._GetKeyAndValue(out string hostname2, out string tmp, "@"))
            {
                hostname = hostname2;

                // オプション文字列が個別に指定されていた場合は、それを先に付ける。同じ項目について上書きをすることになる、
                optionsStr = tmp._NonNull() + "," + optionsStr;
            }
        }

        // オプション文字列のパース
        var options = QueryStringList.Parse(optionsStr, splitChar: ',', trimKeyAndValue: true);

        // IP アドレスバージョンの決定
        AllowedIPVersions allowedIPVersions = AllowedIPVersions.All;

        string ipVerStr = options._GetStrFirst("ipver");

        if (ipVerStr._InStr("4") && ipVerStr._InStr("6") == false)
        {
            allowedIPVersions = AllowedIPVersions.IPv4;
        }
        else if (ipVerStr._InStr("6") && ipVerStr._InStr("4") == false)
        {
            allowedIPVersions = AllowedIPVersions.IPv6;
        }

        bool preferV6 = false;

        string ipperfer = options._GetStrFirst("ipprefer");

        if (ipperfer._InStri("6"))
        {
            preferV6 = true;
        }

        IPAddress GetIpAddress(string hostname, AllowedIPVersions allowedIPVersions)
        {
            var ip = hostname._ToIPAddress(allowedIPVersions, true);

            if (ip != null)
            {
                return(ip);
            }

            return(this.DnsClient.GetIpAddressAsync(hostname, allowedIPVersions, preferV6, noCache: true)._GetResult());
        }

        if (TargetPort == 0)
        {
            // ping の実行
            try
            {
                IPAddress ip = GetIpAddress(hostname, allowedIPVersions);

                SendPingReply ret = SendPing.Send(ip, null, Timeout);

                lock (lockObj)
                {
                    ok       = ret.Ok;
                    finished = true;
                }
            }
            catch
            {
                lock (lockObj)
                {
                    ok       = false;
                    finished = true;
                }
            }

            Console.Write(ok ? "+" : "-");
        }
        else
        {
            int  port      = TargetPort;
            bool tcp_check = false;

            if (port >= 100000)
            {
                port     -= 100000;
                tcp_check = true;
            }

            // TCP Connect の実行
            try
            {
                if (tcp_check == false)
                {
                    IPAddress ip = GetIpAddress(hostname, allowedIPVersions);

                    Sock s = Sock.Connect(ip.ToString(), port, Timeout, true, true);

                    try
                    {
                        if (TcpSendData)
                        {
                            s.SetTimeout(Timeout);

                            long end_tick    = Time.Tick64 + (long)Timeout;
                            int  num_packets = 0;

                            while (true)
                            {
                                if (Time.Tick64 > end_tick)
                                {
                                    break;
                                }

                                if (num_packets >= 16)
                                {
                                    break;
                                }

                                byte[] data = new byte[1];
                                data[0] = (byte)'a';
                                if (s.SendAll(data) == false)
                                {
                                    break;
                                }

                                ThreadObj.Sleep(1);
                                num_packets++;
                            }
                        }

                        s.Disconnect();
                    }
                    catch
                    {
                    }
                }
                else
                {
                    IPAddress ip = GetIpAddress(hostname, allowedIPVersions);

                    if (tcp_check_do(ip.ToString(), port, Timeout) == false)
                    {
                        throw new ApplicationException();
                    }
                }

                lock (lockObj)
                {
                    ok       = true;
                    finished = true;
                }
            }
            catch
            {
                lock (lockObj)
                {
                    ok       = false;
                    finished = true;
                }
            }

            Console.Write(ok ? "*" : "-");
        }

        //EndEvent.Set();
    }
コード例 #9
0
ファイル: SEPinger.cs プロジェクト: IPA-CyberLab/IPA-DN-Cores
    // タスクを実行
    public PingerTask[] ExecTasks(Config config, PingerTask[] baseTaskList)
    {
        double            startTime = Time.NowHighResDouble;
        List <PingerTask> taskList  = new List <PingerTask>();
        List <PingerTask> taskList2 = new List <PingerTask>();

        int num = 0;

        if (config.TcpSendData)
        {
            Con.WriteLine("\n  starting TCP send data...\n");

            foreach (Target target in config.TargetListLastOkHost)
            {
                foreach (int port in target.Ports)
                {
                    if (port != 0)
                    {
                        PingerTask task = new PingerTask(this.DnsClient, target.HostName, config.ConvertHostnameToOkHostname(target.HostName), port, config.Timeout, true, config.DefaultOptions);

                        taskList2.Add(task);
                    }
                }
            }
            foreach (Target target in config.TargetListLastNgHost)
            {
                foreach (int port in target.Ports)
                {
                    if (port != 0)
                    {
                        PingerTask task = new PingerTask(this.DnsClient, target.HostName, config.ConvertHostnameToOkHostname(target.HostName), port, config.Timeout, true, config.DefaultOptions);

                        taskList2.Add(task);
                    }
                }
            }
            foreach (PingerTask task in taskList2)
            {
                if (task != null)
                {
                    task.WaitForEnd();
                }
            }
            Con.WriteLine("\n  TCP send data ended.\n");
        }

        // 各タスクの開始
        foreach (Target target in config.TargetListLastOkHost)
        {
            foreach (int port in target.Ports)
            {
                PingerTask task = null !;
                bool       ok   = false;
                if (baseTaskList != null)
                {
                    if (baseTaskList[num].Ok)
                    {
                        if (config.TcpSendData == false || port == 0)
                        {
                            // すでに前回で Ok が出ている
                            ok = true;
                        }
                    }
                }

                if (ok == false)
                {
                    task = new PingerTask(this.DnsClient, target.HostName, config.ConvertHostnameToOkHostname(target.HostName), port, config.Timeout, config.TcpSendData, config.DefaultOptions);
                }

                taskList.Add(task);

                num++;
            }
        }
        ThreadObj.Sleep(1000);
        foreach (Target target in config.TargetListLastNgHost)
        {
            foreach (int port in target.Ports)
            {
                PingerTask task = null !;
                bool       ok   = false;
                if (baseTaskList != null)
                {
                    if (baseTaskList[num].Ok)
                    {
                        if (config.TcpSendData == false || port == 0)
                        {
                            // すでに前回で Ok が出ている
                            ok = true;
                        }
                    }
                }

                if (ok == false)
                {
                    task = new PingerTask(this.DnsClient, target.HostName, config.ConvertHostnameToOkHostname(target.HostName), port, config.Timeout, config.TcpSendData, config.DefaultOptions);
                }

                taskList.Add(task);

                num++;
            }
        }

        // タスクの完了の待機
        foreach (PingerTask task in taskList)
        {
            if (task != null)
            {
                task.WaitForEnd();

                if (config.TcpSendData)
                {
                    if (task.TargetPort != 0)
                    {
                        task.TcpNg = !task.Ok;
                    }
                }

                if (task.Ok)
                {
                    CurrentOkHostList.Add(task.TargetHost);
                }
            }
        }

        double endTime = Time.NowHighResDouble;

        return(taskList.ToArray());
    }