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();
            }
        }
Example #2
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);
    }
Example #3
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();
            }
        }
Example #4
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);
        }
Example #5
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);
        }
Example #6
0
        static int ConvertTextFiles(ConsoleService c, string cmdName, string str)
        {
            ConsoleParam[] args =
            {
                new ConsoleParam("[srcdir]", ConsoleService.Prompt, "Input source directory: ",      ConsoleService.EvalNotEmpty, null),
                new ConsoleParam("dst",      ConsoleService.Prompt, "Input destination directory: ", ConsoleService.EvalNotEmpty, null),
                new ConsoleParam("encode"),
                new ConsoleParam("bom"),
                new ConsoleParam("newline"),
            };

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

            string srcdir = vl.DefaultParam.StrValue;

            string dstdir = vl["dst"].StrValue;

            string encode = vl["encode"].StrValue._FilledOrDefault("utf8");

            bool bom = vl["bom"].BoolValue;

            string newline = vl["newline"].StrValue._FilledOrDefault("crlf");

            Encoding?encoding = null;

            switch (encode.ToLower())
            {
            case "sjis":
                encoding = Str.ShiftJisEncoding;
                break;

            case "euc":
                encoding = Str.EucJpEncoding;
                break;

            case "utf8":
                encoding = Str.Utf8Encoding;
                break;

            default:
                throw new CoresException("encode param is invalid.");
            }

            CrlfStyle crlfStyle = CrlfStyle.CrLf;

            switch (newline.ToLower())
            {
            case "crlf":
                crlfStyle = CrlfStyle.CrLf;
                break;

            case "lf":
                crlfStyle = CrlfStyle.Lf;
                break;

            case "platform":
                crlfStyle = CrlfStyle.LocalPlatform;
                break;

            default:
                throw new CoresException("newline param is invalid.");
            }

            var srcFileList = Lfs.EnumDirectory(srcdir, true);

            foreach (var srcFile in srcFileList)
            {
                if (srcFile.IsFile)
                {
                    string relativeFileName = Lfs.PathParser.GetRelativeFileName(srcFile.FullPath, srcdir);

                    string destFileName = Lfs.PathParser.Combine(dstdir, relativeFileName);

                    string body = Lfs.ReadStringFromFile(srcFile.FullPath);

                    body = Str.NormalizeCrlf(body, crlfStyle);

                    Con.WriteLine(relativeFileName);

                    Lfs.WriteStringToFile(destFileName, body, FileFlags.AutoCreateDirectory, encoding: encoding, writeBom: bom);
                }
            }

            return(0);
        }
