diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f1229f --- /dev/null +++ b/.gitignore @@ -0,0 +1,350 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ \ No newline at end of file diff --git a/CefClassifier.cs b/CefClassifier.cs new file mode 100644 index 0000000..60f2317 --- /dev/null +++ b/CefClassifier.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Security.AccessControl; +using Mono.Unix; + +namespace CefDetector.Net +{ + public enum CefType + { + UNKNOWN, + EDGE, + CHROME, + LIBCEF, + ELECTRON, + ELECTRON2, + CEF_SHARP, + NWJS, + MINI_ELECTRON, + MINI_BLINK + } + + public static class CefClassifier + { + public static List searchedDir = new(); + + public static Dictionary CefByteFingerprint = new() + { + { + CefType.LIBCEF, + Encoding.UTF8 + .GetBytes( "cef_string_utf8_to_utf16" ) + }, + { + CefType.ELECTRON, + Encoding.UTF8 + .GetBytes( "third_party/electron_node" ) + }, + { + CefType.ELECTRON2, + Encoding.UTF8 + .GetBytes( "register_atom_browser_web_contents" ) + }, + { + CefType.CEF_SHARP, + Encoding.UTF8 + .GetBytes( "CefSharp.Internals" ) + }, + { + CefType.NWJS, + Encoding.UTF8.GetBytes( "url-nwjs" ) + }, + { + CefType.MINI_ELECTRON, + Encoding.UTF8 + .GetBytes( "napi_create_buffer" ) + }, + { + CefType.MINI_BLINK, + Encoding.UTF8.GetBytes( "miniblink" ) + } + }; + + public static Dictionary> + CefBaseCheck = new() + { + { + CefType.EDGE, + ( dir ) => + { + var file = Path.Join( dir.FullName, "msedge" ); + return ( File.Exists( file ), file ); + } + }, + { + CefType.CHROME, + ( dir ) => + { + var file = Path.Join( dir.FullName, "chrome" ); + return ( File.Exists( file ), file ); + } + }, + }; + + private static bool FileByteContains( byte[] file, + byte[] search ) + { + return Parallel.For( 0, + file.Length - search.Length, + ( i, + loopState ) => + { + if ( file[ i ] == search[ 0 ] ) + { + byte[] localCache = new byte[ search.Length ]; + Array.Copy( file, i, localCache, 0, search.Length ); + if ( localCache.SequenceEqual( search ) ) + loopState.Stop(); + } + } ) + .IsCompleted == + false; + } + + public static List FilterExecuteBinaries( string[] files ) + { + List executeBinaries = new(); + foreach ( string file in files ) + { + Mono.Unix.UnixFileInfo ufi = new(file); + if ( ufi.FileAccessPermissions.HasFlag( FileAccessPermissions.UserExecute | + FileAccessPermissions.GroupExecute | + FileAccessPermissions.OtherExecute ) ) + { + executeBinaries.Add( file ); + } + } + + return executeBinaries; + } + + public static Dictionary CheckDirCefType( string dirPath ) + { + if ( !Directory.Exists( dirPath ) ) return new(); + + DirectoryInfo dir = new DirectoryInfo( dirPath ); + foreach ( var (type, checkFunc) in CefBaseCheck ) + { + var (isSucc, file) = checkFunc( dir ); + if ( isSucc ) + { + return new() + { + {file, type} + }; + } + } + + return new(); + } + + public static CefType CheckBinaryCefType( string filePath ) + { + if ( !File.Exists( filePath ) ) return CefType.UNKNOWN; + + byte[] fileContent = File.ReadAllBytes( filePath ); + CefType result = CefType.UNKNOWN; + + //浏览器文件字节检查 + foreach ( var (type, bytes) in CefByteFingerprint ) + { + if ( FileByteContains( fileContent, bytes ) ) + { + return type; + } + } + + return result; + } + + public static Dictionary SearchDir( string cefPath ) + { + if ( !File.Exists( cefPath ) ) return new(); + Dictionary cefBinaries = new(); + + var dir = new FileInfo( cefPath ).Directory!; + + //不搜索之前搜索过的目录 + if ( searchedDir.Contains( dir.FullName ) ) + { + return new(); + } + else + { + searchedDir.Add( dir.FullName ); + } + + //先根据目录检查 + var dirCheckResult = CheckDirCefType( dir.FullName ); + if ( dirCheckResult.Any() ) + { + return dirCheckResult; + } + + //再搜索目录内所有文件,检查字节 + var files = FilterExecuteBinaries( Directory.GetFiles( dir.FullName, "*", SearchOption.TopDirectoryOnly ) ); + foreach ( var file in files ) + { + if ( !cefBinaries.ContainsKey( file ) ) + { + var result = CheckBinaryCefType( file ); + if ( result != CefType.UNKNOWN ) + { + cefBinaries.Add( file, result ); + } + } + } + + return cefBinaries; + } + } +} diff --git a/CefDetector.Net.csproj b/CefDetector.Net.csproj new file mode 100644 index 0000000..e3dfc31 --- /dev/null +++ b/CefDetector.Net.csproj @@ -0,0 +1,14 @@ + + + + Exe + net7.0 + enable + enable + + + + + + + diff --git a/CefDetector.Net.sln b/CefDetector.Net.sln new file mode 100644 index 0000000..30f5ad1 --- /dev/null +++ b/CefDetector.Net.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33103.184 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CefDetector.Net", "CefDetector.Net.csproj", "{392FCB02-6127-49CF-8C7A-04C31AFA2128}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {392FCB02-6127-49CF-8C7A-04C31AFA2128}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {392FCB02-6127-49CF-8C7A-04C31AFA2128}.Debug|Any CPU.Build.0 = Debug|Any CPU + {392FCB02-6127-49CF-8C7A-04C31AFA2128}.Release|Any CPU.ActiveCfg = Release|Any CPU + {392FCB02-6127-49CF-8C7A-04C31AFA2128}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {93057F90-CA85-486C-92A2-A8A545536FAC} + EndGlobalSection +EndGlobal diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f74e4ab --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 XiaoHe321 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/ProcessExecutor.cs b/ProcessExecutor.cs new file mode 100644 index 0000000..4eff76c --- /dev/null +++ b/ProcessExecutor.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CefDetector.Net +{ + public class ProcessExecutor : IDisposable + { + public event EventHandler? OnExited; + + public event EventHandler? OnOutputDataReceived; + + public event EventHandler? OnErrorDataReceived; + + protected readonly Process _process; + + protected bool _started; + + public ProcessExecutor( string binPath ) : this( new ProcessStartInfo( binPath ) ) { } + + public ProcessExecutor( string binPath, + string arguments ) : this( new ProcessStartInfo( binPath, arguments ) ) { } + + public ProcessExecutor( ProcessStartInfo startInfo ) + { + _process = new Process() + { + StartInfo = startInfo, + EnableRaisingEvents = true, + }; + _process.StartInfo.UseShellExecute = false; + _process.StartInfo.CreateNoWindow = true; + _process.StartInfo.RedirectStandardOutput = true; + _process.StartInfo.RedirectStandardInput = true; + _process.StartInfo.RedirectStandardError = true; + } + + protected virtual void InitializeEvents() + { + _process.OutputDataReceived += ( sender, + args ) => + { + if ( args.Data != null ) + { + OnOutputDataReceived?.Invoke( sender, args.Data ); + } + }; + _process.ErrorDataReceived += ( sender, + args ) => + { + if ( args.Data != null ) + { + OnErrorDataReceived?.Invoke( sender, args.Data ); + } + }; + _process.Exited += ( sender, + args ) => + { + if ( sender is Process process ) + { + OnExited?.Invoke( sender, process.ExitCode ); + } + else + { + OnExited?.Invoke( sender, _process.ExitCode ); + } + }; + } + + protected virtual void Start() + { + if ( _started ) + { + return; + } + + _started = true; + + _process.Start(); + _process.BeginOutputReadLine(); + _process.BeginErrorReadLine(); + _process.WaitForExit(); + } + + public virtual async Task SendInput( string input ) + { + try + { + await _process.StandardInput.WriteAsync( input! ); + } + catch ( Exception e ) + { + OnErrorDataReceived?.Invoke( _process, e.ToString() ); + } + } + + public virtual int Execute() + { + InitializeEvents(); + Start(); + return _process.ExitCode; + } + + public virtual async Task ExecuteAsync() + { + InitializeEvents(); + return await Task.Run( () => + { + Start(); + return _process.ExitCode; + } ) + .ConfigureAwait( false ); + } + + public virtual void Dispose() + { + _process.Dispose(); + OnExited = null; + OnOutputDataReceived = null; + OnErrorDataReceived = null; + } + } +} diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..9eccdb4 --- /dev/null +++ b/Program.cs @@ -0,0 +1,26 @@ +using CefDetector.Net; + +Dictionary cefList = new(); + +Console.WriteLine("正在计算chrome内核个数,请等待,下面是列表:"); +using var executor = new ProcessExecutor( "find", " / -name *_percent.pak" ); +executor.OnOutputDataReceived += ( sender, + str ) => + { + var result = CefClassifier.SearchDir( str ); + foreach ( var (file, type) in result ) + { + if ( !cefList.ContainsKey( file ) ) + { + cefList.Add( file, type ); + Console.WriteLine( type + "|" + file ); + } + } + }; +executor.OnErrorDataReceived += ( sender, + str ) => + { + //Console.WriteLine( "ERR:" + str ); + }; +executor.Execute(); +Console.WriteLine($"喜报:您系统里总共有{cefList.Count}个chrome内核!(可能有重复计算)"); \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..6211b1f --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +# CefDetector.Net - 检测你系统中包含多少个 Chromium 内核程序 + +Check how many CEFs are on your Linux. + +看看你系统 **(Linux)** 上有多少个 [CEF (Chromium Embedded Framework)](https://bitbucket.org/chromiumembedded/cef/). + +目前没有特别完善,可能还有很多情况没考虑到,欢迎发 issue ! + +(测试系统:Deepin 23 Alpha,Deepin上浏览器会存在重复检测的情况,看截图你就懂了) + +(也许可以起一个 Web 服务然后展示“喜报“,再说啦) + +> 目前仅支持Linux,Windows支持计划中... + +## 截屏 + +![Screenshot](./screenshot.png) + +## 使用 + +从 [Release](https://github.com/xh321/CefDetector.Net/releases) 页面下载最新的压缩包, 解压后给予 `CefDetector.Net` 执行权限后运行即可. + +## 特性 + +- 检测 CEF 的类型: 如 [libcef](https://bitbucket.org/chromiumembedded/cef/src/master/)、[Electron](https://www.electronjs.org/)、[NWJS](https://nwjs.io/)、[CefSharp](http://cefsharp.github.io/)、[Edge](https://www.microsoft.com/en-us/edge) 和 [Chrome](https://www.google.com/chrome/) +- 计算总数量 + +## 作者 + +xh321 + +创意来自 @ShirasawaSama 的 [CefDetector](https://github.com/ShirasawaSama/CefDetector) 项目。由于这个项目不支持Linux,所以我花一下午搓了一个功能差不多的。 + +## 协议 + +[MIT](./LICENSE) \ No newline at end of file diff --git a/screenshot.png b/screenshot.png new file mode 100644 index 0000000..a95517b Binary files /dev/null and b/screenshot.png differ