示例#1
0
        static int DirSuperBackup(ConsoleService c, string cmdName, string str)
        {
            ConsoleParam[] args =
            {
                new ConsoleParam("[src]",       ConsoleService.Prompt, "Source directory path: ",      ConsoleService.EvalNotEmpty, null),
                new ConsoleParam("dst",         ConsoleService.Prompt, "Destination directory path: ", ConsoleService.EvalNotEmpty, null),
                new ConsoleParam("errorlog"),
                new ConsoleParam("infolog"),
                new ConsoleParam("ignoredirs"),
            };

            ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);

            string src        = vl.DefaultParam.StrValue;
            string dst        = vl["dst"].StrValue;
            string errorlog   = vl["errorlog"].StrValue;
            string infolog    = vl["infolog"].StrValue;
            string ignoredirs = vl["ignoredirs"].StrValue;

            bool err = false;

            try
            {
                Lfs.EnableBackupPrivilege();
            }
            catch (Exception ex)
            {
                Con.WriteError(ex);
            }

            using (var b = new DirSuperBackup(new DirSuperBackupOptions(Lfs, infolog, errorlog)))
            {
                Async(async() =>
                {
                    await b.DoSingleDirBackupAsync(src, dst, default, ignoredirs);
    public GitLabMainteClient(GitLabMainteClientSettings settings)
    {
        try
        {
            this.Settings = settings;

            if (Env.IsWindows)
            {
                this.GitExe = Util.GetGitForWindowsExeFileName();
            }
            else
            {
                this.GitExe = Lfs.UnixGetFullPathFromCommandName("git");
            }

            this.Web = new WebApi(new WebApiOptions(new WebApiSettings {
                SslAcceptAnyCerts = true,
            }));
        }
        catch
        {
            this._DisposeSafe();
            throw;
        }
    }
示例#3
0
    async Task NormalizeAndPollAsync(CancellationToken cancel = default, bool noPoll = false)
    {
        using (await FileLock.LockWithAwait(cancel))
        {
            if (noPoll == false && this.IsCanceled == false && this.IsCleanuped == false)
            {
                if (this.Config.Callback != null)
                {
                    StatManDatabase tmp = new StatManDatabase();

                    await this.Config.Callback(Config.Param, tmp.LongValues, tmp.StrValues)._TryWaitAsync();

                    tmp.LongValues._DoForEach(x => this.AddReport(x.Key, x.Value));
                    tmp.StrValues._DoForEach(x => this.AddReport(x.Key, x.Value));
                }
            }

            StatManDatabase dataCopy;

            lock (DataLock)
            {
                dataCopy = this.Database._CloneWithJson();
            }

            await Lfs.WriteJsonToFileEncryptedAsync(this.FileNameFullPath, dataCopy, Consts.Strings.StatManEncryptKey, FileFlags.AutoCreateDirectory, cancel : cancel)._TryWaitAsync();
        }
    }
示例#4
0
        public ExecOptions(string commandName, IEnumerable <string> argumentsList, string?currentDirectory = null, ExecFlags flags = ExecFlags.Default,
                           int easyOutputMaxSize = Consts.Numbers.DefaultLargeBufferSize, string?easyInputStr = null, string printTag = "",
                           Func <string, Task <bool> >?easyOneLineRecvCallbackAsync = null,
                           Func <ReadOnlyMemory <byte>, ReadOnlyMemory <byte>, Task <bool> >?easyRealtimeRecvBufCallbackAsync = null,
                           int easyRealtimeRecvBufCallbackDelayTickMsecs = 0, StrDictionary <string>?additionalEnvVars = null)
        {
            this.CommandName = commandName._NullCheck();
            if (Env.IsUnix == false || flags.Bit(ExecFlags.UnixAutoFullPath) == false)
            {
                this.FileName = this.CommandName._NullCheck();
            }
            else
            {
                try
                {
                    this.FileName = Lfs.UnixGetFullPathFromCommandName(this.CommandName._NullCheck());
                }
                catch
                {
                    this.FileName = this.CommandName._NullCheck();
                }
            }

            this.Arguments                                 = "";
            this.ArgumentsList                             = argumentsList;
            this.CurrentDirectory                          = currentDirectory._NonNull();
            this.Flags                                     = flags;
            this.EasyOutputMaxSize                         = easyOutputMaxSize._Max(1);
            this.EasyInputStr                              = easyInputStr._NullIfZeroLen();
            this.PrintTag                                  = printTag;
            this.EasyOneLineRecvCallbackAsync              = easyOneLineRecvCallbackAsync;
            this.EasyRealtimeRecvBufCallbackAsync          = easyRealtimeRecvBufCallbackAsync;
            this.EasyRealtimeRecvBufCallbackDelayTickMsecs = easyRealtimeRecvBufCallbackDelayTickMsecs;
            this.AdditionalEnvVars                         = additionalEnvVars;
        }
    public async Task GitPullFromRepositoryAsync(string repositoryPath, string localDir, string branch, CancellationToken cancel = default)
    {
        string gitUrl = this.Settings.GitLabBaseUrl._CombineUrl(repositoryPath + ".git").ToString();

        gitUrl = gitUrl._ReplaceStr("https://", $"https://*****:*****@");

        await Lfs.CreateDirectoryAsync(localDir);

        // localDir ディレクトリに .git ディレクトリは存在するか?
        string dotgitDir = localDir._CombinePath(".git");

        bool init = false;

        StrDictionary <string> envVars = new StrDictionary <string>();

        // empty config
        string emptyCfgPath = Env.MyLocalTempDir._CombinePath("empty.txt");

        using (await Lock1.LockWithAwait(cancel))
        {
            if (await Lfs.IsFileExistsAsync(emptyCfgPath, cancel) == false)
            {
                await Lfs.WriteStringToFileAsync(emptyCfgPath, "\n\n", cancel : cancel);
            }
        }

        envVars.Add("GIT_CONFIG_GLOBAL", emptyCfgPath);
        envVars.Add("GIT_CONFIG_SYSTEM", emptyCfgPath);

        if (await Lfs.IsDirectoryExistsAsync(dotgitDir, cancel))
        {
            try
            {
                // update を試みる
                await EasyExec.ExecAsync(this.GitExe, $"pull origin {branch}", localDir, cancel : cancel, additionalEnvVars : envVars);
            }
            catch (Exception ex)
            {
                ex._Error();
                init = true;
            }
        }
        else
        {
            init = true;
        }

        if (init)
        {
            // 初期化する
            await Lfs.DeleteDirectoryAsync(localDir, true, cancel : cancel, forcefulUseInternalRecursiveDelete : true);

            // git clone をする
            await EasyExec.ExecAsync(this.GitExe, $"clone {gitUrl} {localDir}", cancel : cancel, additionalEnvVars : envVars);

            // update を試みる
            await EasyExec.ExecAsync(this.GitExe, $"pull origin {branch}", localDir, cancel : cancel, additionalEnvVars : envVars);
        }
    }
    protected override async Task GetValueAsync(SortedDictionary <string, string> ret, RefInt nextPollingInterval, CancellationToken cancel = default)
    {
        // sys/class/thermal/ から温度取得
        foreach (var thermalFile in this.ThermalFiles)
        {
            string value = (await Lfs.ReadStringFromFileAsync(thermalFile.Value))._GetFirstFilledLineFromLines();

            double d = ((double)value._ToInt()) / 1000.0;

            ret.TryAdd($"{thermalFile.Key}", NormalizeDoubleValue(d.ToString("F3")));
        }

        if (IsSensorsCommandOk)
        {
            try
            {
                // Sensors コマンドで温度取得
                var result = await EasyExec.ExecAsync(Consts.LinuxCommands.Sensors, "-u", cancel : cancel);

                string[] lines = result.OutputStr._GetLines(true);

                string groupName = "";
                string fieldName = "";

                foreach (string line2 in lines)
                {
                    string line = line2.TrimEnd();

                    if (line.StartsWith(" ") == false && line._InStr(":") == false)
                    {
                        // グループ名
                        groupName = line.Trim();
                    }
                    else if (line.StartsWith(" ") == false && line.EndsWith(":"))
                    {
                        // 値名
                        fieldName = line.Substring(0, line.Length - 1);
                    }
                    else if (line.StartsWith(" ") && line._GetKeyAndValue(out string key, out string value, ":"))
                    {
                        // 値サブ名 : 値
                        key   = key.Trim();
                        value = value.Trim();

                        if (key.EndsWith("_input", StringComparison.OrdinalIgnoreCase))
                        {
                            ret.TryAdd($"{groupName}/{fieldName}", NormalizeDoubleValue(value));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex._Debug();
            }
        }
    }
示例#7
0
        public async Task <byte[]> SignSeInternalAsync(ReadOnlyMemory <byte> srcData, string certName, string flags, string comment, int numRetry = 5, CancellationToken cancel = default)
        {
            if (SeInternalPasswordCache._IsEmpty())
            {
                SeInternalPasswordCache = await Lfs.ReadStringFromFileAsync(SeInternalPasswordFilePath, oneLine : true);
            }

            return(await SignAsync(SeInternalPasswordCache, srcData, certName, flags, comment, numRetry, cancel));
        }
        public static SafeFileHandle OpenHandle(string fullPath, bool asDirectory, bool writeMode = false, bool backupMode = false, bool asyncMode = true, int additionalFlags = 0)
        {
            string root = fullPath.Substring(0, Win32PathInternal.GetRootLength(fullPath.AsSpan()));

            if (root == fullPath && root[1] == Path.VolumeSeparatorChar)
            {
                // intentionally not fullpath, most upstack public APIs expose this as path.
                throw new ArgumentException("path");
            }

            if (asyncMode)
            {
                additionalFlags |= (int)FileOptions.Asynchronous;
            }

            using (Lfs.EnterDisableMediaInsertionPrompt())
            {
                SafeFileHandle handle = Win32Api.Kernel32.CreateFile(
                    fullPath,
                    writeMode ? Win32Api.Kernel32.GenericOperations.GENERIC_WRITE | Win32Api.Kernel32.GenericOperations.GENERIC_READ : Win32Api.Kernel32.GenericOperations.GENERIC_READ,
                    FileShare.ReadWrite | FileShare.Delete,
                    FileMode.Open,
                    ((asDirectory || backupMode) ? Win32Api.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS : 0) | additionalFlags);

                if (handle.IsInvalid)
                {
                    int errorCode = Marshal.GetLastWin32Error();

                    // NT5 oddity - when trying to open "C:\" as a File,
                    // we usually get ERROR_PATH_NOT_FOUND from the OS.  We should
                    // probably be consistent w/ every other directory.
                    if (!asDirectory && errorCode == Win32Api.Errors.ERROR_PATH_NOT_FOUND && fullPath.Equals(Directory.GetDirectoryRoot(fullPath)))
                    {
                        errorCode = Win32Api.Errors.ERROR_ACCESS_DENIED;
                    }

                    throw PalWin32FileStream.GetExceptionForWin32Error(errorCode, fullPath);
                }

                if (((FileOptions)additionalFlags).Bit(FileOptions.Asynchronous))
                {
                    handle._SetAsync(true);
                    ThreadPool.BindHandle(handle);
                }
                else
                {
                    handle._SetAsync(false);
                }

                return(handle);
            }
        }
        static int Git(ConsoleService c, string cmdName, string str)
        {
            ConsoleParam[]        args = { };
            ConsoleParamValueList vl   = c.ParseCommandList(cmdName, str, args);

            if (Lfs.IsDirectoryExists(GitTestBaseDir) == false)
            {
                Git_Test_Clone();
            }

            Git_Test_1();

            return(0);
        }
示例#10
0
            async Task ProcessDirectoryAsync(ProgressReporterBase r, string dirName)
            {
                var entities = await Lfs.EnumDirectoryAsync(dirName, false, EnumDirectoryFlags.None);

                foreach (var file in entities.Where(x => x.IsFile && x.IsSymbolicLink == false))
                {
                    TotalReadNum++;

                    try
                    {
                        //Con.WriteLine($"File '{file.FullPath}'");

                        using (var f = Lfs.Open(file.FullPath))
                        {
                            while (true)
                            {
                                int readSize = await f.ReadAsync(this.TmpBuffer);

                                if (readSize == 0)
                                {
                                    break;
                                }

                                TotalReadSize += readSize;

                                r.ReportProgress(new ProgressData(TotalReadSize));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Con.WriteError($"Reading the file '{file.FullPath}' error. {ex.Message}");
                        TotalErrorNum++;
                    }
                }

                foreach (var dir in entities.Where(x => x.IsDirectory && x.Attributes.Bit(FileAttributes.ReparsePoint) == false && x.IsSymbolicLink == false))
                {
                    try
                    {
                        //Con.WriteLine($"Directory '{dir.FullPath}'");

                        await ProcessDirectoryAsync(r, dir.FullPath);
                    }
                    catch (Exception ex)
                    {
                        Con.WriteError($"Processing the directory '{dir.FullPath}' error. {ex.Message}");
                    }
                }
            }
示例#11
0
    // ファイルから復元
    public ThinMemoryDb(string filePath)
    {
        ThinMemoryDb?tmp = Lfs.ReadJsonFromFile <ThinMemoryDb>(filePath, maxSize: Consts.Numbers.LocalDatabaseJsonFileMaxSize, nullIfError: true);

        if (tmp == null)
        {
            tmp = Lfs.ReadJsonFromFile <ThinMemoryDb>(filePath + ".bak", maxSize: Consts.Numbers.LocalDatabaseJsonFileMaxSize, nullIfError: false);
        }

        this.SvcList     = tmp.SvcList;
        this.MachineList = tmp.MachineList;
        this.VarList     = tmp.VarList;

        BuildOnMemoryData();
    }
示例#12
0
        public static bool CheckFileDigitalSignature(ReadOnlyMemory <byte> data, bool checkDriverSignature = false)
        {
            string tmpPath = Lfs.SaveToTempFile("dat", data);

            bool b1 = CheckFileDigitalSignature(tmpPath);

            bool b2 = true;

            if (checkDriverSignature)
            {
                b2 = IsKernelModeSignedFile(data.Span);
            }

            return(b1 && b2);
        }
示例#13
0
        public static void WriteToFile(string path, string bodyString, Encoding?encoding = null, bool writeBom = false, bool noDebug = false)
        {
            bodyString = bodyString._NonNull();
            bodyString = Str.NormalizeCrlf(bodyString, CrlfStyle.LocalPlatform);

            Lfs.WriteStringToFile(path, bodyString, FileFlags.AutoCreateDirectory | FileFlags.WriteOnlyIfChanged,
                                  encoding: encoding, writeBom: writeBom);

            if (noDebug == false)
            {
                Con.WriteDebug($"--- WriteToFile \"{path}\" ---");
                Con.WriteDebug(bodyString);
                Con.WriteDebug($"--- EOF ---");
                Con.WriteDebug();
            }
        }
示例#14
0
    public long SaveToFile(string filePath)
    {
        string backupPath = filePath + ".bak";

        try
        {
            if (Lfs.IsFileExists(filePath))
            {
                Lfs.CopyFile(filePath, backupPath);
            }
        }
        catch (Exception ex)
        {
            ex._Error();
        }

        return(Lfs.WriteJsonToFile(filePath, this, flags: FileFlags.AutoCreateDirectory | FileFlags.OnCreateSetCompressionFlag));
    }
示例#15
0
        static string GenerateNewRepositoryDirName(string repoUrl)
        {
            repoUrl = repoUrl.Trim().ToLower();

            string repoName = LinuxParser.GetFileNameWithoutExtension(LinuxParser.RemoveLastSeparatorChar(repoUrl));

            DateTime now = DateTime.Now;

            for (int i = 1; ; i++)
            {
                string name     = $"{Lfs.PathParser.MakeSafeFileName(repoName)}_{now.Year:D4}{now.Month:D2}{now.Day:D2}_{Env.ProcessId}_{i:D5}";
                string fullPath = Lfs.PathParser.Combine(RepoDir, name);

                if (Lfs.IsDirectoryExists(fullPath) == false)
                {
                    return(name);
                }
            }
        }
示例#16
0
        public DaemonCenterServerRpcHttpHost(Server daemonCenterServer)
        {
            try
            {
                // Start Log Server
                string certVaultDir = Lfs.ConfigPathStringToPhysicalDirectoryPath(@"Local/DaemonCenterRpc_CertVault/");

                this.CertVault = new CertVault(certVaultDir,
                                               new CertVaultSettings(EnsureSpecial.Yes)
                {
                    ReloadIntervalMsecs = 3600 * 1000,
                    UseAcme             = false,
                    NonAcmeEnableAutoGenerateSubjectNameCert = false,
                });

                PalSslServerAuthenticationOptions sslOptions = new PalSslServerAuthenticationOptions(this.CertVault.X509CertificateSelector("dummy", true), true, null);

                this.DaemonCenterServer = daemonCenterServer;

                JsonRpcServerConfig rpcCfg = new JsonRpcServerConfig();

                HttpServerOptions httpConfig = new HttpServerOptions
                {
                    HttpPortsList  = new List <int>(),
                    HttpsPortsList = Consts.Ports.DaemonCenterHttps._SingleList(),
                    UseStaticFiles = false,
                    AutomaticRedirectToHttpsIfPossible = false,
                    HiveName           = "DaemonCenterRpcHttpServer",
                    DenyRobots         = true,
                    UseGlobalCertVault = false,
                    ServerCertSelector = (param, sni) => (X509Certificate2)(this.CertVault.X509CertificateSelector(sni, true).NativeCertificate),
                };

                this.HttpServer = JsonRpcHttpServerBuilder.StartServer(httpConfig, rpcCfg, this.DaemonCenterServer);
            }
            catch
            {
                this._DisposeSafe();
                throw;
            }
        }
示例#17
0
        public AssemblyWithSourceInfo(Type sampleType, params SourceCodePathAndMarkerFileName[] sourceInfoList)
        {
            this.Assembly = sampleType.Assembly;

            List <DirectoryPath> srcRootList = new List <DirectoryPath>();

            foreach (SourceCodePathAndMarkerFileName srcInfo in sourceInfoList)
            {
                try
                {
                    DirectoryPath?root = Lfs.DetermineRootPathWithMarkerFile(srcInfo.SourceCodePath, srcInfo.MarkerFileName);
                    if (root != null)
                    {
                        srcRootList.Add(root);
                    }
                }
                catch { }
            }

            this.SourceRootList = srcRootList;
        }
示例#18
0
        static int RawDiskRestore(ConsoleService c, string cmdName, string str)
        {
            ConsoleParam[] args =
            {
                new ConsoleParam("[diskName]", ConsoleService.Prompt, "Physical disk name: ", ConsoleService.EvalNotEmpty, null),
                new ConsoleParam("src",        ConsoleService.Prompt, "Source file name: ",   ConsoleService.EvalNotEmpty, null),
                new ConsoleParam("truncate"),
            };

            ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);

            string diskName    = vl.DefaultParam.StrValue;
            string dstFileName = vl["src"].StrValue;
            long   truncate    = vl["truncate"].StrValue._ToLong();

            if (truncate <= 0)
            {
                truncate = -1;
            }
            else
            {
                truncate = (truncate + 4095L) / 4096L * 4096L;
            }

            using (var rawFs = new LocalRawDiskFileSystem())
            {
                using (var disk = rawFs.Open($"/{diskName}", writeMode: true))
                {
                    using (var file = Lfs.Open(dstFileName, flags: FileFlags.AutoCreateDirectory))
                    {
                        using (var reporter = new ProgressReporter(new ProgressReporterSetting(ProgressReporterOutputs.Console, toStr3: true), null))
                        {
                            FileUtil.CopyBetweenFileBaseAsync(file, disk, truncateSize: truncate, param: new CopyFileParams(asyncCopy: true, bufferSize: 16 * 1024 * 1024), reporter: reporter)._GetResult();
                        }
                    }
                }
            }

            return(0);
        }
示例#19
0
    // UNIX におけるコマンド名からフルパスを取得する (指定されたファイル名がフルパスとして見つからない場合)
    public string UnixGetFullPathFromCommandName(string commandName)
    {
        if (Env.IsUnix == false)
        {
            throw new ArgumentException("Env.IsUnix == false");
        }
        if (commandName._IsEmpty())
        {
            throw new ArgumentException(nameof(commandName));
        }

        commandName = commandName.Trim();

        if (this.PathParser.IsAbsolutePath(commandName))
        {
            if (Lfs.IsFileExists(commandName))
            {
                // 最初から指定されたフルパスが存在する
                return(commandName);
            }

            // 指定されたフルパスにファイルが存在しない。コマンド名だけを取り出して解決しようと試みる。
            commandName = this.PathParser.GetFileName(commandName);
        }

        lock (CommandNamdToFullPathCache)
        {
            return(CommandNamdToFullPathCache._GetOrNew(commandName, () =>
            {
                string fullPath = UnixGetFullPathFromCommandNameInternal(commandName);

                if (fullPath._IsEmpty())
                {
                    throw new CoresException($"The full path of UNIX command '{commandName}' not found.");
                }

                return fullPath;
            }));
        }
    }
示例#20
0
    static int PrependLineNumber(ConsoleService c, string cmdName, string str)
    {
        ConsoleParam[] args =
        {
            new ConsoleParam("[srcFile]", ConsoleService.Prompt, "Src File Path: ",  ConsoleService.EvalNotEmpty, null),
            new ConsoleParam("DEST",      ConsoleService.Prompt, "Dest File Path: ", ConsoleService.EvalNotEmpty, null),
        };

        ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);

        string src  = vl.DefaultParam.StrValue;
        string dest = vl["DEST"].StrValue;

        if (src._IsSamei(dest))
        {
            Con.WriteError("Source is Dest.");
            return(1);
        }

        var body = Lfs.ReadStringFromFile(src);

        string[] lines = body._GetLines(singleLineAtLeast: true);

        int keta = lines.Length.ToString().Length;

        StringWriter w = new StringWriter();

        for (int i = 0; i < lines.Length; i++)
        {
            string lineStr = (i + 1).ToString("D" + keta);
            string tmp     = lineStr + ": " + lines[i];

            w.WriteLine(tmp);
        }

        Lfs.WriteStringToFile(dest, w.ToString(), writeBom: true, flags: FileFlags.AutoCreateDirectory);

        return(0);
    }
示例#21
0
        public static void RebootOperatingSystemForcefullyDangerous()
        {
            if (Env.IsLinux)
            {
                if (RebootOnceFlag.IsFirstCall())
                {
                    // sync, sync, sync
                    for (int i = 0; i < 3; i++)
                    {
                        UnixTryRunSystemProgram(EnsureInternal.Yes, Consts.LinuxCommands.Sync, "", CoresConfig.Timeouts.RebootDangerous_Sync_Timeout);
                    }

                    Sleep(300);

                    // reboot
                    for (int i = 0; i < 3; i++)
                    {
                        UnixTryRunSystemProgram(EnsureInternal.Yes, Consts.LinuxCommands.Reboot, "--reboot --force", CoresConfig.Timeouts.RebootDangerous_Reboot_Timeout);
                    }

                    Sleep(300);

                    // reboot with BIOS (最後の手段)
                    Lfs.WriteStringToFile(@"/proc/sys/kernel/sysrq", "1");

                    Sleep(300);

                    Lfs.WriteStringToFile(@"/proc/sysrq-trigger", "b");
                }
                else
                {
                    throw new CoresException("Already rebooting");
                }
            }
            else
            {
                throw new NotImplementedException();
            }
        }
示例#22
0
    public StatMan(StatManConfig config)
    {
        try
        {
            // this.Config = config._CloneDeep(); DO NOT CLONE THIE OBJECT!! delegate をクローンすると不具合が発生します。
            this.Config = config;

            this.Config.Callback = config.Callback;

            this.Config.Normalize();

            this.FileNameFullPath = this.Config.StatFileName;
            if (PP.IsAbsolutePath(this.Config.StatFileName) == false)
            {
                this.FileNameFullPath = Env.AppLocalDir._CombinePath("Config", "Statistics", this.Config.StatFileName);
            }

            this.FileNameFullPath = PP.NormalizeDirectorySeparator(this.FileNameFullPath, true);

            this.Database = Lfs.ReadJsonFromFileEncrypted <StatManDatabase>(this.FileNameFullPath, Consts.Strings.StatManEncryptKey, nullIfError: true);
            if (this.Database == null)
            {
                this.Database = new StatManDatabase();
            }

            this.Database.Normalize();

            NormalizeAndPollAsync(noPoll: true)._GetResult();

            this.SaveTask = SaveTaskProcAsync(this.GrandCancel)._LeakCheck();
            this.PostTask = PostTaskProcAsync(this.GrandCancel)._LeakCheck();
        }
        catch (Exception ex)
        {
            this._DisposeSafe(ex);
            throw;
        }
    }
示例#23
0
        static int MergeResourceHeader(ConsoleService c, string cmdName, string str)
        {
            string baseFile   = @"C:\git\IPA-DNP-DeskVPN\src\PenCore\resource.h";
            string targetFile = @"C:\sec\Desk\current\Desk\DeskVPN\PenCore\resource.h";
            string destFile   = @"c:\tmp\200404\resource.h";
            int    minId      = 2500;

            var baseDict   = DevTools.ParseHeaderConstants(Lfs.ReadStringFromFile(baseFile));
            var targetDict = DevTools.ParseHeaderConstants(Lfs.ReadStringFromFile(targetFile));

            KeyValueList <string, int> adding = new KeyValueList <string, int>();

            // 利用可能な ID の最小値
            int newId = Math.Max(baseDict.Values.Where(x => x < 40000).Max(), minId);

            foreach (var kv in targetDict.OrderBy(x => x.Value))
            {
                if (baseDict.ContainsKey(kv.Key) == false)
                {
                    adding.Add(kv.Key, ++newId);
                }
            }

            // 結果を出力
            StringWriter w = new StringWriter();

            foreach (var kv in adding)
            {
                int paddingCount = Math.Max(31 - kv.Key.Length, 0);

                w.WriteLine($"#define {kv.Key}{Str.MakeCharArray(' ', paddingCount)} {kv.Value}");
            }

            Lfs.WriteStringToFile(destFile, w.ToString(), FileFlags.AutoCreateDirectory);

            return(0);
        }
示例#24
0
    public static async Task DownloadGraphsAsync(string destDir, string baseUrl, string username, string password, IEnumerable <int> targetGraphIdList, CancellationToken cancel = default)
    {
        using var r = new CactiSession(baseUrl, username, password);

        List <CactiDownloadedGraph> list = new List <CactiDownloadedGraph>();

        foreach (int id in targetGraphIdList.Distinct())
        {
            await r.EnsureLoginAsync(cancel);

            Con.WriteLine($"Downloading id = {id} ...");

            try
            {
                var tmp = await r.DownloadGraphAsync(id, 1, 6, cancel);

                tmp._DoForEach(x => list.Add(x));
            }
            catch
            {
            }
        }

        if (list.Count == 0)
        {
            throw new CoresException($"Download cacti graphs failed.");
        }

        Con.WriteLine("Done.");

        foreach (var g in list)
        {
            string fn = destDir._CombinePath("graph_size_" + g.Size + "_id_" + g.GraphId.ToString("D5") + "_rra_" + g.RraId.ToString("D5") + ".png");

            Lfs.WriteDataToFile(fn, g.Data, FileFlags.AutoCreateDirectory);
        }
    }
    protected override void InitImpl(object?param = null)
    {
        // sensors コマンドが利用可能かどうか確認
        if (EasyExec.ExecAsync(Consts.LinuxCommands.Sensors, "-u")._TryGetResult() != default)
        {
            IsSensorsCommandOk = true;
        }

        // /sys/class/thermal/ から取得可能な値一覧を列挙
        FileSystemEntity[]? dirList = null;
        try
        {
            dirList = Lfs.EnumDirectory(Consts.LinuxPaths.SysThermal);
        }
        catch { }

        if (dirList != null)
        {
            foreach (var dir in dirList)
            {
                string fileName = Lfs.PathParser.Combine(dir.FullPath, "temp");

                if (Lfs.IsFileExists(fileName))
                {
                    try
                    {
                        Lfs.ReadStringFromFile(fileName);

                        ThermalFiles.Add(dir.Name, fileName);
                    }
                    catch
                    {
                    }
                }
            }
        }
    }
示例#26
0
        public static async Task <EasyExecResult> ExecBashAsync(string command, string?currentDirectory = null,
                                                                ExecFlags flags          = ExecFlags.Default | ExecFlags.EasyInputOutputMode,
                                                                int easyOutputMaxSize    = Consts.Numbers.DefaultLargeBufferSize, string?easyInputStr = null, int?timeout = null,
                                                                CancellationToken cancel = default, bool debug = false, bool throwOnErrorExitCode = true,
                                                                string printTag          = "",
                                                                Func <string, Task <bool> >?easyOneLineRecvCallbackAsync = null,
                                                                Func <ReadOnlyMemory <byte>, ReadOnlyMemory <byte>, Task <bool> >?easyRealtimeRecvBufCallbackAsync = null,
                                                                int easyRealtimeRecvBufCallbackDelayTickMsecs = 0, StrDictionary <string>?additionalEnvVars = null)
        {
            if (timeout <= 0)
            {
                timeout = Timeout.Infinite;
            }

            List <string> args = new List <string>();

            args.Add("-c");
            args.Add(command);

            ExecOptions opt = new ExecOptions(Lfs.UnixGetFullPathFromCommandName(Consts.LinuxCommands.Bash),
                                              args, currentDirectory, flags, easyOutputMaxSize, easyInputStr, printTag,
                                              easyOneLineRecvCallbackAsync, easyRealtimeRecvBufCallbackAsync, easyRealtimeRecvBufCallbackDelayTickMsecs, additionalEnvVars);

            if (debug)
            {
                Dbg.WriteLine($"ExecBashAsync: --- Starting bash command \"{command}\" ---");
            }

            EasyExecResult result;

            try
            {
                using ExecInstance exec = new ExecInstance(opt);

                try
                {
                    await exec.WaitForExitAsync(timeout._NormalizeTimeout(CoresConfig.Timeouts.DefaultEasyExecTimeout), cancel);
                }
                finally
                {
                    await exec.CancelAsync();
                }

                result = new EasyExecResult(exec);
            }
            catch (Exception ex)
            {
                Dbg.WriteLine($"Error on bash process \"{command}\". Exception: {ex.Message}");
                throw;
            }

            if (debug)
            {
                Dbg.WriteLine($"ExecAsync: The result of bash \"{command}\": " + result.ToString(Str.GetCrlfStr(), false));
            }

            if (throwOnErrorExitCode)
            {
                result.ThrowExceptionIfError();
            }

            return(result);
        }
示例#27
0
 public static CactiTask LoadFromFile(string filename) => LoadFromData(Lfs.ReadDataFromFile(filename).Span);
示例#28
0
        static int SslCertListCollector(ConsoleService c, string cmdName, string str)
        {
            ConsoleParam[] args =
            {
                new ConsoleParam("[dnsZonesDir]", ConsoleService.Prompt, "dnsZonesDir: ", ConsoleService.EvalNotEmpty, null),
                new ConsoleParam("OUT",           ConsoleService.Prompt, "outDir: ",      ConsoleService.EvalNotEmpty, null),
                new ConsoleParam("HASH"),
            };
            ConsoleParamValueList vl = c.ParseCommandList(cmdName, str, args);

            string dirZonesDir = vl.DefaultParam.StrValue;
            string outDir      = vl["OUT"].StrValue;
            string hashliststr = vl["HASH"].StrValue;

            string[] hashlist = hashliststr._Split(StringSplitOptions.RemoveEmptyEntries, ";", "/", ",", ":", " ");

            var dirList = Lfs.EnumDirectory(dirZonesDir, false);

            if (dirList.Where(x => x.IsFile && (IgnoreCaseTrim)Lfs.PathParser.GetExtension(x.Name) == ".dns").Any() == false)
            {
                // 指定されたディレクトリに *.dns ファイルが 1 つもない場合は子ディレクトリ名をソートして一番大きいものを選択する
                dirZonesDir = dirList.OrderByDescending(x => x.Name).Where(x => x.IsDirectory).Select(x => x.FullPath).First();
            }

            Con.WriteLine($"Target directory: '{dirZonesDir}'");

            // 1. DNS ゾーンファイルを入力してユニークな FQDN レコードの一覧を生成する
            DnsFlattenUtil flat = new DnsFlattenUtil();

            foreach (FileSystemEntity ent in Lfs.EnumDirectory(dirZonesDir, true))
            {
                if (ent.IsFile)
                {
                    string fn = ent.FullPath;
                    fn._Print();

                    flat.InputZoneFile(Lfs.PathParser.GetFileNameWithoutExtension(fn), Lfs.ReadDataFromFile(fn).Span);
                }
            }

            // 2. FQDN の一覧を入力して FQDN と IP アドレスのペアの一覧を生成する
            DnsIpPairGeneratorUtil pairGenerator = new DnsIpPairGeneratorUtil(100, flat.FqdnSet);

            List <SniHostnameIpAddressPair> list = pairGenerator.ExecuteAsync()._GetResult().ToList();

            // 3. FQDN と IP アドレスのペアの一覧を入力して SSL 証明書一覧を出力する
            SslCertCollectorUtil col = new SslCertCollectorUtil(1000, list);

            IReadOnlyList <SslCertCollectorItem> ret = col.ExecuteAsync()._GetResult();

            if (hashlist.Length >= 1)
            {
                List <SslCertCollectorItem> filtered = new List <SslCertCollectorItem>();
                ret.Where(x => hashlist.Where(y => y._IsSameHex(x.CertHashSha1)).Any())._DoForEach(x => filtered.Add(x));
                ret = filtered;
            }

            ret = ret.OrderBy(x => x.FriendName._NonNullTrim()._Split(StringSplitOptions.RemoveEmptyEntries, ".").Reverse()._Combine("."), StrComparer.IgnoreCaseTrimComparer).ToList();

            // 結果表示
            Con.WriteLine($"Results: {ret.Count} endpoints");

            // 結果保存
            string csv = ret._ObjectArrayToCsv(withHeader: true);

            XmlAndXsd xmlData = Util.GenerateXmlAndXsd(ret);

            string dir = outDir;

            Lfs.WriteDataToFile(Lfs.PathParser.Combine(dir, xmlData.XmlFileName), xmlData.XmlData, flags: FileFlags.AutoCreateDirectory);
            Lfs.WriteDataToFile(Lfs.PathParser.Combine(dir, xmlData.XsdFileName), xmlData.XsdData, flags: FileFlags.AutoCreateDirectory);
            Lfs.WriteStringToFile(Lfs.PathParser.Combine(dir, "csv.csv"), csv, flags: FileFlags.AutoCreateDirectory, writeBom: true);

            return(0);
        }
    protected override async Task GetValueAsync(SortedDictionary <string, string> ret, RefInt nextPollingInterval, CancellationToken cancel = default)
    {
        if (IsConnTrackOk)
        {
            try
            {
                // ConnTrack
                var result = await EasyExec.ExecAsync(Consts.LinuxCommands.ConnTrack, "-C");

                string valueStr = result.OutputStr._GetFirstFilledLineFromLines();

                ret.TryAdd($"ConnTrack Sessions", valueStr._ToInt().ToString());
            }
            catch (Exception ex)
            {
                ex._Debug();
            }
        }

        if (true)
        {
            try
            {
                // Threads
                var result = EasyExec.ExecBashAsync("ps -eo nlwp | tail -n +2 | awk '{ num_threads += $1 } END { print num_threads }'")._GetResult();

                string valueStr = result.OutputStr._GetFirstFilledLineFromLines();

                ret.TryAdd($"Threads", valueStr._ToInt().ToString());
            }
            catch (Exception ex)
            {
                ex._Debug();
            }
        }

        if (true)
        {
            try
            {
                // FDs
                string result = await Lfs.ReadStringFromFileAsync(Consts.LinuxPaths.FileNr, flags : FileFlags.NoCheckFileSize);

                string valueStr = result._GetFirstFilledLineFromLines();

                string[] tokens = valueStr._Split(StringSplitOptions.RemoveEmptyEntries, " ", "\t");

                int numFd = -1;

                if (tokens.Length >= 1)
                {
                    numFd = tokens[0]._ToInt();
                }

                ret.TryAdd($"FDs", numFd.ToString());
            }
            catch (Exception ex)
            {
                ex._Debug();
            }
        }

        if (true)
        {
            try
            {
                // Sockets
                string[] lines = (await Lfs.ReadStringFromFileAsync(Consts.LinuxPaths.SockStat, flags: FileFlags.NoCheckFileSize))._GetLines();

                int numSockets = -1;
                int numTcp     = -1;
                int numUdp     = -1;

                foreach (string line in lines)
                {
                    string[] tokens = line._Split(StringSplitOptions.RemoveEmptyEntries, " ");

                    if (tokens.Length >= 3)
                    {
                        if (tokens[0]._IsSamei("sockets:"))
                        {
                            numSockets = tokens[2]._ToInt();
                        }

                        if (tokens[0]._IsSamei("TCP:"))
                        {
                            numTcp = tokens[2]._ToInt();
                        }

                        if (tokens[0]._IsSamei("UDP:"))
                        {
                            numUdp = tokens[2]._ToInt();
                        }
                    }
                }

                if (numSockets >= 0 && numTcp >= 0 && numUdp >= 0)
                {
                    ret.TryAdd($"Sockets", numSockets.ToString());
                    ret.TryAdd($"TCP", numTcp.ToString());
                    ret.TryAdd($"UDP", numUdp.ToString());
                }
            }
            catch (Exception ex)
            {
                ex._Debug();
            }
        }
    }
 protected override void InitImpl(object?param = null)
 {
     isBirdcExists  = Lfs.IsFileExists(Consts.LinuxCommands.Birdc);
     isBirdc6Exists = Lfs.IsFileExists(Consts.LinuxCommands.Birdc6);
 }