Example #7
0
        static int GoogleMapsDirectionCross(ConsoleService c, string cmdName, string str)
        {
            ConsoleParam[] args =
            {
                new ConsoleParam("[dir]", ConsoleService.Prompt, "Directory path: ", ConsoleService.EvalNotEmpty, null),
            };

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

            string dir = vl.DefaultParam.StrValue;

            string apiKey = Lfs.ReadStringFromFile(dir._CombinePath("ApiKey.txt"), oneLine: true);

            string srcListText  = Lfs.ReadStringFromFile(dir._CombinePath("Source.txt"));
            string destListText = Lfs.ReadStringFromFile(dir._CombinePath("Destination.txt"));

            string[] srcList  = srcListText._GetLines(removeEmpty: true);
            string[] destList = destListText._GetLines(removeEmpty: true);

            using var googleMapsApi = new GoogleMapsApi(new GoogleMapsApiSettings(apiKey: apiKey));

            DateTimeOffset departure = Util.GetStartOfDay(DateTime.Now.AddDays(2))._AsDateTimeOffset(isLocalTime: true);

            List <DirectionCrossResults> csv = new List <DirectionCrossResults>();

            foreach (string src in srcList)
            {
                foreach (string dest in destList)
                {
                    Console.WriteLine($"「{src}」 → 「{dest}」 ...");

                    DirectionCrossResults r = new DirectionCrossResults();

                    r.Start = src;
                    r.End   = dest;

                    try
                    {
                        var result = googleMapsApi.CalcDurationAsync(src, dest, departure)._GetResult();

                        if (result.IsError == false)
                        {
                            r.StartAddress = result.StartAddress;
                            r.EndAddress   = result.EndAddress;
                            r.Error        = "";
                            r.Duration     = result.Duration;
                            r.DistanceKm   = result.DistanceKm;
                            r.RouteSummary = result.RouteSummary;

                            $"  {r.Duration} - {r.DistanceKm} km ({r.RouteSummary})"._Print();
                        }
                        else
                        {
                            r.Error = result.ErrorString;
                            r.Error._Print();
                        }
                    }
                    catch (Exception ex)
                    {
                        ex._Debug();
                        r.Error = ex.Message;
                    }

                    csv.Add(r);
                }
            }

            string csvText = csv._ObjectArrayToCsv(withHeader: true);

            Lfs.WriteStringToFile(dir._CombinePath("Result.csv"), csvText, writeBom: true);

            return(0);
        }
        public void ExecMain()
        {
            if (Once.IsFirstCall() == false)
            {
                throw new ApplicationException("StartMainLoop can be called only once.");
            }

            this.SingleInstance = new SingleInstance($"UserModeService_{this.Name}");

            try
            {
                string?         eventName   = null;
                EventWaitHandle?eventHandle = null;

                if (Env.IsUnix)
                {
                    System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += UnixSigTermHandler;
                }
                else
                {
                    eventName = @"Global\usermodesvc_" + Util.Rand(16)._GetHexString().ToLower();

                    eventHandle = new EventWaitHandle(false, EventResetMode.ManualReset, eventName);

                    TaskUtil.StartSyncTaskAsync(() =>
                    {
                        eventHandle.WaitOne();

                        Win32PipeRecvHandler();
                    }, leakCheck: false)._LaissezFaire(true);
                }

                // Start the TelnetLogWatcher
                List <IPEndPoint> telnetWatcherEpList = new List <IPEndPoint>();

                telnetWatcherEpList.Add(new IPEndPoint(IPAddress.Loopback, HiveData.ManagedData.LocalLogWatchPort));
                telnetWatcherEpList.Add(new IPEndPoint(IPAddress.IPv6Loopback, HiveData.ManagedData.LocalLogWatchPort));

                if (this.TelnetLogWatcherPort != 0)
                {
                    telnetWatcherEpList.Add(new IPEndPoint(IPAddress.Any, this.TelnetLogWatcherPort));
                    telnetWatcherEpList.Add(new IPEndPoint(IPAddress.IPv6Any, this.TelnetLogWatcherPort));
                }

                TelnetWatcher = new TelnetLocalLogWatcher(new TelnetStreamWatcherOptions((ip) => ip._GetIPAddressType().BitAny(IPAddressType.LocalUnicast | IPAddressType.Loopback), null,
                                                                                         telnetWatcherEpList.ToArray()));

                InternalStart();

                lock (HiveData.DataLock)
                {
                    HiveData.ManagedData.Pid       = Env.ProcessId;
                    HiveData.ManagedData.EventName = eventName;
                }

                HiveData.SyncWithStorage(HiveSyncFlags.SaveToFile, true);

                // Save pid
                string pidFileName = Lfs.PathParser.Combine(CoresConfig.UserModeServiceSettings.GetLocalHiveDirProc.Value(), this.Name + ".pid");
                string pidBody     = Env.ProcessId.ToString() + Env.NewLine;
                Lfs.WriteStringToFile(pidFileName, pidBody, FileFlags.AutoCreateDirectory);

                Console.WriteLine(ExecMainSignature);

                // The daemon routine is now started. Wait here until InternalStop() is called.
                StoppedEvent.Wait();
            }
            finally
            {
                this.TelnetWatcher._DisposeSafe();
                this.TelnetWatcher = null;

                this.SingleInstance._DisposeSafe();
                this.SingleInstance = null;
            }
        }