refactor: 将 libcore 转换为 Git 子模块并更新 .gitignore

- 将 libcore 从直接提交转换为 Git 子模块管理
- 更新 .gitignore 排除 libcore 编译产物(bin/, node_modules/, *.tar.gz, *.aar)
- 保留 libcore 源码用于 GitHub Actions 在线编译
- libcore 源码仓库: https://github.com/hiddify/hiddify-next-core
This commit is contained in:
Rust 2025-10-27 23:07:29 +08:00
parent 09d229a592
commit 2b8d34086a
5448 changed files with 10 additions and 683038 deletions

10
.gitignore vendored
View File

@ -90,4 +90,12 @@ app.*.map.json
# Local configuration
local.properties
key.properties
libcore
# libcore 编译产物(源码需要提交用于 GitHub Actions 编译)
libcore/bin/
libcore/node_modules/
libcore/*.tar.gz
libcore/*.aar
# Android 编译产物
android/app/libs/*.aar

1
libcore Submodule

@ -0,0 +1 @@
Subproject commit bfb026f06f8d9a70284cc585cb87f21ee3aa4d05

View File

@ -1,2 +0,0 @@
*.h linguist-detectable=false
*.c linguist-detectable=false

View File

@ -1,23 +0,0 @@
#! /bin/bash
SED() { [[ "$OSTYPE" == "darwin"* ]] && sed -i '' "$@" || sed -i "$@"; }
echo "previous version was $(git describe --tags $(git rev-list --tags --max-count=1))"
echo "WARNING: This operation will creates version tag and push to github"
read -p "Version? (provide the next x.y.z semver) : " TAG
echo $TAG
[[ "$TAG" =~ ^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}(\.dev)?$ ]] || { echo "Incorrect tag. e.g., 1.2.3 or 1.2.3.dev"; exit 1; }
IFS="." read -r -a VERSION_ARRAY <<< "$TAG"
VERSION_STR="${VERSION_ARRAY[0]}.${VERSION_ARRAY[1]}.${VERSION_ARRAY[2]}"
BUILD_NUMBER=$(( ${VERSION_ARRAY[0]} * 10000 + ${VERSION_ARRAY[1]} * 100 + ${VERSION_ARRAY[2]} ))
echo "version: ${VERSION_STR}+${BUILD_NUMBER}"
SED -e "s|<key>CFBundleVersion</key>\s*<string>[^<]*</string>|<key>CFBundleVersion</key><string>${VERSION_STR}</string>|" Info.plist
SED -e "s|<key>CFBundleShortVersionString</key>\s*<string>[^<]*</string>|<key>CFBundleShortVersionString</key><string>${VERSION_STR}</string>|" Info.plist
SED "s|ENV VERSION=.*|ENV VERSION=v${TAG}|g" docker/Dockerfile
git add Info.plist docker/Dockerfile
git commit -m "release: version ${TAG}"
echo "creating git tag : v${TAG}"
git push
git tag v${TAG}
git push -u origin HEAD --tags
echo "Github Actions will detect the new tag and release the new version."

View File

@ -1,303 +0,0 @@
name: Build
on:
workflow_call:
inputs:
upload-artifact:
type: boolean
default: true
tag-name:
type: string
default: "draft"
channel:
type: string
default: "dev"
env:
REGISTRY_IMAGE: ghcr.io/hiddify/hiddify-core
jobs:
update_wrt_hash:
permissions: write-all
runs-on: ubuntu-latest
if: ${{ inputs.channel=='prod' }}
steps:
- uses: actions/checkout@v4
- run: |
git checkout -b main
curl -L -o hiddify-core.tar.gz https://codeload.github.com/hiddify/hiddify-core/tar.gz/${{ inputs.tag-name }}
HIDDIFY_CORE_WRT_HASH=$(sha256sum hiddify-core.tar.gz | cut -d' ' -f1)
github_ref_name="${{ inputs.tag-name }}"
IFS="." read -r -a VERSION_ARRAY <<< "${github_ref_name#v}"
VERSION_STR="${VERSION_ARRAY[0]}.${VERSION_ARRAY[1]}.${VERSION_ARRAY[2]}"
sed -i "s|PKG_VERSION:=.*|PKG_VERSION:=${VERSION_STR}|g" wrt/Makefile
sed -i "s|PKG_HASH:=.*|PKG_HASH:=${HIDDIFY_CORE_WRT_HASH}|g" wrt/Makefile
- uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "Update WRT package HASH."
branch: main
# push_options: --force
build:
permissions: write-all
strategy:
fail-fast: false
matrix:
job:
- { name: 'hiddify-core-android', os: 'ubuntu-latest', target: 'android' }
- { name: 'hiddify-core-linux-amd64', os: 'ubuntu-20.04', target: 'linux-amd64' }
- { name: "hiddify-core-windows-amd64", os: 'ubuntu-latest', target: 'windows-amd64', aarch: 'x64' }
- { name: "hiddify-core-macos-universal", os: 'macos-12', target: 'macos-universal' }
- { name: "hiddify-core-ios", os: "macos-12", target: "ios" }
# linux custom
- {name: hiddify-cli-linux-amd64, goos: linux, goarch: amd64, goamd64: v1, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-amd64-v3, goos: linux, goarch: amd64, goamd64: v3, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-386, goos: linux, goarch: 386, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-arm64, goos: linux, goarch: arm64, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-armv5, goos: linux, goarch: arm, goarm: 5, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-armv6, goos: linux, goarch: arm, goarm: 6, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-armv7, goos: linux, goarch: arm, goarm: 7, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-mips-softfloat, goos: linux, goarch: mips, gomips: softfloat, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-mips-hardfloat, goos: linux, goarch: mips, gomips: hardfloat, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-mipsel-softfloat, goos: linux, goarch: mipsle, gomips: softfloat, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-mipsel-hardfloat, goos: linux, goarch: mipsle, gomips: hardfloat, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-mips64, goos: linux, goarch: mips64, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-mips64el, goos: linux, goarch: mips64le, target: 'linux-custom', os: 'ubuntu-20.04'}
- {name: hiddify-cli-linux-s390x, goos: linux, goarch: s390x, target: 'linux-custom', os: 'ubuntu-20.04'}
runs-on: ${{ matrix.job.os }}
env:
GOOS: ${{ matrix.job.goos }}
GOARCH: ${{ matrix.job.goarch }}
GOAMD64: ${{ matrix.job.goamd64 }}
GOARM: ${{ matrix.job.goarm }}
GOMIPS: ${{ matrix.job.gomips }}
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version-file: 'go.mod'
check-latest: false
- name: Setup Java
if: startsWith(matrix.job.target,'android')
uses: actions/setup-java@v3
with:
distribution: 'zulu'
java-version: '17'
- name: Setup NDK
if: startsWith(matrix.job.target,'android')
uses: nttld/setup-ndk@v1.4.0
id: setup-ndk
with:
ndk-version: r26b
add-to-path: true
local-cache: false
link-to-sdk: true
- name: Setup MinGW
if: startsWith(matrix.job.target,'windows')
uses: egor-tensin/setup-mingw@v2
with:
platform: ${{ matrix.job.aarch }}
- name: Setup macos
if: startsWith(matrix.job.target,'macos') || startsWith(matrix.job.target,'ios')
run: |
brew install create-dmg tree coreutils
- name: Build
run: |
make -j$(($(nproc) + 1)) ${{ matrix.job.target }}
- name: zip
run: |
tree
rm -f /*.h */*.h
rm ./hiddify-libcore*sources* ||echo "no source"
rm ./hiddify-libcore-macos-a*.dylib || echo "no macos arm and amd"
files=$(ls | grep -E '^(libcore\.(dll|so|dylib|aar)|webui|Libcore.xcframework|lib|HiddifyCli(\.exe)?)$')
echo tar -czvf ${{ matrix.job.name }}.tar.gz $files
tar -czvf ${{ matrix.job.name }}.tar.gz $files
working-directory: bin
- uses: actions/upload-artifact@v4
if: ${{ success() }}
with:
name: ${{ matrix.job.name }}
path: bin/*.tar.gz
retention-days: 1
upload-prerelease:
permissions: write-all
if: ${{ inputs.upload-artifact }}
needs: [build]
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v4
with:
merge-multiple: true
pattern: hiddify-*
path: bin/
- name: Display Files Structure
run: tree
working-directory: bin
- name: Delete Current Release Assets
uses: 8Mi-Tech/delete-release-assets-action@main
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
tag: 'draft'
deleteOnlyFromDrafts: false
- name: Create or Update Draft Release
uses: softprops/action-gh-release@v1
if: ${{ success() }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
files: ./bin/*.tar.gz
name: 'draft'
tag_name: 'draft'
prerelease: true
upload-release:
permissions: write-all
if: ${{ inputs.channel=='prod' }}
needs: [build]
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v4
with:
merge-multiple: true
pattern: hiddify-*
path: bin/
- name: Display Files Structure
run: ls -R
working-directory: bin
- name: Upload Release
uses: softprops/action-gh-release@v1
if: ${{ success() }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ inputs.tag-name }}
files: bin/*.tar.gz
make-upload-docker:
permissions: write-all
if: ${{ inputs.channel=='prod' }}
needs: [upload-release]
runs-on: ubuntu-latest
strategy:
fail-fast: true
matrix:
platform:
- linux/amd64
# - linux/arm/v5
- linux/arm/v6
- linux/arm/v7
- linux/arm64
- linux/386
# - linux/ppc64le
# - linux/riscv64
- linux/s390x
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
- name: Setup QEMU
uses: docker/setup-qemu-action@v3
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker meta
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY_IMAGE }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v6
with:
platforms: ${{ matrix.platform }}
context: ./docker/
build-args: |
BUILDKIT_CONTEXT_KEEP_GIT_DIR=1
labels: ${{ steps.meta.outputs.labels }}
outputs: type=image,name=${{ env.REGISTRY_IMAGE }},push-by-digest=true,name-canonical=true,push=true
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v4
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
merge:
permissions: write-all
runs-on: ubuntu-latest
needs:
- make-upload-docker
env:
LATEST: ${{ endsWith(inputs.tag-name , 'dev') && 'beta' ||'latest'}}
steps:
- name: Download digests
uses: actions/download-artifact@v4
with:
path: /tmp/digests
pattern: digests-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Create manifest list and push
working-directory: /tmp/digests
run: |
docker buildx imagetools create \
-t "${{ env.REGISTRY_IMAGE }}:${{ env.LATEST }}" \
-t "${{ env.REGISTRY_IMAGE }}:${{ inputs.tag-name }}" \
$(printf '${{ env.REGISTRY_IMAGE }}@sha256:%s ' *)
- name: Inspect image
run: |
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ env.LATEST }}
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ inputs.tag-name }}

View File

@ -1,32 +0,0 @@
name: CI
on:
pull_request:
paths-ignore:
- '**.md'
- 'docs/**'
- '.vscode/'
- 'appcast.xml'
push:
branches:
- main
- dev
- android-fix-action-bug
paths-ignore:
- '**.md'
- 'docs/**'
- '.vscode/'
- 'appcast.xml'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
run:
uses: ./.github/workflows/build.yml
secrets: inherit
permissions: write-all
if: "${{!contains(github.event.head_commit.message, 'release: version')}}"
with:
upload-artifact: ${{ github.event_name == 'push' }}

View File

@ -1,20 +0,0 @@
name: Release
on:
push:
tags:
- 'v[0-9]+.[0-9]+.[0-9]+'
- 'v[0-9]+.[0-9]+.[0-9]+.*'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build-release:
uses: ./.github/workflows/build.yml
secrets: inherit
permissions: write-all
with:
upload-artifact: true
tag-name: "${{ github.ref_name }}"
channel: "${{ github.ref_type == 'tag' && endsWith(github.ref_name, 'dev') && 'dev' || github.ref_type != 'tag' && 'dev' || 'prod' }}"

12
libcore/.gitignore vendored
View File

@ -1,12 +0,0 @@
/bin/*
!/bin/.gitkeep
.build
.idea
cert
**/*.log
.DS_Store
**/*.syso
node_modules
*.db
*.json

View File

@ -1,10 +0,0 @@
{
"overrides": [
{
"files": ".github/**",
"options": {
"singleQuote": true
}
}
]
}

View File

@ -1,9 +0,0 @@
.git
.build
.idea
**/*.log
.DS_Store
**/*.syso

View File

@ -1,26 +0,0 @@
Hiddify uses [Go](https://go.dev), make sure that you have the correct version installed before starting development. You can use the following commands to check your installed version:
```shell
$ go version
# example response
go version go1.21.1 darwin/arm64
```
### Working with the Go Code
> if you're not interested in building/contributing to the Go code, you can skip this section
The Go code for Hiddify can be found in the `libcore` folder, as a [git submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules) and in [core repository](https://github.com/hiddify/hiddify-next-core). The entrypoints for the desktop version are available in the [`libcore/custom`](https://github.com/hiddify/hiddify-next-core/tree/main/custom) folder and for the mobile version they can be found in the [`libcore/mobile`](https://github.com/hiddify/hiddify-next-core/tree/main/mobile) folder.
For the desktop version, we have to compile the Go code into a C shared library. We are providing a Makefile to generate the C shared libraries for all operating systems. The following Make commands will build libcore and copy the resulting output in [`libcore/bin`](https://github.com/hiddify/hiddify-next-core/tree/main/bin):
- `make windows-amd64`
- `make linux-amd64`
- `make macos-universal`
For the mobile version, we are using the [`gomobile`](https://github.com/golang/go/wiki/Mobile) tools. The following Make commands will build libcore for Android and iOS and copy the resulting output in [`libcore/bin`](https://github.com/hiddify/hiddify-next-core/tree/main/bin):
- `make android`
- `make ios`

View File

@ -1,50 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>AvailableLibraries</key>
<array>
<dict>
<key>BinaryPath</key>
<string>Libcore.framework/Libcore</string>
<key>LibraryIdentifier</key>
<string>ios-arm64_x86_64-simulator</string>
<key>LibraryPath</key>
<string>Libcore.framework</string>
<key>SupportedArchitectures</key>
<array>
<string>arm64</string>
<string>x86_64</string>
</array>
<key>SupportedPlatform</key>
<string>ios</string>
<key>SupportedPlatformVariant</key>
<string>simulator</string>
</dict>
<dict>
<key>BinaryPath</key>
<string>Libcore.framework/Libcore</string>
<key>LibraryIdentifier</key>
<string>ios-arm64</string>
<key>LibraryPath</key>
<string>Libcore.framework</string>
<key>SupportedArchitectures</key>
<array>
<string>arm64</string>
</array>
<key>SupportedPlatform</key>
<string>ios</string>
</dict>
</array>
<key>CFBundlePackageType</key>
<string>XFWK</string>
<key>XCFrameworkFormatVersion</key>
<string>1.0</string>
<key>CFBundleIdentifier</key>
<string>ios.libcore.hiddify</string>
<key>CFBundleShortVersionString</key><string>3.1.7</string>
<key>CFBundleVersion</key><string>3.1.7</string>
<key>MinimumOSVersion</key>
<string>15.0</string>
</dict>
</plist>

View File

@ -1,699 +0,0 @@
# GNU GENERAL PUBLIC LICENSE v3
## Summary:
Additional Permissions and Restrictions Under GNU GPL Version 3 Section 7
- If you use extends this code, you should directly fork it from github.
- The forks of the app are not allowed to be listed on F-Droid or other app stores under the original name or original design.
- Any forks should be published open-source under the same license.
- Prior consent is required to publish a fork or utilize any part of this repository (github.com/hiddify/hiddify-next and github.com/hiddify/hiddify-next-core) in an application intended for publication on the App Store or for iOS/macOS platforms. (We reserve the right to modify this requirement in the future after completing development for iOS and macOS).
- You need prior consent to publish a fork or use any part of this code in an application published in AppStore or publish for iOS or macOS. (We reserve the right to modify this requirement in the future after completing development for iOS and macOS).
- You are free to:
- Share — copy and redistribute the material in any medium or format with
- Adapt — remix, transform, and build upon the material
- Under the following terms:
- Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
- NonCommercial — You may not use the material for commercial purposes. You can not even include ads in it.
- ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.
- Prior consent is required before utilizing any portion of this code for integration into an application intended for the App Store.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -1,107 +0,0 @@
.ONESHELL:
PRODUCT_NAME=libcore
BASENAME=$(PRODUCT_NAME)
BINDIR=bin
LIBNAME=$(PRODUCT_NAME)
CLINAME=HiddifyCli
BRANCH=$(shell git branch --show-current)
VERSION=$(shell git describe --tags || echo "unknown version")
ifeq ($(OS),Windows_NT)
Not available for Windows! use bash in WSL
endif
TAGS=with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc
IOS_ADD_TAGS=with_dhcp,with_low_memory,with_conntrack
GOBUILDLIB=CGO_ENABLED=1 go build -trimpath -tags $(TAGS) -ldflags="-w -s" -buildmode=c-shared
GOBUILDSRV=CGO_ENABLED=1 go build -ldflags "-s -w" -trimpath -tags $(TAGS)
.PHONY: protos
protos:
protoc --go_out=./ --go-grpc_out=./ --proto_path=hiddifyrpc hiddifyrpc/*.proto
protoc --js_out=import_style=commonjs,binary:./extension/html/rpc/ --grpc-web_out=import_style=commonjs,mode=grpcwebtext:./extension/html/rpc/ --proto_path=hiddifyrpc hiddifyrpc/*.proto
npx browserify extension/html/rpc/extension.js >extension/html/rpc.js
lib_install:
go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.1.1
go install -v github.com/sagernet/gomobile/cmd/gobind@v0.1.1
npm install
headers:
go build -buildmode=c-archive -o $(BINDIR)/$(LIBNAME).h ./custom
android: lib_install
gomobile bind -v -androidapi=21 -javapkg=io.nekohasekai -libname=box -tags=$(TAGS) -trimpath -target=android -o $(BINDIR)/$(LIBNAME).aar github.com/sagernet/sing-box/experimental/libbox ./mobile
ios-full: lib_install
gomobile bind -v -target ios,iossimulator,tvos,tvossimulator,macos -libname=box -tags=$(TAGS),$(IOS_ADD_TAGS) -trimpath -ldflags="-w -s" -o $(BINDIR)/$(PRODUCT_NAME).xcframework github.com/sagernet/sing-box/experimental/libbox ./mobile
mv $(BINDIR)/$(PRODUCT_NAME).xcframework $(BINDIR)/$(LIBNAME).xcframework
cp Libcore.podspec $(BINDIR)/$(LIBNAME).xcframework/
ios: lib_install
gomobile bind -v -target ios -libname=box -tags=$(TAGS),$(IOS_ADD_TAGS) -trimpath -ldflags="-w -s" -o $(BINDIR)/Libcore.xcframework github.com/sagernet/sing-box/experimental/libbox ./mobile
cp Info.plist $(BINDIR)/Libcore.xcframework/
webui:
curl -L -o webui.zip https://github.com/hiddify/Yacd-meta/archive/gh-pages.zip
unzip -d ./ -q webui.zip
rm webui.zip
rm -rf bin/webui
mv Yacd-meta-gh-pages bin/webui
.PHONY: build
windows-amd64:
curl http://localhost:18020/exit || echo "exited"
env GOOS=windows GOARCH=amd64 CC=x86_64-w64-mingw32-gcc $(GOBUILDLIB) -o $(BINDIR)/$(LIBNAME).dll ./custom
go install -mod=readonly github.com/akavel/rsrc@latest ||echo "rsrc error in installation"
go run ./cli tunnel exit
cp $(BINDIR)/$(LIBNAME).dll ./$(LIBNAME).dll
$$(go env GOPATH)/bin/rsrc -ico ./assets/hiddify-cli.ico -o ./cli/bydll/cli.syso ||echo "rsrc error in syso"
env GOOS=windows GOARCH=amd64 CC=x86_64-w64-mingw32-gcc CGO_LDFLAGS="$(LIBNAME).dll" $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME).exe ./cli/bydll
rm ./$(LIBNAME).dll
make webui
linux-amd64:
mkdir -p $(BINDIR)/lib
env GOOS=linux GOARCH=amd64 $(GOBUILDLIB) -o $(BINDIR)/lib/$(LIBNAME).so ./custom
mkdir lib
cp $(BINDIR)/lib/$(LIBNAME).so ./lib/$(LIBNAME).so
env GOOS=linux GOARCH=amd64 CGO_LDFLAGS="./lib/$(LIBNAME).so" $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME) ./cli/bydll
rm -rf ./lib
chmod +x $(BINDIR)/$(CLINAME)
make webui
linux-custom:
mkdir -p $(BINDIR)/
#env GOARCH=mips $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME) ./cli/
go build -ldflags "-s -w" -trimpath -tags $(TAGS) -o $(BINDIR)/$(CLINAME) ./cli/
chmod +x $(BINDIR)/$(CLINAME)
make webui
macos-amd64:
env GOOS=darwin GOARCH=amd64 CGO_CFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="-mmacosx-version-min=10.11" CGO_ENABLED=1 go build -trimpath -tags $(TAGS),$(IOS_ADD_TAGS) -buildmode=c-shared -o $(BINDIR)/$(LIBNAME)-amd64.dylib ./custom
macos-arm64:
env GOOS=darwin GOARCH=arm64 CGO_CFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="-mmacosx-version-min=10.11" CGO_ENABLED=1 go build -trimpath -tags $(TAGS),$(IOS_ADD_TAGS) -buildmode=c-shared -o $(BINDIR)/$(LIBNAME)-arm64.dylib ./custom
macos-universal: macos-amd64 macos-arm64
lipo -create $(BINDIR)/$(LIBNAME)-amd64.dylib $(BINDIR)/$(LIBNAME)-arm64.dylib -output $(BINDIR)/$(LIBNAME).dylib
cp $(BINDIR)/$(LIBNAME).dylib ./$(LIBNAME).dylib
env GOOS=darwin GOARCH=amd64 CGO_CFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="-mmacosx-version-min=10.11" CGO_LDFLAGS="bin/$(LIBNAME).dylib" CGO_ENABLED=1 $(GOBUILDSRV) -o $(BINDIR)/$(CLINAME) ./cli/bydll
rm ./$(LIBNAME).dylib
chmod +x $(BINDIR)/$(CLINAME)
clean:
rm $(BINDIR)/*
release: # Create a new tag for release.
@bash -c '.github/change_version.sh'

View File

@ -1,53 +0,0 @@
# hiddify-core
## Docker
To Run our docker image see https://github.com/hiddify/hiddify-core/pkgs/container/hiddify-core
Docker
```
docker pull ghcr.io/hiddify/hiddify-core:latest
```
Docker Compose
```
git clone https://github.com/hiddify/hiddify-core
cd hiddify-core/docker
docker-compose up
```
## WRT
...
## Extension
An extension is something that can be added to hiddify application by a third party. It will add capability to modify configs, do some extra action, show and receive data from users.
This extension will be shown in all Hiddify Platforms such as Android/macOS/Linux/Windows/iOS
[Create an extension](https://github.com/hiddify/hiddify-app-example-extension)
Features and Road map:
- [x] Add Third Party Extension capability
- [x] Test Extension from Browser without any dependency to android/mac/.... `./cmd.sh extension` the open browser `https://127.0.0.1:12346`
- [x] Show Custom UI from Extension `github.com/hiddify/hiddify-core/extension.UpdateUI()`
- [x] Show Custom Dialog from Extension `github.com/hiddify/hiddify-core/extension.ShowDialog()`
- [x] Show Alert Dialog from Extension `github.com/hiddify/hiddify-core/extension.ShowMessage()`
- [x] Get Data from UI `github.com/hiddify/hiddify-core/extension.SubmitData()`
- [x] Save Extension Data from `e.Base.Data`
- [x] Load Extension Data to `e.Base.Data`
- [x] Disable / Enable Extension
- [x] Update user proxies before connecting `github.com/hiddify/hiddify-core/extension.BeforeAppConnect()`
- [x] Run Tiny Independent Instance `github.com/hiddify/hiddify-core/extension/sdk.RunInstance()`
- [x] Parse Any type of configs/url `github.com/hiddify/hiddify-core/extension/sdk.ParseConfig()`
- [ ] ToDo: Add Support for MultiLanguage Interface
- [ ] ToDo: Custom Extension Outbound
- [ ] ToDo: Custom Extension Inbound
- [ ] ToDo: Custom Extension ProxyConfig
Demo Screenshots from HTML:
<img width="531" alt="image" src="https://github.com/user-attachments/assets/0fbef76f-896f-4c45-a6b8-7a2687c47013">
<img width="531" alt="image" src="https://github.com/user-attachments/assets/15bccfa0-d03e-4354-9368-241836d82948">

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

View File

Binary file not shown.

View File

@ -1,36 +0,0 @@
// +build cgo
package bridge
// #include "stdint.h"
// #include "include/dart_api_dl.c"
//
// // Go does not allow calling C function pointers directly. So we are
// // forced to provide a trampoline.
// bool GoDart_PostCObject(Dart_Port_DL port, Dart_CObject* obj) {
// return Dart_PostCObject_DL(port, obj);
// }
import "C"
import (
"fmt"
"unsafe"
)
func InitializeDartApi(api unsafe.Pointer) {
if C.Dart_InitializeApiDL(api) != 0 {
panic("failed to initialize Dart DL C API: version mismatch. " +
"must update include/ to match Dart SDK version")
}
}
func SendStringToPort(port int64, msg string) {
var obj C.Dart_CObject
obj._type = C.Dart_CObject_kString
msg_obj := C.CString(msg) // go string -> char*s
// union type, we do a force conversion
ptr := unsafe.Pointer(&obj.value[0])
*(**C.char)(ptr) = msg_obj
ret := C.GoDart_PostCObject(C.Dart_Port_DL(port), &obj)
if !ret {
fmt.Println("ERROR: post to port ", port, " failed", msg)
}
}

View File

@ -1,11 +0,0 @@
//go:build !cgo
// +build !cgo
package bridge
import "unsafe"
func InitializeDartApi(api unsafe.Pointer) {
}
func SendStringToPort(port int64, msg string) {
}

View File

@ -1,23 +0,0 @@
# Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import("../../sdk_args.gni")
# This rule copies header files to include/
copy("copy_headers") {
visibility = [ "../../sdk:copy_headers" ]
sources = [
"dart_api.h",
"dart_api_dl.c",
"dart_api_dl.h",
"dart_native_api.h",
"dart_tools_api.h",
"dart_version.h",
"internal/dart_api_dl_impl.h",
]
outputs =
[ "$root_out_dir/$dart_sdk_output/include/{{source_target_relative}}" ]
}

View File

@ -1,30 +0,0 @@
/*
* Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#ifndef RUNTIME_INCLUDE_ANALYZE_SNAPSHOT_API_H_
#define RUNTIME_INCLUDE_ANALYZE_SNAPSHOT_API_H_
#include <stdint.h>
#include <optional>
namespace dart {
namespace snapshot_analyzer {
typedef struct {
const uint8_t* vm_snapshot_data;
const uint8_t* vm_snapshot_instructions;
const uint8_t* vm_isolate_data;
const uint8_t* vm_isolate_instructions;
} Dart_SnapshotAnalyzerInformation;
void Dart_DumpSnapshotInformationAsJson(
const Dart_SnapshotAnalyzerInformation& info,
char** buffer,
intptr_t* buffer_length);
} // namespace snapshot_analyzer
} // namespace dart
#endif // RUNTIME_INCLUDE_ANALYZE_SNAPSHOT_API_H_

View File

@ -1,69 +0,0 @@
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#ifndef RUNTIME_INCLUDE_BIN_DART_IO_API_H_
#define RUNTIME_INCLUDE_BIN_DART_IO_API_H_
#include "dart_tools_api.h"
namespace dart {
namespace bin {
// Bootstraps 'dart:io'.
void BootstrapDartIo();
// Cleans up 'dart:io'.
void CleanupDartIo();
// Lets dart:io know where the system temporary directory is located.
// Currently only wired up on Android.
void SetSystemTempDirectory(const char* system_temp);
// Tells the system whether to capture Stdout events.
void SetCaptureStdout(bool value);
// Tells the system whether to capture Stderr events.
void SetCaptureStderr(bool value);
// Should Stdout events be captured?
bool ShouldCaptureStdout();
// Should Stderr events be captured?
bool ShouldCaptureStderr();
// Set the executable name used by Platform.executable.
void SetExecutableName(const char* executable_name);
// Set the arguments used by Platform.executableArguments.
void SetExecutableArguments(int script_index, char** argv);
// Set dart:io implementation specific fields of Dart_EmbedderInformation.
void GetIOEmbedderInformation(Dart_EmbedderInformation* info);
// Appropriate to assign to Dart_InitializeParams.file_open/read/write/close.
void* OpenFile(const char* name, bool write);
void ReadFile(uint8_t** data, intptr_t* file_len, void* stream);
void WriteFile(const void* buffer, intptr_t num_bytes, void* stream);
void CloseFile(void* stream);
// Generates 'length' random bytes into 'buffer'. Returns true on success
// and false on failure. This is appropriate to assign to
// Dart_InitializeParams.entropy_source.
bool GetEntropy(uint8_t* buffer, intptr_t length);
// Performs a lookup of the I/O Dart_NativeFunction with a specified 'name' and
// 'argument_count'. Returns NULL if no I/O native function with a matching
// name and parameter count is found.
Dart_NativeFunction LookupIONative(Dart_Handle name,
int argument_count,
bool* auto_setup_scope);
// Returns the symbol for I/O native function 'nf'. Returns NULL if 'nf' is not
// a valid I/O native function.
const uint8_t* LookupIONativeSymbol(Dart_NativeFunction nf);
} // namespace bin
} // namespace dart
#endif // RUNTIME_INCLUDE_BIN_DART_IO_API_H_

File diff suppressed because it is too large Load Diff

View File

@ -1,79 +0,0 @@
/*
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#include "dart_api_dl.h" /* NOLINT */
#include "dart_version.h" /* NOLINT */
#include "internal/dart_api_dl_impl.h" /* NOLINT */
#include <stdio.h>
#include <string.h>
#define DART_API_DL_DEFINITIONS(name, R, A) name##_Type name##_DL = NULL;
DART_API_ALL_DL_SYMBOLS(DART_API_DL_DEFINITIONS)
DART_API_DEPRECATED_DL_SYMBOLS(DART_API_DL_DEFINITIONS)
#undef DART_API_DL_DEFINITIONS
typedef void* DartApiEntry_function;
DartApiEntry_function FindFunctionPointer(const DartApiEntry* entries,
const char* name) {
while (entries->name != NULL) {
if (strcmp(entries->name, name) == 0) return entries->function;
entries++;
}
return NULL;
}
DART_EXPORT void Dart_UpdateExternalSize_Deprecated(
Dart_WeakPersistentHandle object, intptr_t external_size) {
printf("Dart_UpdateExternalSize is a nop, it has been deprecated\n");
}
DART_EXPORT void Dart_UpdateFinalizableExternalSize_Deprecated(
Dart_FinalizableHandle object,
Dart_Handle strong_ref_to_object,
intptr_t external_allocation_size) {
printf("Dart_UpdateFinalizableExternalSize is a nop, "
"it has been deprecated\n");
}
intptr_t Dart_InitializeApiDL(void* data) {
DartApi* dart_api_data = (DartApi*)data;
if (dart_api_data->major != DART_API_DL_MAJOR_VERSION) {
// If the DartVM we're running on does not have the same version as this
// file was compiled against, refuse to initialize. The symbols are not
// compatible.
return -1;
}
// Minor versions are allowed to be different.
// If the DartVM has a higher minor version, it will provide more symbols
// than we initialize here.
// If the DartVM has a lower minor version, it will not provide all symbols.
// In that case, we leave the missing symbols un-initialized. Those symbols
// should not be used by the Dart and native code. The client is responsible
// for checking the minor version number himself based on which symbols it
// is using.
// (If we would error out on this case, recompiling native code against a
// newer SDK would break all uses on older SDKs, which is too strict.)
const DartApiEntry* dart_api_function_pointers = dart_api_data->functions;
#define DART_API_DL_INIT(name, R, A) \
name##_DL = \
(name##_Type)(FindFunctionPointer(dart_api_function_pointers, #name));
DART_API_ALL_DL_SYMBOLS(DART_API_DL_INIT)
#undef DART_API_DL_INIT
#define DART_API_DEPRECATED_DL_INIT(name, R, A) \
name##_DL = name##_Deprecated;
DART_API_DEPRECATED_DL_SYMBOLS(DART_API_DEPRECATED_DL_INIT)
#undef DART_API_DEPRECATED_DL_INIT
return 0;
}

View File

@ -1,162 +0,0 @@
/*
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#ifndef RUNTIME_INCLUDE_DART_API_DL_H_
#define RUNTIME_INCLUDE_DART_API_DL_H_
#include "dart_api.h" /* NOLINT */
#include "dart_native_api.h" /* NOLINT */
/** \mainpage Dynamically Linked Dart API
*
* This exposes a subset of symbols from dart_api.h and dart_native_api.h
* available in every Dart embedder through dynamic linking.
*
* All symbols are postfixed with _DL to indicate that they are dynamically
* linked and to prevent conflicts with the original symbol.
*
* Link `dart_api_dl.c` file into your library and invoke
* `Dart_InitializeApiDL` with `NativeApi.initializeApiDLData`.
*/
DART_EXPORT intptr_t Dart_InitializeApiDL(void* data);
// ============================================================================
// IMPORTANT! Never update these signatures without properly updating
// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION.
//
// Verbatim copy of `dart_native_api.h` and `dart_api.h` symbol names and types
// to trigger compile-time errors if the symbols in those files are updated
// without updating these.
//
// Function return and argument types, and typedefs are carbon copied. Structs
// are typechecked nominally in C/C++, so they are not copied, instead a
// comment is added to their definition.
typedef int64_t Dart_Port_DL;
typedef void (*Dart_NativeMessageHandler_DL)(Dart_Port_DL dest_port_id,
Dart_CObject* message);
// dart_native_api.h symbols can be called on any thread.
#define DART_NATIVE_API_DL_SYMBOLS(F) \
/***** dart_native_api.h *****/ \
/* Dart_Port */ \
F(Dart_PostCObject, bool, (Dart_Port_DL port_id, Dart_CObject * message)) \
F(Dart_PostInteger, bool, (Dart_Port_DL port_id, int64_t message)) \
F(Dart_NewNativePort, Dart_Port_DL, \
(const char* name, Dart_NativeMessageHandler_DL handler, \
bool handle_concurrently)) \
F(Dart_CloseNativePort, bool, (Dart_Port_DL native_port_id))
// dart_api.h symbols can only be called on Dart threads.
#define DART_API_DL_SYMBOLS(F) \
/***** dart_api.h *****/ \
/* Errors */ \
F(Dart_IsError, bool, (Dart_Handle handle)) \
F(Dart_IsApiError, bool, (Dart_Handle handle)) \
F(Dart_IsUnhandledExceptionError, bool, (Dart_Handle handle)) \
F(Dart_IsCompilationError, bool, (Dart_Handle handle)) \
F(Dart_IsFatalError, bool, (Dart_Handle handle)) \
F(Dart_GetError, const char*, (Dart_Handle handle)) \
F(Dart_ErrorHasException, bool, (Dart_Handle handle)) \
F(Dart_ErrorGetException, Dart_Handle, (Dart_Handle handle)) \
F(Dart_ErrorGetStackTrace, Dart_Handle, (Dart_Handle handle)) \
F(Dart_NewApiError, Dart_Handle, (const char* error)) \
F(Dart_NewCompilationError, Dart_Handle, (const char* error)) \
F(Dart_NewUnhandledExceptionError, Dart_Handle, (Dart_Handle exception)) \
F(Dart_PropagateError, void, (Dart_Handle handle)) \
/* Dart_Handle, Dart_PersistentHandle, Dart_WeakPersistentHandle */ \
F(Dart_HandleFromPersistent, Dart_Handle, (Dart_PersistentHandle object)) \
F(Dart_HandleFromWeakPersistent, Dart_Handle, \
(Dart_WeakPersistentHandle object)) \
F(Dart_NewPersistentHandle, Dart_PersistentHandle, (Dart_Handle object)) \
F(Dart_SetPersistentHandle, void, \
(Dart_PersistentHandle obj1, Dart_Handle obj2)) \
F(Dart_DeletePersistentHandle, void, (Dart_PersistentHandle object)) \
F(Dart_NewWeakPersistentHandle, Dart_WeakPersistentHandle, \
(Dart_Handle object, void* peer, intptr_t external_allocation_size, \
Dart_HandleFinalizer callback)) \
F(Dart_DeleteWeakPersistentHandle, void, (Dart_WeakPersistentHandle object)) \
F(Dart_NewFinalizableHandle, Dart_FinalizableHandle, \
(Dart_Handle object, void* peer, intptr_t external_allocation_size, \
Dart_HandleFinalizer callback)) \
F(Dart_DeleteFinalizableHandle, void, \
(Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object)) \
/* Isolates */ \
F(Dart_CurrentIsolate, Dart_Isolate, (void)) \
F(Dart_ExitIsolate, void, (void)) \
F(Dart_EnterIsolate, void, (Dart_Isolate)) \
/* Dart_Port */ \
F(Dart_Post, bool, (Dart_Port_DL port_id, Dart_Handle object)) \
F(Dart_NewSendPort, Dart_Handle, (Dart_Port_DL port_id)) \
F(Dart_SendPortGetId, Dart_Handle, \
(Dart_Handle port, Dart_Port_DL * port_id)) \
/* Scopes */ \
F(Dart_EnterScope, void, (void)) \
F(Dart_ExitScope, void, (void)) \
/* Objects */ \
F(Dart_IsNull, bool, (Dart_Handle))
// dart_api.h symbols that have been deprecated but are retained here
// until we can make a breaking change bumping the major version number
// (DART_API_DL_MAJOR_VERSION)
#define DART_API_DEPRECATED_DL_SYMBOLS(F) \
F(Dart_UpdateExternalSize, void, \
(Dart_WeakPersistentHandle object, intptr_t external_allocation_size)) \
F(Dart_UpdateFinalizableExternalSize, void, \
(Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object, \
intptr_t external_allocation_size))
#define DART_API_ALL_DL_SYMBOLS(F) \
DART_NATIVE_API_DL_SYMBOLS(F) \
DART_API_DL_SYMBOLS(F)
// IMPORTANT! Never update these signatures without properly updating
// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION.
//
// End of verbatim copy.
// ============================================================================
// Copy of definition of DART_EXPORT without 'used' attribute.
//
// The 'used' attribute cannot be used with DART_API_ALL_DL_SYMBOLS because
// they are not function declarations, but variable declarations with a
// function pointer type.
//
// The function pointer variables are initialized with the addresses of the
// functions in the VM. If we were to use function declarations instead, we
// would need to forward the call to the VM adding indirection.
#if defined(__CYGWIN__)
#error Tool chain and platform not supported.
#elif defined(_WIN32)
#if defined(DART_SHARED_LIB)
#define DART_EXPORT_DL DART_EXTERN_C __declspec(dllexport)
#else
#define DART_EXPORT_DL DART_EXTERN_C
#endif
#else
#if __GNUC__ >= 4
#if defined(DART_SHARED_LIB)
#define DART_EXPORT_DL DART_EXTERN_C __attribute__((visibility("default")))
#else
#define DART_EXPORT_DL DART_EXTERN_C
#endif
#else
#error Tool chain not supported.
#endif
#endif
#define DART_API_DL_DECLARATIONS(name, R, A) \
typedef R(*name##_Type) A; \
DART_EXPORT_DL name##_Type name##_DL;
DART_API_ALL_DL_SYMBOLS(DART_API_DL_DECLARATIONS)
DART_API_DEPRECATED_DL_SYMBOLS(DART_API_DL_DECLARATIONS)
#undef DART_API_DL_DECLARATIONS
#undef DART_EXPORT_DL
#endif /* RUNTIME_INCLUDE_DART_API_DL_H_ */ /* NOLINT */

View File

@ -1,108 +0,0 @@
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#ifndef RUNTIME_INCLUDE_DART_EMBEDDER_API_H_
#define RUNTIME_INCLUDE_DART_EMBEDDER_API_H_
#include "include/dart_api.h"
#include "include/dart_tools_api.h"
namespace dart {
namespace embedder {
// Initialize all subsystems of the embedder.
//
// Must be called before the `Dart_Initialize()` call to initialize the
// Dart VM.
//
// Returns true on success and false otherwise, in which case error would
// contain error message.
DART_WARN_UNUSED_RESULT bool InitOnce(char** error);
// Cleans up all subsystems of the embedder.
//
// Must be called after the `Dart_Cleanup()` call to initialize the
// Dart VM.
void Cleanup();
// Common arguments that are passed to isolate creation callback and to
// API methods that create isolates.
struct IsolateCreationData {
// URI for the main script that will be running in the isolate.
const char* script_uri;
// Advisory name of the main method that will be run by isolate.
// Only used for error messages.
const char* main;
// Isolate creation flags. Might be absent.
Dart_IsolateFlags* flags;
// Isolate group callback data.
void* isolate_group_data;
// Isolate callback data.
void* isolate_data;
};
// Create and initialize kernel-service isolate. This method should be used
// when VM invokes isolate creation callback with DART_KERNEL_ISOLATE_NAME as
// script_uri.
// The isolate is created from the given snapshot (might be kernel data or
// app-jit snapshot).
DART_WARN_UNUSED_RESULT Dart_Isolate
CreateKernelServiceIsolate(const IsolateCreationData& data,
const uint8_t* buffer,
intptr_t buffer_size,
char** error);
// Service isolate configuration.
struct VmServiceConfiguration {
enum {
kBindHttpServerToAFreePort = 0,
kDoNotAutoStartHttpServer = -1
};
// Address to which HTTP server will be bound.
const char* ip;
// Default port. See enum above for special values.
int port;
// If non-null, connection information for the VM service will be output to a
// file in JSON format at the location specified.
const char* write_service_info_filename;
// TODO(vegorov) document these ones.
bool dev_mode;
bool deterministic;
bool disable_auth_codes;
};
// Create and initialize vm-service isolate from the given AOT snapshot, which
// is expected to contain all necessary 'vm-service' libraries.
// This method should be used when VM invokes isolate creation callback with
// DART_VM_SERVICE_ISOLATE_NAME as script_uri.
DART_WARN_UNUSED_RESULT Dart_Isolate
CreateVmServiceIsolate(const IsolateCreationData& data,
const VmServiceConfiguration& config,
const uint8_t* isolate_data,
const uint8_t* isolate_instr,
char** error);
// Create and initialize vm-service isolate from the given kernel binary, which
// is expected to contain all necessary 'vm-service' libraries.
// This method should be used when VM invokes isolate creation callback with
// DART_VM_SERVICE_ISOLATE_NAME as script_uri.
DART_WARN_UNUSED_RESULT Dart_Isolate
CreateVmServiceIsolateFromKernel(const IsolateCreationData& data,
const VmServiceConfiguration& config,
const uint8_t* kernel_buffer,
intptr_t kernel_buffer_size,
char** error);
} // namespace embedder
} // namespace dart
#endif // RUNTIME_INCLUDE_DART_EMBEDDER_API_H_

View File

@ -1,207 +0,0 @@
/*
* Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#ifndef RUNTIME_INCLUDE_DART_NATIVE_API_H_
#define RUNTIME_INCLUDE_DART_NATIVE_API_H_
#include "dart_api.h" /* NOLINT */
/*
* ==========================================
* Message sending/receiving from native code
* ==========================================
*/
/**
* A Dart_CObject is used for representing Dart objects as native C
* data outside the Dart heap. These objects are totally detached from
* the Dart heap. Only a subset of the Dart objects have a
* representation as a Dart_CObject.
*
* The string encoding in the 'value.as_string' is UTF-8.
*
* All the different types from dart:typed_data are exposed as type
* kTypedData. The specific type from dart:typed_data is in the type
* field of the as_typed_data structure. The length in the
* as_typed_data structure is always in bytes.
*
* The data for kTypedData is copied on message send and ownership remains with
* the caller. The ownership of data for kExternalTyped is passed to the VM on
* message send and returned when the VM invokes the
* Dart_HandleFinalizer callback; a non-NULL callback must be provided.
*
* Note that Dart_CObject_kNativePointer is intended for internal use by
* dart:io implementation and has no connection to dart:ffi Pointer class.
* It represents a pointer to a native resource of a known type.
* The receiving side will only see this pointer as an integer and will not
* see the specified finalizer.
* The specified finalizer will only be invoked if the message is not delivered.
*/
typedef enum {
Dart_CObject_kNull = 0,
Dart_CObject_kBool,
Dart_CObject_kInt32,
Dart_CObject_kInt64,
Dart_CObject_kDouble,
Dart_CObject_kString,
Dart_CObject_kArray,
Dart_CObject_kTypedData,
Dart_CObject_kExternalTypedData,
Dart_CObject_kSendPort,
Dart_CObject_kCapability,
Dart_CObject_kNativePointer,
Dart_CObject_kUnsupported,
Dart_CObject_kUnmodifiableExternalTypedData,
Dart_CObject_kNumberOfTypes
} Dart_CObject_Type;
// This enum is versioned by DART_API_DL_MAJOR_VERSION, only add at the end
// and bump the DART_API_DL_MINOR_VERSION.
typedef struct _Dart_CObject {
Dart_CObject_Type type;
union {
bool as_bool;
int32_t as_int32;
int64_t as_int64;
double as_double;
const char* as_string;
struct {
Dart_Port id;
Dart_Port origin_id;
} as_send_port;
struct {
int64_t id;
} as_capability;
struct {
intptr_t length;
struct _Dart_CObject** values;
} as_array;
struct {
Dart_TypedData_Type type;
intptr_t length; /* in elements, not bytes */
const uint8_t* values;
} as_typed_data;
struct {
Dart_TypedData_Type type;
intptr_t length; /* in elements, not bytes */
uint8_t* data;
void* peer;
Dart_HandleFinalizer callback;
} as_external_typed_data;
struct {
intptr_t ptr;
intptr_t size;
Dart_HandleFinalizer callback;
} as_native_pointer;
} value;
} Dart_CObject;
// This struct is versioned by DART_API_DL_MAJOR_VERSION, bump the version when
// changing this struct.
/**
* Posts a message on some port. The message will contain the Dart_CObject
* object graph rooted in 'message'.
*
* While the message is being sent the state of the graph of Dart_CObject
* structures rooted in 'message' should not be accessed, as the message
* generation will make temporary modifications to the data. When the message
* has been sent the graph will be fully restored.
*
* If true is returned, the message was enqueued, and finalizers for external
* typed data will eventually run, even if the receiving isolate shuts down
* before processing the message. If false is returned, the message was not
* enqueued and ownership of external typed data in the message remains with the
* caller.
*
* This function may be called on any thread when the VM is running (that is,
* after Dart_Initialize has returned and before Dart_Cleanup has been called).
*
* \param port_id The destination port.
* \param message The message to send.
*
* \return True if the message was posted.
*/
DART_EXPORT bool Dart_PostCObject(Dart_Port port_id, Dart_CObject* message);
/**
* Posts a message on some port. The message will contain the integer 'message'.
*
* \param port_id The destination port.
* \param message The message to send.
*
* \return True if the message was posted.
*/
DART_EXPORT bool Dart_PostInteger(Dart_Port port_id, int64_t message);
/**
* A native message handler.
*
* This handler is associated with a native port by calling
* Dart_NewNativePort.
*
* The message received is decoded into the message structure. The
* lifetime of the message data is controlled by the caller. All the
* data references from the message are allocated by the caller and
* will be reclaimed when returning to it.
*/
typedef void (*Dart_NativeMessageHandler)(Dart_Port dest_port_id,
Dart_CObject* message);
/**
* Creates a new native port. When messages are received on this
* native port, then they will be dispatched to the provided native
* message handler.
*
* \param name The name of this port in debugging messages.
* \param handler The C handler to run when messages arrive on the port.
* \param handle_concurrently Is it okay to process requests on this
* native port concurrently?
*
* \return If successful, returns the port id for the native port. In
* case of error, returns ILLEGAL_PORT.
*/
DART_EXPORT Dart_Port Dart_NewNativePort(const char* name,
Dart_NativeMessageHandler handler,
bool handle_concurrently);
/* TODO(turnidge): Currently handle_concurrently is ignored. */
/**
* Closes the native port with the given id.
*
* The port must have been allocated by a call to Dart_NewNativePort.
*
* \param native_port_id The id of the native port to close.
*
* \return Returns true if the port was closed successfully.
*/
DART_EXPORT bool Dart_CloseNativePort(Dart_Port native_port_id);
/*
* ==================
* Verification Tools
* ==================
*/
/**
* Forces all loaded classes and functions to be compiled eagerly in
* the current isolate..
*
* TODO(turnidge): Document.
*/
DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_CompileAll(void);
/**
* Finalizes all classes.
*/
DART_EXPORT DART_WARN_UNUSED_RESULT Dart_Handle Dart_FinalizeAllClasses(void);
/* This function is intentionally undocumented.
*
* It should not be used outside internal tests.
*/
DART_EXPORT void* Dart_ExecuteInternalCommand(const char* command, void* arg);
#endif /* INCLUDE_DART_NATIVE_API_H_ */ /* NOLINT */

View File

@ -1,658 +0,0 @@
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#ifndef RUNTIME_INCLUDE_DART_TOOLS_API_H_
#define RUNTIME_INCLUDE_DART_TOOLS_API_H_
#include "dart_api.h" /* NOLINT */
/** \mainpage Dart Tools Embedding API Reference
*
* This reference describes the Dart embedding API for tools. Tools include
* a debugger, service protocol, and timeline.
*
* NOTE: The APIs described in this file are unstable and subject to change.
*
* This reference is generated from the header include/dart_tools_api.h.
*/
/*
* ========
* Debugger
* ========
*/
/**
* ILLEGAL_ISOLATE_ID is a number guaranteed never to be associated with a
* valid isolate.
*/
#define ILLEGAL_ISOLATE_ID ILLEGAL_PORT
/**
* ILLEGAL_ISOLATE_GROUP_ID is a number guaranteed never to be associated with a
* valid isolate group.
*/
#define ILLEGAL_ISOLATE_GROUP_ID 0
/*
* =======
* Service
* =======
*/
/**
* A service request callback function.
*
* These callbacks, registered by the embedder, are called when the VM receives
* a service request it can't handle and the service request command name
* matches one of the embedder registered handlers.
*
* The return value of the callback indicates whether the response
* should be used as a regular result or an error result.
* Specifically, if the callback returns true, a regular JSON-RPC
* response is built in the following way:
*
* {
* "jsonrpc": "2.0",
* "result": <json_object>,
* "id": <some sequence id>,
* }
*
* If the callback returns false, a JSON-RPC error is built like this:
*
* {
* "jsonrpc": "2.0",
* "error": <json_object>,
* "id": <some sequence id>,
* }
*
* \param method The rpc method name.
* \param param_keys Service requests can have key-value pair parameters. The
* keys and values are flattened and stored in arrays.
* \param param_values The values associated with the keys.
* \param num_params The length of the param_keys and param_values arrays.
* \param user_data The user_data pointer registered with this handler.
* \param result A C string containing a valid JSON object. The returned
* pointer will be freed by the VM by calling free.
*
* \return True if the result is a regular JSON-RPC response, false if the
* result is a JSON-RPC error.
*/
typedef bool (*Dart_ServiceRequestCallback)(const char* method,
const char** param_keys,
const char** param_values,
intptr_t num_params,
void* user_data,
const char** json_object);
/**
* Register a Dart_ServiceRequestCallback to be called to handle
* requests for the named rpc on a specific isolate. The callback will
* be invoked with the current isolate set to the request target.
*
* \param method The name of the method that this callback is responsible for.
* \param callback The callback to invoke.
* \param user_data The user data passed to the callback.
*
* NOTE: If multiple callbacks with the same name are registered, only
* the last callback registered will be remembered.
*/
DART_EXPORT void Dart_RegisterIsolateServiceRequestCallback(
const char* method,
Dart_ServiceRequestCallback callback,
void* user_data);
/**
* Register a Dart_ServiceRequestCallback to be called to handle
* requests for the named rpc. The callback will be invoked without a
* current isolate.
*
* \param method The name of the command that this callback is responsible for.
* \param callback The callback to invoke.
* \param user_data The user data passed to the callback.
*
* NOTE: If multiple callbacks with the same name are registered, only
* the last callback registered will be remembered.
*/
DART_EXPORT void Dart_RegisterRootServiceRequestCallback(
const char* method,
Dart_ServiceRequestCallback callback,
void* user_data);
/**
* Embedder information which can be requested by the VM for internal or
* reporting purposes.
*
* The pointers in this structure are not going to be cached or freed by the VM.
*/
#define DART_EMBEDDER_INFORMATION_CURRENT_VERSION (0x00000001)
typedef struct {
int32_t version;
const char* name; // [optional] The name of the embedder
int64_t current_rss; // [optional] the current RSS of the embedder
int64_t max_rss; // [optional] the maximum RSS of the embedder
} Dart_EmbedderInformation;
/**
* Callback provided by the embedder that is used by the VM to request
* information.
*
* \return Returns a pointer to a Dart_EmbedderInformation structure.
* The embedder keeps the ownership of the structure and any field in it.
* The embedder must ensure that the structure will remain valid until the
* next invocation of the callback.
*/
typedef void (*Dart_EmbedderInformationCallback)(
Dart_EmbedderInformation* info);
/**
* Register a Dart_ServiceRequestCallback to be called to handle
* requests for the named rpc. The callback will be invoked without a
* current isolate.
*
* \param method The name of the command that this callback is responsible for.
* \param callback The callback to invoke.
* \param user_data The user data passed to the callback.
*
* NOTE: If multiple callbacks are registered, only the last callback registered
* will be remembered.
*/
DART_EXPORT void Dart_SetEmbedderInformationCallback(
Dart_EmbedderInformationCallback callback);
/**
* Invoke a vm-service method and wait for its result.
*
* \param request_json The utf8-encoded json-rpc request.
* \param request_json_length The length of the json-rpc request.
*
* \param response_json The returned utf8-encoded json response, must be
* free()ed by caller.
* \param response_json_length The length of the returned json response.
* \param error An optional error, must be free()ed by caller.
*
* \return Whether the call was successfully performed.
*
* NOTE: This method does not need a current isolate and must not have the
* vm-isolate being the current isolate. It must be called after
* Dart_Initialize() and before Dart_Cleanup().
*/
DART_EXPORT bool Dart_InvokeVMServiceMethod(uint8_t* request_json,
intptr_t request_json_length,
uint8_t** response_json,
intptr_t* response_json_length,
char** error);
/*
* ========
* Event Streams
* ========
*/
/**
* A callback invoked when the VM service gets a request to listen to
* some stream.
*
* \return Returns true iff the embedder supports the named stream id.
*/
typedef bool (*Dart_ServiceStreamListenCallback)(const char* stream_id);
/**
* A callback invoked when the VM service gets a request to cancel
* some stream.
*/
typedef void (*Dart_ServiceStreamCancelCallback)(const char* stream_id);
/**
* Adds VM service stream callbacks.
*
* \param listen_callback A function pointer to a listen callback function.
* A listen callback function should not be already set when this function
* is called. A NULL value removes the existing listen callback function
* if any.
*
* \param cancel_callback A function pointer to a cancel callback function.
* A cancel callback function should not be already set when this function
* is called. A NULL value removes the existing cancel callback function
* if any.
*
* \return Success if the callbacks were added. Otherwise, returns an
* error handle.
*/
DART_EXPORT char* Dart_SetServiceStreamCallbacks(
Dart_ServiceStreamListenCallback listen_callback,
Dart_ServiceStreamCancelCallback cancel_callback);
/**
* Sends a data event to clients of the VM Service.
*
* A data event is used to pass an array of bytes to subscribed VM
* Service clients. For example, in the standalone embedder, this is
* function used to provide WriteEvents on the Stdout and Stderr
* streams.
*
* If the embedder passes in a stream id for which no client is
* subscribed, then the event is ignored.
*
* \param stream_id The id of the stream on which to post the event.
*
* \param event_kind A string identifying what kind of event this is.
* For example, 'WriteEvent'.
*
* \param bytes A pointer to an array of bytes.
*
* \param bytes_length The length of the byte array.
*
* \return NULL if the arguments are well formed. Otherwise, returns an
* error string. The caller is responsible for freeing the error message.
*/
DART_EXPORT char* Dart_ServiceSendDataEvent(const char* stream_id,
const char* event_kind,
const uint8_t* bytes,
intptr_t bytes_length);
/*
* ========
* Reload support
* ========
*
* These functions are used to implement reloading in the Dart VM.
* This is an experimental feature, so embedders should be prepared
* for these functions to change.
*/
/**
* A callback which determines whether the file at some url has been
* modified since some time. If the file cannot be found, true should
* be returned.
*/
typedef bool (*Dart_FileModifiedCallback)(const char* url, int64_t since);
DART_EXPORT char* Dart_SetFileModifiedCallback(
Dart_FileModifiedCallback file_modified_callback);
/**
* Returns true if isolate is currently reloading.
*/
DART_EXPORT bool Dart_IsReloading();
/*
* ========
* Timeline
* ========
*/
/**
* Enable tracking of specified timeline category. This is operational
* only when systrace timeline functionality is turned on.
*
* \param categories A comma separated list of categories that need to
* be enabled, the categories are
* "all" : All categories
* "API" - Execution of Dart C API functions
* "Compiler" - Execution of Dart JIT compiler
* "CompilerVerbose" - More detailed Execution of Dart JIT compiler
* "Dart" - Execution of Dart code
* "Debugger" - Execution of Dart debugger
* "Embedder" - Execution of Dart embedder code
* "GC" - Execution of Dart Garbage Collector
* "Isolate" - Dart Isolate lifecycle execution
* "VM" - Execution in Dart VM runtime code
* "" - None
*
* When "all" is specified all the categories are enabled.
* When a comma separated list of categories is specified, the categories
* that are specified will be enabled and the rest will be disabled.
* When "" is specified all the categories are disabled.
* The category names are case sensitive.
* eg: Dart_EnableTimelineCategory("all");
* Dart_EnableTimelineCategory("GC,API,Isolate");
* Dart_EnableTimelineCategory("GC,Debugger,Dart");
*
* \return True if the categories were successfully enabled, False otherwise.
*/
DART_EXPORT bool Dart_SetEnabledTimelineCategory(const char* categories);
/**
* Returns a timestamp in microseconds. This timestamp is suitable for
* passing into the timeline system, and uses the same monotonic clock
* as dart:developer's Timeline.now.
*
* \return A timestamp that can be passed to the timeline system.
*/
DART_EXPORT int64_t Dart_TimelineGetMicros();
/**
* Returns a raw timestamp in from the monotonic clock.
*
* \return A raw timestamp from the monotonic clock.
*/
DART_EXPORT int64_t Dart_TimelineGetTicks();
/**
* Returns the frequency of the monotonic clock.
*
* \return The frequency of the monotonic clock.
*/
DART_EXPORT int64_t Dart_TimelineGetTicksFrequency();
typedef enum {
Dart_Timeline_Event_Begin, // Phase = 'B'.
Dart_Timeline_Event_End, // Phase = 'E'.
Dart_Timeline_Event_Instant, // Phase = 'i'.
Dart_Timeline_Event_Duration, // Phase = 'X'.
Dart_Timeline_Event_Async_Begin, // Phase = 'b'.
Dart_Timeline_Event_Async_End, // Phase = 'e'.
Dart_Timeline_Event_Async_Instant, // Phase = 'n'.
Dart_Timeline_Event_Counter, // Phase = 'C'.
Dart_Timeline_Event_Flow_Begin, // Phase = 's'.
Dart_Timeline_Event_Flow_Step, // Phase = 't'.
Dart_Timeline_Event_Flow_End, // Phase = 'f'.
} Dart_Timeline_Event_Type;
/**
* Add a timeline event to the embedder stream.
*
* DEPRECATED: this function will be removed in Dart SDK v3.2.
*
* \param label The name of the event. Its lifetime must extend at least until
* Dart_Cleanup.
* \param timestamp0 The first timestamp of the event.
* \param timestamp1_or_id When reporting an event of type
* |Dart_Timeline_Event_Duration|, the second (end) timestamp of the event
* should be passed through |timestamp1_or_id|. When reporting an event of
* type |Dart_Timeline_Event_Async_Begin|, |Dart_Timeline_Event_Async_End|,
* or |Dart_Timeline_Event_Async_Instant|, the async ID associated with the
* event should be passed through |timestamp1_or_id|. When reporting an
* event of type |Dart_Timeline_Event_Flow_Begin|,
* |Dart_Timeline_Event_Flow_Step|, or |Dart_Timeline_Event_Flow_End|, the
* flow ID associated with the event should be passed through
* |timestamp1_or_id|. When reporting an event of type
* |Dart_Timeline_Event_Begin| or |Dart_Timeline_Event_End|, the event ID
* associated with the event should be passed through |timestamp1_or_id|.
* Note that this event ID will only be used by the MacOS recorder. The
* argument to |timestamp1_or_id| will not be used when reporting events of
* other types.
* \param argument_count The number of argument names and values.
* \param argument_names An array of names of the arguments. The lifetime of the
* names must extend at least until Dart_Cleanup. The array may be reclaimed
* when this call returns.
* \param argument_values An array of values of the arguments. The values and
* the array may be reclaimed when this call returns.
*/
DART_EXPORT void Dart_TimelineEvent(const char* label,
int64_t timestamp0,
int64_t timestamp1_or_id,
Dart_Timeline_Event_Type type,
intptr_t argument_count,
const char** argument_names,
const char** argument_values);
/**
* Add a timeline event to the embedder stream.
*
* Note regarding flow events: events must be associated with flow IDs in two
* different ways to allow flow events to be serialized correctly in both
* Chrome's JSON trace event format and Perfetto's proto trace format. Events
* of type |Dart_Timeline_Event_Flow_Begin|, |Dart_Timeline_Event_Flow_Step|,
* and |Dart_Timeline_Event_Flow_End| must be reported to support serialization
* in Chrome's trace format. The |flow_ids| argument must be supplied when
* reporting events of type |Dart_Timeline_Event_Begin|,
* |Dart_Timeline_Event_Duration|, |Dart_Timeline_Event_Instant|,
* |Dart_Timeline_Event_Async_Begin|, and |Dart_Timeline_Event_Async_Instant| to
* support serialization in Perfetto's proto format.
*
* \param label The name of the event. Its lifetime must extend at least until
* Dart_Cleanup.
* \param timestamp0 The first timestamp of the event.
* \param timestamp1_or_id When reporting an event of type
* |Dart_Timeline_Event_Duration|, the second (end) timestamp of the event
* should be passed through |timestamp1_or_id|. When reporting an event of
* type |Dart_Timeline_Event_Async_Begin|, |Dart_Timeline_Event_Async_End|,
* or |Dart_Timeline_Event_Async_Instant|, the async ID associated with the
* event should be passed through |timestamp1_or_id|. When reporting an
* event of type |Dart_Timeline_Event_Flow_Begin|,
* |Dart_Timeline_Event_Flow_Step|, or |Dart_Timeline_Event_Flow_End|, the
* flow ID associated with the event should be passed through
* |timestamp1_or_id|. When reporting an event of type
* |Dart_Timeline_Event_Begin| or |Dart_Timeline_Event_End|, the event ID
* associated with the event should be passed through |timestamp1_or_id|.
* Note that this event ID will only be used by the MacOS recorder. The
* argument to |timestamp1_or_id| will not be used when reporting events of
* other types.
* \param flow_id_count The number of flow IDs associated with this event.
* \param flow_ids An array of flow IDs associated with this event. The array
* may be reclaimed when this call returns.
* \param argument_count The number of argument names and values.
* \param argument_names An array of names of the arguments. The lifetime of the
* names must extend at least until Dart_Cleanup. The array may be reclaimed
* when this call returns.
* \param argument_values An array of values of the arguments. The values and
* the array may be reclaimed when this call returns.
*/
DART_EXPORT void Dart_RecordTimelineEvent(const char* label,
int64_t timestamp0,
int64_t timestamp1_or_id,
intptr_t flow_id_count,
const int64_t* flow_ids,
Dart_Timeline_Event_Type type,
intptr_t argument_count,
const char** argument_names,
const char** argument_values);
/**
* Associates a name with the current thread. This name will be used to name
* threads in the timeline. Can only be called after a call to Dart_Initialize.
*
* \param name The name of the thread.
*/
DART_EXPORT void Dart_SetThreadName(const char* name);
typedef struct {
const char* name;
const char* value;
} Dart_TimelineRecorderEvent_Argument;
#define DART_TIMELINE_RECORDER_CURRENT_VERSION (0x00000002)
typedef struct {
/* Set to DART_TIMELINE_RECORDER_CURRENT_VERSION */
int32_t version;
/* The event's type / phase. */
Dart_Timeline_Event_Type type;
/* The event's timestamp according to the same clock as
* Dart_TimelineGetMicros. For a duration event, this is the beginning time.
*/
int64_t timestamp0;
/**
* For a duration event, this is the end time. For an async event, this is the
* async ID. For a flow event, this is the flow ID. For a begin or end event,
* this is the event ID (which is only referenced by the MacOS recorder).
*/
int64_t timestamp1_or_id;
/* The current isolate of the event, as if by Dart_GetMainPortId, or
* ILLEGAL_PORT if the event had no current isolate. */
Dart_Port isolate;
/* The current isolate group of the event, as if by
* Dart_CurrentIsolateGroupId, or ILLEGAL_PORT if the event had no current
* isolate group. */
Dart_IsolateGroupId isolate_group;
/* The callback data associated with the isolate if any. */
void* isolate_data;
/* The callback data associated with the isolate group if any. */
void* isolate_group_data;
/* The name / label of the event. */
const char* label;
/* The stream / category of the event. */
const char* stream;
intptr_t argument_count;
Dart_TimelineRecorderEvent_Argument* arguments;
} Dart_TimelineRecorderEvent;
/**
* Callback provided by the embedder to handle the completion of timeline
* events.
*
* \param event A timeline event that has just been completed. The VM keeps
* ownership of the event and any field in it (i.e., the embedder should copy
* any values it needs after the callback returns).
*/
typedef void (*Dart_TimelineRecorderCallback)(
Dart_TimelineRecorderEvent* event);
/**
* Register a `Dart_TimelineRecorderCallback` to be called as timeline events
* are completed.
*
* The callback will be invoked without a current isolate.
*
* The callback will be invoked on the thread completing the event. Because
* `Dart_TimelineEvent` may be called by any thread, the callback may be called
* on any thread.
*
* The callback may be invoked at any time after `Dart_Initialize` is called and
* before `Dart_Cleanup` returns.
*
* If multiple callbacks are registered, only the last callback registered
* will be remembered. Providing a NULL callback will clear the registration
* (i.e., a NULL callback produced a no-op instead of a crash).
*
* Setting a callback is insufficient to receive events through the callback. The
* VM flag `timeline_recorder` must also be set to `callback`.
*/
DART_EXPORT void Dart_SetTimelineRecorderCallback(
Dart_TimelineRecorderCallback callback);
/*
* =======
* Metrics
* =======
*/
/**
* Return metrics gathered for the VM and individual isolates.
*/
DART_EXPORT int64_t
Dart_IsolateGroupHeapOldUsedMetric(Dart_IsolateGroup group); // Byte
DART_EXPORT int64_t
Dart_IsolateGroupHeapOldCapacityMetric(Dart_IsolateGroup group); // Byte
DART_EXPORT int64_t
Dart_IsolateGroupHeapOldExternalMetric(Dart_IsolateGroup group); // Byte
DART_EXPORT int64_t
Dart_IsolateGroupHeapNewUsedMetric(Dart_IsolateGroup group); // Byte
DART_EXPORT int64_t
Dart_IsolateGroupHeapNewCapacityMetric(Dart_IsolateGroup group); // Byte
DART_EXPORT int64_t
Dart_IsolateGroupHeapNewExternalMetric(Dart_IsolateGroup group); // Byte
/*
* ========
* UserTags
* ========
*/
/*
* Gets the current isolate's currently set UserTag instance.
*
* \return The currently set UserTag instance.
*/
DART_EXPORT Dart_Handle Dart_GetCurrentUserTag();
/*
* Gets the current isolate's default UserTag instance.
*
* \return The default UserTag with label 'Default'
*/
DART_EXPORT Dart_Handle Dart_GetDefaultUserTag();
/*
* Creates a new UserTag instance.
*
* \param label The name of the new UserTag.
*
* \return The newly created UserTag instance or an error handle.
*/
DART_EXPORT Dart_Handle Dart_NewUserTag(const char* label);
/*
* Updates the current isolate's UserTag to a new value.
*
* \param user_tag The UserTag to be set as the current UserTag.
*
* \return The previously set UserTag instance or an error handle.
*/
DART_EXPORT Dart_Handle Dart_SetCurrentUserTag(Dart_Handle user_tag);
/*
* Returns the label of a given UserTag instance.
*
* \param user_tag The UserTag from which the label will be retrieved.
*
* \return The UserTag's label. NULL if the user_tag is invalid. The caller is
* responsible for freeing the returned label.
*/
DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_GetUserTagLabel(
Dart_Handle user_tag);
/*
* =======
* Heap Snapshot
* =======
*/
/**
* Callback provided by the caller of `Dart_WriteHeapSnapshot` which is
* used to write out chunks of the requested heap snapshot.
*
* \param context An opaque context which was passed to `Dart_WriteHeapSnapshot`
* together with this callback.
*
* \param buffer Pointer to the buffer containing a chunk of the snapshot.
* The callback owns the buffer and needs to `free` it.
*
* \param size Number of bytes in the `buffer` to be written.
*
* \param is_last Set to `true` for the last chunk. The callback will not
* be invoked again after it was invoked once with `is_last` set to `true`.
*/
typedef void (*Dart_HeapSnapshotWriteChunkCallback)(void* context,
uint8_t* buffer,
intptr_t size,
bool is_last);
/**
* Generate heap snapshot of the current isolate group and stream it into the
* given `callback`. VM would produce snapshot in chunks and send these chunks
* one by one back to the embedder by invoking the provided `callback`.
*
* This API enables embedder to stream snapshot into a file or socket without
* allocating a buffer to hold the whole snapshot in memory.
*
* The isolate group will be paused for the duration of this operation.
*
* \param write Callback used to write chunks of the heap snapshot.
*
* \param context Opaque context which would be passed on each invocation of
* `write` callback.
*
* \returns `nullptr` if the operation is successful otherwise error message.
* Caller owns error message string and needs to `free` it.
*/
DART_EXPORT char* Dart_WriteHeapSnapshot(
Dart_HeapSnapshotWriteChunkCallback write,
void* context);
#endif // RUNTIME_INCLUDE_DART_TOOLS_API_H_

View File

@ -1,16 +0,0 @@
/*
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#ifndef RUNTIME_INCLUDE_DART_VERSION_H_
#define RUNTIME_INCLUDE_DART_VERSION_H_
// On breaking changes the major version is increased.
// On backwards compatible changes the minor version is increased.
// The versioning covers the symbols exposed in dart_api_dl.h
#define DART_API_DL_MAJOR_VERSION 2
#define DART_API_DL_MINOR_VERSION 3
#endif /* RUNTIME_INCLUDE_DART_VERSION_H_ */ /* NOLINT */

View File

@ -1,21 +0,0 @@
/*
* Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
#ifndef RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_
#define RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_
typedef struct {
const char* name;
void (*function)(void);
} DartApiEntry;
typedef struct {
const int major;
const int minor;
const DartApiEntry* const functions;
} DartApi;
#endif /* RUNTIME_INCLUDE_INTERNAL_DART_API_DL_IMPL_H_ */ /* NOLINT */

View File

@ -1,18 +0,0 @@
@echo off
set GOOS=windows
set GOARCH=amd64
set CC=x86_64-w64-mingw32-gcc
set CGO_ENABLED=1
go run ./cli tunnel exit
del bin\libcore.dll bin\HiddifyCli.exe
set CGO_LDFLAGS=
go build -trimpath -tags with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc -ldflags="-w -s" -buildmode=c-shared -o bin/libcore.dll ./custom
go get github.com/akavel/rsrc
go install github.com/akavel/rsrc
rsrc -ico .\assets\hiddify-cli.ico -o cli\bydll\cli.syso
copy bin\libcore.dll .
set CGO_LDFLAGS="libcore.dll"
go build -o bin/HiddifyCli.exe ./cli/bydll/
del libcore.dll

View File

@ -1,35 +0,0 @@
package main
/*
#include <stdlib.h>
#include <stdint.h>
// Import the function from the DLL
char* parseCli(int argc, char** argv);
*/
import "C"
import (
"fmt"
"os"
"unsafe"
)
func main() {
args := os.Args
// Convert []string to []*C.char
var cArgs []*C.char
for _, arg := range args {
cArgs = append(cArgs, C.CString(arg))
}
defer func() {
for _, arg := range cArgs {
C.free(unsafe.Pointer(arg))
}
}()
// Call the C function
result := C.parseCli(C.int(len(cArgs)), (**C.char)(unsafe.Pointer(&cArgs[0])))
fmt.Println(C.GoString(result))
}

View File

@ -1,29 +0,0 @@
package main
import (
"os"
"github.com/hiddify/hiddify-core/cmd"
)
type UpdateRequest struct {
Description string `json:"description,omitempty"`
PrivatePods bool `json:"private_pods"`
OperatingMode string `json:"operating_mode,omitempty"`
ActivationState string `json:"activation_state,omitempty"`
}
func main() {
cmd.ParseCli(os.Args[1:])
// var request UpdateRequest
// // jsonTag, err2 := validation.ErrorFieldName(&request, &request.OperatingMode)
// jsonTag, err2 := request.ValName(&request.OperatingMode)
// fmt.Println(jsonTag, err2)
// RegisterExtension("com.example.extension", NewExampleExtension())
// ex := extensionsMap["com.example.extension"].(*Extension[struct])
// fmt.Println(NewExampleExtension().Get())
// fmt.Println(ex.Get())
}

View File

@ -1,4 +0,0 @@
@echo off
set TAGS=with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc
@REM set TAGS=with_dhcp,with_low_memory,with_conntrack
go run --tags %TAGS% ./cli %*

View File

@ -1,4 +0,0 @@
go mod tidy
TAGS=with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc
# TAGS=with_dhcp,with_low_memory,with_conntrack
go run --tags $TAGS ./cli $@

View File

@ -1,188 +0,0 @@
package cmd
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/hiddify/hiddify-core/config"
pb "github.com/hiddify/hiddify-core/hiddifyrpc"
v2 "github.com/hiddify/hiddify-core/v2"
"github.com/sagernet/sing-box/experimental/libbox"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/spf13/cobra"
)
var (
hiddifySettingPath string
configPath string
defaultConfigs config.HiddifyOptions = *config.DefaultHiddifyOptions()
commandBuildOutputPath string
)
var commandBuild = &cobra.Command{
Use: "build",
Short: "Build configuration",
Run: func(cmd *cobra.Command, args []string) {
err := build(configPath, hiddifySettingPath)
if err != nil {
log.Fatal(err)
}
},
}
var generateConfig = &cobra.Command{
Use: "gen",
Short: "gen configuration",
Run: func(cmd *cobra.Command, args []string) {
conf, err := v2.GenerateConfig(&pb.GenerateConfigRequest{
Path: args[0],
})
if err != nil {
log.Fatal(err)
}
log.Debug(string(conf.ConfigContent))
},
}
var commandCheck = &cobra.Command{
Use: "check",
Short: "Check configuration",
Run: func(cmd *cobra.Command, args []string) {
err := check(configPath)
if err != nil {
log.Fatal(err)
}
},
}
func init() {
commandBuild.Flags().StringVarP(&commandBuildOutputPath, "output", "o", "", "write result to file path instead of stdout")
addHConfigFlags(commandBuild)
mainCommand.AddCommand(commandBuild)
mainCommand.AddCommand(generateConfig)
}
func build(path string, optionsPath string) error {
if workingDir != "" {
path = filepath.Join(workingDir, path)
if optionsPath != "" {
optionsPath = filepath.Join(workingDir, optionsPath)
}
os.Chdir(workingDir)
}
options, err := readConfigAt(path)
if err != nil {
return err
}
HiddifyOptions := &defaultConfigs // config.DefaultHiddifyOptions()
if optionsPath != "" {
HiddifyOptions, err = readHiddifyOptionsAt(optionsPath)
if err != nil {
return err
}
}
config, err := config.BuildConfigJson(*HiddifyOptions, *options)
if err != nil {
return err
}
if commandBuildOutputPath != "" {
outputPath, _ := filepath.Abs(filepath.Join(workingDir, commandBuildOutputPath))
err = os.WriteFile(outputPath, []byte(config), 0o644)
if err != nil {
return err
}
fmt.Println("result successfully written to ", outputPath)
// libbox.Setup(outputPath, workingDir, workingDir, true)
// instance, err := NewService(*patchedOptions)
} else {
os.Stdout.WriteString(config)
}
return nil
}
func check(path string) error {
content, err := os.ReadFile(path)
if err != nil {
return err
}
return libbox.CheckConfig(string(content))
}
func readConfigAt(path string) (*option.Options, error) {
content, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var options option.Options
err = options.UnmarshalJSON(content)
if err != nil {
return nil, err
}
return &options, nil
}
func readConfigBytes(content []byte) (*option.Options, error) {
var options option.Options
err := options.UnmarshalJSON(content)
if err != nil {
return nil, err
}
return &options, nil
}
func readHiddifyOptionsAt(path string) (*config.HiddifyOptions, error) {
content, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var options config.HiddifyOptions
err = json.Unmarshal(content, &options)
if err != nil {
return nil, err
}
if options.Warp.WireguardConfigStr != "" {
err := json.Unmarshal([]byte(options.Warp.WireguardConfigStr), &options.Warp.WireguardConfig)
if err != nil {
return nil, err
}
}
if options.Warp2.WireguardConfigStr != "" {
err := json.Unmarshal([]byte(options.Warp2.WireguardConfigStr), &options.Warp2.WireguardConfig)
if err != nil {
return nil, err
}
}
return &options, nil
}
func addHConfigFlags(commandRun *cobra.Command) {
commandRun.Flags().StringVarP(&configPath, "config", "c", "", "proxy config path or url")
commandRun.MarkFlagRequired("config")
commandRun.Flags().StringVarP(&hiddifySettingPath, "hiddify", "d", "", "Hiddify Setting JSON Path")
commandRun.Flags().BoolVar(&defaultConfigs.EnableFullConfig, "full-config", false, "allows including tags other than output")
commandRun.Flags().StringVar(&defaultConfigs.LogLevel, "log", "warn", "log level")
commandRun.Flags().BoolVar(&defaultConfigs.InboundOptions.EnableTun, "tun", false, "Enable Tun")
commandRun.Flags().BoolVar(&defaultConfigs.InboundOptions.EnableTunService, "tun-service", false, "Enable Tun Service")
commandRun.Flags().BoolVar(&defaultConfigs.InboundOptions.SetSystemProxy, "system-proxy", false, "Enable System Proxy")
commandRun.Flags().Uint16Var(&defaultConfigs.InboundOptions.MixedPort, "in-proxy-port", 2334, "Input Mixed Port")
commandRun.Flags().BoolVar(&defaultConfigs.TLSTricks.EnableFragment, "fragment", false, "Enable Fragment")
commandRun.Flags().StringVar(&defaultConfigs.TLSTricks.FragmentSize, "fragment-size", "2-4", "FragmentSize")
commandRun.Flags().StringVar(&defaultConfigs.TLSTricks.FragmentSleep, "fragment-sleep", "2-4", "FragmentSleep")
commandRun.Flags().BoolVar(&defaultConfigs.TLSTricks.EnablePadding, "padding", false, "Enable Padding")
commandRun.Flags().StringVar(&defaultConfigs.TLSTricks.PaddingSize, "padding-size", "1300-1400", "PaddingSize")
commandRun.Flags().BoolVar(&defaultConfigs.TLSTricks.MixedSNICase, "mixed-sni-case", false, "MixedSNICase")
commandRun.Flags().StringVar(&defaultConfigs.RemoteDnsAddress, "dns-remote", "1.1.1.1", "RemoteDNS (1.1.1.1, https://1.1.1.1/dns-query)")
commandRun.Flags().StringVar(&defaultConfigs.DirectDnsAddress, "dns-direct", "1.1.1.1", "DirectDNS (1.1.1.1, https://1.1.1.1/dns-query)")
commandRun.Flags().StringVar(&defaultConfigs.ClashApiSecret, "web-secret", "", "Web Server Secret")
commandRun.Flags().Uint16Var(&defaultConfigs.ClashApiPort, "web-port", 6756, "Web Server Port")
}

View File

@ -1,21 +0,0 @@
package cmd
import (
_ "github.com/hiddify/hiddify-core/extension/repository"
"github.com/hiddify/hiddify-core/extension/server"
"github.com/spf13/cobra"
)
var commandExtension = &cobra.Command{
Use: "extension",
Short: "extension configuration",
Args: cobra.MaximumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
server.StartTestExtensionServer()
},
}
func init() {
// commandWarp.Flags().StringVarP(&warpKey, "key", "k", "", "warp key")
mainCommand.AddCommand(commandExtension)
}

View File

@ -1,21 +0,0 @@
package cmd
import (
"os"
"github.com/hiddify/hiddify-core/utils"
"github.com/spf13/cobra"
)
var commandGenerateCertification = &cobra.Command{
Use: "gen-cert",
Short: "Generate certification for web server",
Run: func(cmd *cobra.Command, args []string) {
err := os.MkdirAll("cert", 0o644)
if err != nil {
panic("Error: " + err.Error())
}
utils.GenerateCertificate("cert/server-cert.pem", "cert/server-key.pem", true, true)
utils.GenerateCertificate("cert/client-cert.pem", "cert/client-key.pem", false, true)
},
}

View File

@ -1,59 +0,0 @@
package cmd
import (
"os"
"os/signal"
"syscall"
v2 "github.com/hiddify/hiddify-core/v2"
"github.com/sagernet/sing-box/log"
"github.com/spf13/cobra"
)
var commandInstance = &cobra.Command{
Use: "instance",
Short: "instance",
Args: cobra.OnlyValidArgs,
Run: func(cmd *cobra.Command, args []string) {
hiddifySetting := defaultConfigs
if hiddifySettingPath != "" {
hiddifySetting2, err := v2.ReadHiddifyOptionsAt(hiddifySettingPath)
if err != nil {
log.Fatal(err)
}
hiddifySetting = *hiddifySetting2
}
instance, err := v2.RunInstanceString(&hiddifySetting, configPath)
if err != nil {
log.Fatal(err)
}
defer instance.Close()
ping, err := instance.PingAverage("http://cp.cloudflare.com", 4)
if err != nil {
// log.Fatal(err)
}
log.Info("Average Ping to Cloudflare : ", ping, "\n")
for i := 1; i <= 4; i++ {
ping, err := instance.PingCloudflare()
if err != nil {
log.Warn(i, " Error ", err, "\n")
} else {
log.Info(i, " Ping time: ", ping, " ms\n")
}
}
log.Info("Instance is running on port socks5://127.0.0.1:", instance.ListenPort, "\n")
log.Info("Press Ctrl+C to exit\n")
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
<-sigChan
log.Info("CTRL+C recived-->stopping\n")
instance.Close()
},
}
func init() {
mainCommand.AddCommand(commandInstance)
addHConfigFlags(commandInstance)
}

View File

@ -1,52 +0,0 @@
package cmd
import (
"fmt"
"os"
"path/filepath"
"github.com/hiddify/hiddify-core/config"
"github.com/sagernet/sing-box/log"
"github.com/spf13/cobra"
)
var commandParseOutputPath string
var commandParse = &cobra.Command{
Use: "parse",
Short: "Parse configuration",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
err := parse(args[0])
if err != nil {
log.Fatal(err)
}
},
}
func init() {
commandParse.Flags().StringVarP(&commandParseOutputPath, "output", "o", "", "write result to file path instead of stdout")
mainCommand.AddCommand(commandParse)
}
func parse(path string) error {
if workingDir != "" {
path = filepath.Join(workingDir, path)
}
config, err := config.ParseConfig(path, true)
if err != nil {
return err
}
if commandParseOutputPath != "" {
outputPath, _ := filepath.Abs(filepath.Join(workingDir, commandParseOutputPath))
err = os.WriteFile(outputPath, config, 0644)
if err != nil {
return err
}
fmt.Println("result successfully written to ", outputPath)
} else {
os.Stdout.Write(config)
}
return nil
}

View File

@ -1,28 +0,0 @@
package cmd
import (
v2 "github.com/hiddify/hiddify-core/v2"
"github.com/spf13/cobra"
)
var commandRun = &cobra.Command{
Use: "run",
Short: "run",
Args: cobra.OnlyValidArgs,
Run: runCommand,
}
func init() {
// commandRun.PersistentFlags().BoolP("help", "", false, "help for this command")
// commandRun.Flags().StringVarP(&hiddifySettingPath, "hiddify", "d", "", "Hiddify Setting JSON Path")
addHConfigFlags(commandRun)
mainCommand.AddCommand(commandRun)
}
func runCommand(cmd *cobra.Command, args []string) {
v2.Setup("./tmp", "./", "./tmp", 0, false)
v2.RunStandalone(hiddifySettingPath, configPath, defaultConfigs)
}

View File

@ -1,141 +0,0 @@
package cmd
// import (
// "context"
// "fmt"
// "io"
// "math/rand"
// "net/http"
// "net/netip"
// "time"
// "github.com/hiddify/hiddify-core/common"
// // "github.com/hiddify/hiddify-core/extension_repository/cleanip_scanner"
// "github.com/spf13/cobra"
// "golang.org/x/net/proxy"
// )
// var commandTemp = &cobra.Command{
// Use: "temp",
// Short: "temp",
// Args: cobra.MaximumNArgs(2),
// Run: func(cmd *cobra.Command, args []string) {
// // fmt.Printf("Ping time: %d ms\n", Ping())
// scanner := cleanip_scanner.NewScannerEngine(&cleanip_scanner.ScannerOptions{
// UseIPv4: true,
// UseIPv6: common.CanConnectIPv6(),
// MaxDesirableRTT: 500 * time.Millisecond,
// IPQueueSize: 4,
// IPQueueTTL: 10 * time.Second,
// ConcurrentPings: 10,
// // MaxDesirableIPs: e.count,
// CidrList: cleanip_scanner.DefaultCFRanges(),
// PingFunc: func(ip netip.Addr) (cleanip_scanner.IPInfo, error) {
// fmt.Printf("Ping: %s\n", ip.String())
// return cleanip_scanner.IPInfo{
// AddrPort: netip.AddrPortFrom(ip, 80),
// RTT: time.Duration(rand.Intn(1000)),
// CreatedAt: time.Now(),
// }, nil
// },
// },
// )
// ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
// defer cancel()
// scanner.Run(ctx)
// t := time.NewTicker(1 * time.Second)
// defer t.Stop()
// for {
// ipList := scanner.GetAvailableIPs(false)
// if len(ipList) > 1 {
// // e.result = ""
// for i := 0; i < 2; i++ {
// // result = append(result, ipList[i])
// // e.result = e.result + ipList[i].AddrPort.String() + "\n"
// fmt.Printf("%d %s\n", ipList[i].RTT, ipList[i].AddrPort.String())
// }
// return
// }
// select {
// case <-ctx.Done():
// // Context is done
// return
// case <-t.C:
// // Prevent the loop from spinning too fast
// continue
// }
// }
// },
// }
// func init() {
// mainCommand.AddCommand(commandTemp)
// }
// func GetContent(url string) (string, error) {
// return ContentFromURL("GET", url, 10*time.Second)
// }
// func ContentFromURL(method string, url string, timeout time.Duration) (string, error) {
// if method == "" {
// return "", fmt.Errorf("empty method")
// }
// if url == "" {
// return "", fmt.Errorf("empty url")
// }
// req, err := http.NewRequest(method, url, nil)
// if err != nil {
// return "", err
// }
// dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:12334", nil, proxy.Direct)
// if err != nil {
// return "", err
// }
// transport := &http.Transport{
// Dial: dialer.Dial,
// }
// client := &http.Client{
// Transport: transport,
// Timeout: timeout,
// }
// resp, err := client.Do(req)
// if err != nil {
// return "", err
// }
// defer resp.Body.Close()
// if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
// return "", fmt.Errorf("request failed with status code: %d", resp.StatusCode)
// }
// body, err := io.ReadAll(resp.Body)
// if err != nil {
// return "", err
// }
// if body == nil {
// return "", fmt.Errorf("empty body")
// }
// return string(body), nil
// }
// func Ping() int {
// startTime := time.Now()
// _, err := ContentFromURL("HEAD", "https://cp.cloudflare.com", 4*time.Second)
// if err != nil {
// return -1
// }
// duration := time.Since(startTime)
// return int(duration.Milliseconds())
// }

View File

@ -1,40 +0,0 @@
package cmd
import (
"fmt"
"time"
"github.com/hiddify/hiddify-core/config"
v2 "github.com/hiddify/hiddify-core/v2"
"github.com/spf13/cobra"
)
var commandService = &cobra.Command{
Use: "tunnel run/start/stop/install/uninstall/activate/deactivate/exit",
Short: "Tunnel Service run/start/stop/install/uninstall/activate/deactivate/exit",
ValidArgs: []string{"run", "start", "stop", "install", "uninstall", "activate", "deactivate", "exit"},
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
Run: func(cmd *cobra.Command, args []string) {
arg := args[0]
switch arg {
case "activate":
config.ActivateTunnelService(config.HiddifyOptions{
InboundOptions: config.InboundOptions{
EnableTunService: true,
MixedPort: 12334,
TUNStack: "gvisor",
},
})
<-time.After(1 * time.Second)
case "deactivate":
config.DeactivateTunnelServiceForce()
case "exit":
config.ExitTunnelService()
default:
code, out := v2.StartTunnelService(arg)
fmt.Printf("exitCode:%d msg=%s", code, out)
}
},
}

View File

@ -1,126 +0,0 @@
package cmd
import (
"bufio"
"encoding/json"
"fmt"
"os"
"strings"
"github.com/hiddify/hiddify-core/config"
T "github.com/sagernet/sing-box/option"
"github.com/spf13/cobra"
)
var warpKey string
var commandWarp = &cobra.Command{
Use: "warp",
Short: "warp configuration",
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
out, err := generateWarp()
fmt.Printf("out=%v Error! %v", out, err)
if err != nil {
fmt.Printf("Error! %v", err)
}
},
}
func init() {
// commandWarp.Flags().StringVarP(&warpKey, "key", "k", "", "warp key")
mainCommand.AddCommand(commandWarp)
}
type WireGuardConfig struct {
Interface InterfaceConfig `json:"Interface"`
Peer PeerConfig `json:"Peer"`
}
type InterfaceConfig struct {
PrivateKey string `json:"PrivateKey"`
DNS string `json:"DNS"`
Address []string `json:"Address"`
}
type PeerConfig struct {
PublicKey string `json:"PublicKey"`
AllowedIPs []string `json:"AllowedIPs"`
Endpoint string `json:"Endpoint"`
}
type SingboxConfig struct {
Type string `json:"type"`
Tag string `json:"tag"`
Server string `json:"server"`
ServerPort int `json:"server_port"`
LocalAddress []string `json:"local_address"`
PrivateKey string `json:"private_key"`
PeerPublicKey string `json:"peer_public_key"`
Reserved []int `json:"reserved"`
MTU int `json:"mtu"`
}
func readWireGuardConfig(filePath string) (WireGuardConfig, error) {
file, err := os.Open(filePath)
if err != nil {
return WireGuardConfig{}, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
var wgConfig WireGuardConfig
var currentSection string
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
currentSection = strings.TrimSpace(line[1 : len(line)-1])
continue
}
if currentSection == "Interface" {
parseInterfaceConfig(&wgConfig.Interface, line)
} else if currentSection == "Peer" {
parsePeerConfig(&wgConfig.Peer, line)
}
}
return wgConfig, nil
}
func parseInterfaceConfig(interfaceConfig *InterfaceConfig, line string) {
if strings.HasPrefix(line, "PrivateKey") {
interfaceConfig.PrivateKey = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
} else if strings.HasPrefix(line, "DNS") {
interfaceConfig.DNS = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
} else if strings.HasPrefix(line, "Address") {
interfaceConfig.Address = append(interfaceConfig.Address, strings.TrimSpace(strings.SplitN(line, "=", 2)[1]))
}
}
func parsePeerConfig(peerConfig *PeerConfig, line string) {
if strings.HasPrefix(line, "PublicKey") {
peerConfig.PublicKey = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
} else if strings.HasPrefix(line, "AllowedIPs") {
peerConfig.AllowedIPs = append(peerConfig.AllowedIPs, strings.TrimSpace(strings.SplitN(line, "=", 2)[1]))
} else if strings.HasPrefix(line, "Endpoint") {
peerConfig.Endpoint = strings.TrimSpace(strings.SplitN(line, "=", 2)[1])
}
}
func generateWarp() (*T.Outbound, error) {
_, _, wg, err := config.GenerateWarpInfo("", "", "")
// fmt.Printf("%v", wgConfig)
singboxConfig, err := config.GenerateWarpSingbox(*wg, "", 0, "", "", "", "")
singboxJSON, err := json.MarshalIndent(singboxConfig, "", " ")
if err != nil {
fmt.Println("Error marshaling Singbox configuration:", err)
return nil, err
}
fmt.Println(string(singboxJSON))
return nil, nil
}

View File

@ -1,55 +0,0 @@
package cmd
import (
"os"
"time"
"context"
"github.com/sagernet/sing-box/log"
"github.com/spf13/cobra"
)
var (
workingDir string
disableColor bool
)
var mainCommand = &cobra.Command{
Use: "HiddifyCli",
PersistentPreRun: preRun,
}
func init() {
mainCommand.AddCommand(commandService)
mainCommand.AddCommand(commandGenerateCertification)
mainCommand.PersistentFlags().StringVarP(&workingDir, "directory", "D", "", "set working directory")
mainCommand.PersistentFlags().BoolVarP(&disableColor, "disable-color", "", false, "disable color output")
}
func ParseCli(args []string) error {
mainCommand.SetArgs(args)
err := mainCommand.Execute()
if err != nil {
log.Fatal(err)
}
return err
}
func preRun(cmd *cobra.Command, args []string) {
if disableColor {
log.SetStdLogger(log.NewDefaultFactory(context.Background(), log.Formatter{BaseTime: time.Now(), DisableColors: true}, os.Stderr, "", nil, false).Logger())
}
if workingDir != "" {
_, err := os.Stat(workingDir)
if err != nil {
os.MkdirAll(workingDir, 0o0644)
}
if err := os.Chdir(workingDir); err != nil {
log.Fatal(err)
}
}
}

View File

@ -1,217 +0,0 @@
package main
import (
"flag"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/hiddify/hiddify-core/cmd/internal/build_shared"
_ "github.com/sagernet/gomobile"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing/common/rw"
)
var target string
func init() {
flag.StringVar(&target, "target", "android", "target platform")
}
func main() {
flag.Parse()
switch target {
case "windows":
buildWindows()
case "linux":
buildLinux()
case "macos":
buildMacOS()
case "android":
buildAndroid()
case "ios":
buildIOS()
}
}
var (
sharedFlags []string
sharedTags []string
iosTags []string
)
const libName = "libcore"
func init() {
sharedFlags = append(sharedFlags, "-trimpath")
sharedFlags = append(sharedFlags, "-ldflags", "-s -w")
sharedTags = append(sharedTags, "with_gvisor", "with_quic", "with_wireguard", "with_ech", "with_utls", "with_clash_api", "with_grpc")
iosTags = append(iosTags, "with_dhcp", "with_low_memory", "with_conntrack")
}
func setDesktopEnv() {
os.Setenv("CGO_ENABLED", "1")
os.Setenv("buildmode", "c-shared")
}
func buildWindows() {
setDesktopEnv()
os.Setenv("GOOS", "windows")
os.Setenv("GOARCH", "amd64")
os.Setenv("CC", "x86_64-w64-mingw32-gcc")
args := []string{"build"}
args = append(args, sharedFlags...)
args = append(args, "-tags")
args = append(args, strings.Join(sharedTags, ","))
output := filepath.Join("bin", libName+".dll")
args = append(args, "-o", output, "./custom")
command := exec.Command("go", args...)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
log.Debug("command: ", command.String())
err := command.Run()
if err != nil {
log.Fatal(err)
}
}
func buildLinux() {
setDesktopEnv()
os.Setenv("GOOS", "linux")
os.Setenv("GOARCH", "amd64")
args := []string{"build"}
args = append(args, sharedFlags...)
args = append(args, "-tags")
args = append(args, strings.Join(sharedTags, ","))
output := filepath.Join("bin", libName+".so")
args = append(args, "-o", output, "./custom")
command := exec.Command("go", args...)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
log.Debug("command: ", command.String())
err := command.Run()
if err != nil {
log.Fatal(err)
}
}
func buildMacOS() {
libPaths := []string{}
for _, arch := range []string{"amd64", "arm64"} {
out, err := buildMacOSArch(arch)
if err != nil {
log.Fatal(err)
return
}
libPaths = append(libPaths, out)
}
args := []string{"-create"}
args = append(args, libPaths...)
args = append(args, "-output", filepath.Join("bin", libName+".dylib"))
command := exec.Command("lipo", args...)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
log.Debug("command: ", command.String())
err := command.Run()
if err != nil {
log.Fatal(err)
}
}
func buildMacOSArch(arch string) (string, error) {
setDesktopEnv()
os.Setenv("GOOS", "darwin")
os.Setenv("GOARCH", arch)
os.Setenv("CGO_CFLAGS", "-mmacosx-version-min=10.11")
os.Setenv("CGO_LDFLAGS", "-mmacosx-version-min=10.11")
args := []string{"build"}
args = append(args, sharedFlags...)
tags := append(sharedTags, iosTags...)
args = append(args, "-tags")
args = append(args, strings.Join(tags, ","))
filename := libName + "-" + arch + ".dylib"
output := filepath.Join("bin", filename)
args = append(args, "-o", output, "./custom")
command := exec.Command("go", args...)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
log.Debug("command: ", command.String())
err := command.Run()
if err != nil {
return "", err
}
return output, nil
}
func buildAndroid() {
build_shared.FindMobile()
build_shared.FindSDK()
args := []string{
"bind",
"-v",
"-androidapi", "21",
"-javapkg=io.nekohasekai",
"-libname=box",
"-target=android",
}
args = append(args, sharedFlags...)
args = append(args, "-tags")
args = append(args, strings.Join(sharedTags, ","))
output := filepath.Join("bin", libName+".aar")
args = append(args, "-o", output, "github.com/sagernet/sing-box/experimental/libbox", "./mobile")
command := exec.Command(build_shared.GoBinPath+"/gomobile", args...)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
log.Debug("command: ", command.String())
err := command.Run()
if err != nil {
log.Fatal(err)
}
}
func buildIOS() {
build_shared.FindMobile()
args := []string{
"bind",
"-v",
"-libname=box",
"-target", "ios,iossimulator,tvos,tvossimulator,macos",
}
args = append(args, sharedFlags...)
tags := append(sharedTags, iosTags...)
args = append(args, "-tags")
args = append(args, strings.Join(tags, ","))
output := filepath.Join("bin", "Libcore.xcframework")
args = append(args, "-o", output, "github.com/sagernet/sing-box/experimental/libbox", "./mobile")
command := exec.Command(build_shared.GoBinPath+"/gomobile", args...)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
log.Debug("command: ", command.String())
err := command.Run()
if err != nil {
log.Fatal(err)
}
rw.CopyFile("Info.plist", filepath.Join(output, "Info.plist"))
}

View File

@ -1,99 +0,0 @@
package build_shared
import (
"go/build"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/rw"
)
var (
androidSDKPath string
androidNDKPath string
)
func FindSDK() {
searchPath := []string{
"$ANDROID_HOME",
"$HOME/Android/Sdk",
"$HOME/.local/lib/android/sdk",
"$HOME/Library/Android/sdk",
}
for _, path := range searchPath {
path = os.ExpandEnv(path)
if rw.FileExists(path + "/licenses/android-sdk-license") {
androidSDKPath = path
break
}
}
if androidSDKPath == "" {
log.Fatal("android SDK not found")
}
if !findNDK() {
log.Fatal("android NDK not found")
}
os.Setenv("ANDROID_HOME", androidSDKPath)
os.Setenv("ANDROID_SDK_HOME", androidSDKPath)
os.Setenv("ANDROID_NDK_HOME", androidNDKPath)
os.Setenv("NDK", androidNDKPath)
os.Setenv("PATH", os.Getenv("PATH")+":"+filepath.Join(androidNDKPath, "toolchains", "llvm", "prebuilt", runtime.GOOS+"-x86_64", "bin"))
}
func findNDK() bool {
if rw.FileExists(androidSDKPath + "/ndk/26.1.10909125") {
androidNDKPath = androidSDKPath + "/ndk/26.1.10909125"
return true
}
ndkVersions, err := os.ReadDir(androidSDKPath + "/ndk")
if err != nil {
return false
}
versionNames := common.Map(ndkVersions, os.DirEntry.Name)
if len(versionNames) == 0 {
return false
}
sort.Slice(versionNames, func(i, j int) bool {
iVersions := strings.Split(versionNames[i], ".")
jVersions := strings.Split(versionNames[j], ".")
for k := 0; k < len(iVersions) && k < len(jVersions); k++ {
iVersion, _ := strconv.Atoi(iVersions[k])
jVersion, _ := strconv.Atoi(jVersions[k])
if iVersion != jVersion {
return iVersion > jVersion
}
}
return true
})
for _, versionName := range versionNames {
if rw.FileExists(androidSDKPath + "/ndk/" + versionName) {
androidNDKPath = androidSDKPath + "/ndk/" + versionName
return true
}
}
return false
}
var GoBinPath string
func FindMobile() {
goBin := filepath.Join(build.Default.GOPATH, "bin")
if runtime.GOOS == "windows" {
if !rw.FileExists(goBin + "/" + "gobind.exe") {
log.Fatal("missing gomobile.exe installation")
}
} else {
if !rw.FileExists(goBin + "/" + "gobind") {
log.Fatal("missing gomobile installation")
}
}
GoBinPath = goBin
}

View File

@ -1,49 +0,0 @@
//go:build !windows
package config
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
func ExecuteCmd(executablePath string, background bool, args ...string) (string, error) {
cwd := filepath.Dir(executablePath)
if appimage := os.Getenv("APPIMAGE"); appimage != "" {
executablePath = appimage
if !background {
return "Fail", fmt.Errorf("Appimage cannot have service")
}
}
commands := [][]string{
{"cocoasudo", "--prompt=Hiddify needs root for tunneling.", executablePath},
{"gksu", executablePath},
{"pkexec", executablePath},
{"xterm", "-e", "sudo", executablePath, strings.Join(args, " ")},
{"sudo", executablePath},
}
var err error
var cmd *exec.Cmd
for _, command := range commands {
cmd = exec.Command(command[0], command[1:]...)
cmd.Dir = cwd
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
fmt.Printf("Running command: %v\n", command)
if background {
err = cmd.Start()
} else {
err = cmd.Run()
}
if err == nil {
return "Ok", nil
}
}
return "", fmt.Errorf("Error executing run as root shell command")
}

View File

@ -1,32 +0,0 @@
//go:build windows
package config
import (
"os"
"strings"
"syscall"
"golang.org/x/sys/windows"
)
func ExecuteCmd(exe string, background bool, args ...string) (string, error) {
verb := "runas"
cwd, err := os.Getwd() // Error handling added
if err != nil {
return "", err
}
verbPtr, _ := syscall.UTF16PtrFromString(verb)
exePtr, _ := syscall.UTF16PtrFromString(exe)
cwdPtr, _ := syscall.UTF16PtrFromString(cwd)
argPtr, _ := syscall.UTF16PtrFromString(strings.Join(args, " "))
var showCmd int32 = 0 // SW_NORMAL
err = windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd)
if err != nil {
return "", err
}
return "", nil
}

View File

@ -1,188 +0,0 @@
package config
import (
context "context"
"fmt"
"log"
"net"
"os"
"path/filepath"
"runtime"
"time"
pb "github.com/hiddify/hiddify-core/hiddifyrpc"
"github.com/sagernet/sing-box/option"
dns "github.com/sagernet/sing-dns"
grpc "google.golang.org/grpc"
)
const (
serviceURL = "http://localhost:18020"
startEndpoint = "/start"
stopEndpoint = "/stop"
)
var tunnelServiceRunning = false
func isSupportedOS() bool {
return runtime.GOOS == "windows" || runtime.GOOS == "linux"
}
func ActivateTunnelService(opt HiddifyOptions) (bool, error) {
tunnelServiceRunning = true
// if !isSupportedOS() {
// return false, E.New("Unsupported OS: " + runtime.GOOS)
// }
go startTunnelRequestWithFailover(opt, true)
return true, nil
}
func DeactivateTunnelServiceForce() (bool, error) {
return stopTunnelRequest()
}
func DeactivateTunnelService() (bool, error) {
// if !isSupportedOS() {
// return true, nil
// }
if tunnelServiceRunning {
res, err := stopTunnelRequest()
if err != nil {
tunnelServiceRunning = false
}
return res, err
} else {
go stopTunnelRequest()
}
return true, nil
}
func startTunnelRequestWithFailover(opt HiddifyOptions, installService bool) {
res, err := startTunnelRequest(opt, installService)
fmt.Printf("Start Tunnel Result: %v\n", res)
if err != nil {
fmt.Printf("Start Tunnel Failed! Stopping core... err=%v\n", err)
// StopAndAlert(pb.MessageType.MessageType_UNEXPECTED_ERROR, "Start Tunnel Failed! Stopping...")
}
}
func isPortInUse(port string) bool {
listener, err := net.Listen("tcp", "127.0.0.1:"+port)
if err != nil {
return true // Port is in use
}
defer listener.Close()
return false // Port is available
}
func startTunnelRequest(opt HiddifyOptions, installService bool) (bool, error) {
if !isPortInUse("18020") {
if installService {
return runTunnelService(opt)
}
return false, fmt.Errorf("service is not running")
}
conn, err := grpc.Dial("127.0.0.1:18020", grpc.WithInsecure())
if err != nil {
log.Printf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewTunnelServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
_, _ = c.Stop(ctx, &pb.Empty{})
res, err := c.Start(ctx, &pb.TunnelStartRequest{
Ipv6: opt.IPv6Mode == option.DomainStrategy(dns.DomainStrategyUseIPv4),
ServerPort: int32(opt.InboundOptions.MixedPort),
StrictRoute: opt.InboundOptions.StrictRoute,
EndpointIndependentNat: true,
Stack: opt.InboundOptions.TUNStack,
})
if err != nil {
log.Printf("could not greet: %+v %+v", res, err)
if installService {
ExitTunnelService()
return runTunnelService(opt)
}
return false, err
}
return true, nil
}
func stopTunnelRequest() (bool, error) {
conn, err := grpc.Dial("127.0.0.1:18020", grpc.WithInsecure())
if err != nil {
log.Printf("did not connect: %v", err)
return false, err
}
defer conn.Close()
c := pb.NewTunnelServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
defer cancel()
res, err := c.Stop(ctx, &pb.Empty{})
if err != nil {
log.Printf("did not Stopped: %v %v", res, err)
_, _ = c.Stop(ctx, &pb.Empty{})
return false, err
}
return true, nil
}
func ExitTunnelService() (bool, error) {
conn, err := grpc.Dial("127.0.0.1:18020", grpc.WithInsecure())
if err != nil {
log.Printf("did not connect: %v", err)
return false, err
}
defer conn.Close()
c := pb.NewTunnelServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*1)
defer cancel()
res, err := c.Exit(ctx, &pb.Empty{})
if res != nil {
log.Printf("did not exit: %v %v", res, err)
return false, err
}
return true, nil
}
func runTunnelService(opt HiddifyOptions) (bool, error) {
executablePath := getTunnelServicePath()
fmt.Printf("Executable path is %s", executablePath)
out, err := ExecuteCmd(executablePath, false, "tunnel", "install")
fmt.Println("Shell command executed:", out, err)
if err != nil {
out, err = ExecuteCmd(executablePath, true, "tunnel", "run")
fmt.Println("Shell command executed without flag:", out, err)
}
if err == nil {
<-time.After(1 * time.Second) // wait until service loaded completely
}
return startTunnelRequest(opt, false)
}
func getTunnelServicePath() string {
var fullPath string
exePath, _ := os.Executable()
binFolder := filepath.Dir(exePath)
switch runtime.GOOS {
case "windows":
fullPath = "HiddifyCli.exe"
case "darwin":
fallthrough
default:
fullPath = "HiddifyCli"
}
abspath, _ := filepath.Abs(filepath.Join(binFolder, fullPath))
return abspath
}

View File

@ -1,869 +0,0 @@
package config
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"math/rand"
"net"
"net/netip"
"net/url"
"runtime"
"strings"
"time"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/option"
dns "github.com/sagernet/sing-dns"
)
const (
DNSRemoteTag = "dns-remote"
DNSLocalTag = "dns-local"
DNSDirectTag = "dns-direct"
DNSBlockTag = "dns-block"
DNSFakeTag = "dns-fake"
DNSTricksDirectTag = "dns-trick-direct"
OutboundDirectTag = "direct"
OutboundBypassTag = "bypass"
OutboundBlockTag = "block"
OutboundSelectTag = "select"
OutboundURLTestTag = "auto"
OutboundDNSTag = "dns-out"
OutboundDirectFragmentTag = "direct-fragment"
InboundTUNTag = "tun-in"
InboundMixedTag = "mixed-in"
InboundDNSTag = "dns-in"
)
var OutboundMainProxyTag = OutboundSelectTag
func BuildConfigJson(configOpt HiddifyOptions, input option.Options) (string, error) {
options, err := BuildConfig(configOpt, input)
if err != nil {
return "", err
}
var buffer bytes.Buffer
json.NewEncoder(&buffer)
encoder := json.NewEncoder(&buffer)
encoder.SetIndent("", " ")
err = encoder.Encode(options)
if err != nil {
return "", err
}
return buffer.String(), nil
}
// TODO include selectors
func BuildConfig(opt HiddifyOptions, input option.Options) (*option.Options, error) {
fmt.Printf("config options: %++v\n", opt)
var options option.Options
if opt.EnableFullConfig {
options.Inbounds = input.Inbounds
options.DNS = input.DNS
options.Route = input.Route
}
setClashAPI(&options, &opt)
setLog(&options, &opt)
setInbound(&options, &opt)
setDns(&options, &opt)
setRoutingOptions(&options, &opt)
setFakeDns(&options, &opt)
err := setOutbounds(&options, &input, &opt)
if err != nil {
return nil, err
}
return &options, nil
}
func addForceDirect(options *option.Options, opt *HiddifyOptions, directDNSDomains map[string]bool) {
remoteDNSAddress := opt.RemoteDnsAddress
if strings.Contains(remoteDNSAddress, "://") {
remoteDNSAddress = strings.SplitAfter(remoteDNSAddress, "://")[1]
}
parsedUrl, err := url.Parse(fmt.Sprintf("https://%s", remoteDNSAddress))
if err == nil && net.ParseIP(parsedUrl.Host) == nil {
directDNSDomains[parsedUrl.Host] = true
}
if len(directDNSDomains) > 0 {
// trickDnsDomains := []string{}
// directDNSDomains = removeDuplicateStr(directDNSDomains)
// b, _ := batch.New(context.Background(), batch.WithConcurrencyNum[bool](10))
// for _, d := range directDNSDomains {
// b.Go(d, func() (bool, error) {
// return isBlockedDomain(d), nil
// })
// }
// b.Wait()
// for domain, isBlock := range b.Result() {
// if isBlock.Value {
// trickDnsDomains = append(trickDnsDomains, domain)
// }
// }
// trickDomains := strings.Join(trickDnsDomains, ",")
// trickRule := Rule{Domains: trickDomains, Outbound: OutboundBypassTag}
// trickDnsRule := trickRule.MakeDNSRule()
// trickDnsRule.Server = DNSTricksDirectTag
// options.DNS.Rules = append([]option.DNSRule{{Type: C.RuleTypeDefault, DefaultOptions: trickDnsRule}}, options.DNS.Rules...)
directDNSDomainskeys := make([]string, 0, len(directDNSDomains))
for key := range directDNSDomains {
directDNSDomainskeys = append(directDNSDomainskeys, key)
}
domains := strings.Join(directDNSDomainskeys, ",")
directRule := Rule{Domains: domains, Outbound: OutboundBypassTag}
dnsRule := directRule.MakeDNSRule()
dnsRule.Server = DNSDirectTag
options.DNS.Rules = append([]option.DNSRule{{Type: C.RuleTypeDefault, DefaultOptions: dnsRule}}, options.DNS.Rules...)
}
}
func setOutbounds(options *option.Options, input *option.Options, opt *HiddifyOptions) error {
directDNSDomains := make(map[string]bool)
var outbounds []option.Outbound
var tags []string
OutboundMainProxyTag = OutboundSelectTag
// inbound==warp over proxies
// outbound==proxies over warp
if opt.Warp.EnableWarp {
for _, out := range input.Outbounds {
if out.Type == C.TypeCustom {
if warp, ok := out.CustomOptions["warp"].(map[string]interface{}); ok {
key, _ := warp["key"].(string)
if key == "p1" {
opt.Warp.EnableWarp = false
break
}
}
}
if out.Type == C.TypeWireGuard && (out.WireGuardOptions.PrivateKey == opt.Warp.WireguardConfig.PrivateKey || out.WireGuardOptions.PrivateKey == "p1") {
opt.Warp.EnableWarp = false
break
}
}
}
if opt.Warp.EnableWarp && (opt.Warp.Mode == "warp_over_proxy" || opt.Warp.Mode == "proxy_over_warp") {
out, err := GenerateWarpSingbox(opt.Warp.WireguardConfig, opt.Warp.CleanIP, opt.Warp.CleanPort, opt.Warp.FakePackets, opt.Warp.FakePacketSize, opt.Warp.FakePacketDelay, opt.Warp.FakePacketMode)
if err != nil {
return fmt.Errorf("failed to generate warp config: %v", err)
}
out.Tag = "Hiddify Warp ✅"
if opt.Warp.Mode == "warp_over_proxy" {
out.WireGuardOptions.Detour = OutboundSelectTag
OutboundMainProxyTag = out.Tag
} else {
out.WireGuardOptions.Detour = OutboundDirectTag
}
patchWarp(out, opt, true, nil)
outbounds = append(outbounds, *out)
// tags = append(tags, out.Tag)
}
for _, out := range input.Outbounds {
outbound, serverDomain, err := patchOutbound(out, *opt, options.DNS.StaticIPs)
if err != nil {
return err
}
if serverDomain != "" {
directDNSDomains[serverDomain] = true
}
out = *outbound
switch out.Type {
case C.TypeDirect, C.TypeBlock, C.TypeDNS:
continue
case C.TypeSelector, C.TypeURLTest:
continue
case C.TypeCustom:
continue
default:
if !strings.Contains(out.Tag, "§hide§") {
tags = append(tags, out.Tag)
}
out = patchHiddifyWarpFromConfig(out, *opt)
outbounds = append(outbounds, out)
}
}
urlTest := option.Outbound{
Type: C.TypeURLTest,
Tag: OutboundURLTestTag,
URLTestOptions: option.URLTestOutboundOptions{
Outbounds: tags,
URL: opt.ConnectionTestUrl,
Interval: option.Duration(opt.URLTestInterval.Duration()),
// IdleTimeout: option.Duration(opt.URLTestIdleTimeout.Duration()),
Tolerance: 1,
IdleTimeout: option.Duration(opt.URLTestInterval.Duration().Nanoseconds() * 3),
InterruptExistConnections: true,
},
}
defaultSelect := urlTest.Tag
for _, tag := range tags {
if strings.Contains(tag, "§default§") {
defaultSelect = "§default§"
}
}
selector := option.Outbound{
Type: C.TypeSelector,
Tag: OutboundSelectTag,
SelectorOptions: option.SelectorOutboundOptions{
Outbounds: append([]string{urlTest.Tag}, tags...),
Default: defaultSelect,
InterruptExistConnections: true,
},
}
outbounds = append([]option.Outbound{selector, urlTest}, outbounds...)
options.Outbounds = append(
outbounds,
[]option.Outbound{
{
Tag: OutboundDNSTag,
Type: C.TypeDNS,
},
{
Tag: OutboundDirectTag,
Type: C.TypeDirect,
},
{
Tag: OutboundDirectFragmentTag,
Type: C.TypeDirect,
DirectOptions: option.DirectOutboundOptions{
DialerOptions: option.DialerOptions{
TCPFastOpen: false,
TLSFragment: option.TLSFragmentOptions{
Enabled: true,
Size: opt.TLSTricks.FragmentSize,
Sleep: opt.TLSTricks.FragmentSleep,
},
},
},
},
{
Tag: OutboundBypassTag,
Type: C.TypeDirect,
},
{
Tag: OutboundBlockTag,
Type: C.TypeBlock,
},
}...,
)
addForceDirect(options, opt, directDNSDomains)
return nil
}
func setClashAPI(options *option.Options, opt *HiddifyOptions) {
if opt.EnableClashApi {
if opt.ClashApiSecret == "" {
opt.ClashApiSecret = generateRandomString(16)
}
options.Experimental = &option.ExperimentalOptions{
ClashAPI: &option.ClashAPIOptions{
ExternalController: fmt.Sprintf("%s:%d", "127.0.0.1", opt.ClashApiPort),
Secret: opt.ClashApiSecret,
},
CacheFile: &option.CacheFileOptions{
Enabled: true,
Path: "clash.db",
},
}
}
}
func setLog(options *option.Options, opt *HiddifyOptions) {
options.Log = &option.LogOptions{
Level: opt.LogLevel,
Output: opt.LogFile,
Disabled: false,
Timestamp: true,
DisableColor: true,
}
}
func setInbound(options *option.Options, opt *HiddifyOptions) {
var inboundDomainStrategy option.DomainStrategy
if !opt.ResolveDestination {
inboundDomainStrategy = option.DomainStrategy(dns.DomainStrategyAsIS)
} else {
inboundDomainStrategy = opt.IPv6Mode
}
if opt.EnableTunService {
ActivateTunnelService(*opt)
} else if opt.EnableTun {
tunInbound := option.Inbound{
Type: C.TypeTun,
Tag: InboundTUNTag,
TunOptions: option.TunInboundOptions{
Stack: opt.TUNStack,
MTU: opt.MTU,
AutoRoute: true,
StrictRoute: opt.StrictRoute,
EndpointIndependentNat: true,
// GSO: runtime.GOOS != "windows",
InboundOptions: option.InboundOptions{
SniffEnabled: true,
SniffOverrideDestination: false,
DomainStrategy: inboundDomainStrategy,
},
},
}
switch opt.IPv6Mode {
case option.DomainStrategy(dns.DomainStrategyUseIPv4):
tunInbound.TunOptions.Inet4Address = []netip.Prefix{
netip.MustParsePrefix("172.19.0.1/28"),
}
case option.DomainStrategy(dns.DomainStrategyUseIPv6):
tunInbound.TunOptions.Inet6Address = []netip.Prefix{
netip.MustParsePrefix("fdfe:dcba:9876::1/126"),
}
default:
tunInbound.TunOptions.Inet4Address = []netip.Prefix{
netip.MustParsePrefix("172.19.0.1/28"),
}
tunInbound.TunOptions.Inet6Address = []netip.Prefix{
netip.MustParsePrefix("fdfe:dcba:9876::1/126"),
}
}
options.Inbounds = append(options.Inbounds, tunInbound)
}
var bind string
if opt.AllowConnectionFromLAN {
bind = "0.0.0.0"
} else {
bind = "127.0.0.1"
}
options.Inbounds = append(
options.Inbounds,
option.Inbound{
Type: C.TypeMixed,
Tag: InboundMixedTag,
MixedOptions: option.HTTPMixedInboundOptions{
ListenOptions: option.ListenOptions{
Listen: option.NewListenAddress(netip.MustParseAddr(bind)),
ListenPort: opt.MixedPort,
InboundOptions: option.InboundOptions{
SniffEnabled: true,
SniffOverrideDestination: true,
DomainStrategy: inboundDomainStrategy,
},
},
SetSystemProxy: opt.SetSystemProxy,
},
},
)
options.Inbounds = append(
options.Inbounds,
option.Inbound{
Type: C.TypeDirect,
Tag: InboundDNSTag,
DirectOptions: option.DirectInboundOptions{
ListenOptions: option.ListenOptions{
Listen: option.NewListenAddress(netip.MustParseAddr(bind)),
ListenPort: opt.LocalDnsPort,
},
// OverrideAddress: "1.1.1.1",
// OverridePort: 53,
},
},
)
}
func setDns(options *option.Options, opt *HiddifyOptions) {
options.DNS = &option.DNSOptions{
StaticIPs: map[string][]string{},
DNSClientOptions: option.DNSClientOptions{
IndependentCache: opt.IndependentDNSCache,
},
Final: DNSRemoteTag,
Servers: []option.DNSServerOptions{
{
Tag: DNSRemoteTag,
Address: opt.RemoteDnsAddress,
AddressResolver: DNSDirectTag,
Strategy: opt.RemoteDnsDomainStrategy,
},
{
Tag: DNSTricksDirectTag,
Address: "https://sky.rethinkdns.com/",
// AddressResolver: "dns-local",
Strategy: opt.DirectDnsDomainStrategy,
Detour: OutboundDirectFragmentTag,
},
{
Tag: DNSDirectTag,
Address: opt.DirectDnsAddress,
AddressResolver: DNSLocalTag,
Strategy: opt.DirectDnsDomainStrategy,
Detour: OutboundDirectTag,
},
{
Tag: DNSLocalTag,
Address: "local",
Detour: OutboundDirectTag,
},
{
Tag: DNSBlockTag,
Address: "rcode://success",
},
},
}
sky_rethinkdns := getIPs([]string{"www.speedtest.net", "sky.rethinkdns.com"})
if len(sky_rethinkdns) > 0 {
options.DNS.StaticIPs["sky.rethinkdns.com"] = sky_rethinkdns
}
}
func setFakeDns(options *option.Options, opt *HiddifyOptions) {
if opt.EnableFakeDNS {
inet4Range := netip.MustParsePrefix("198.18.0.0/15")
inet6Range := netip.MustParsePrefix("fc00::/18")
options.DNS.FakeIP = &option.DNSFakeIPOptions{
Enabled: true,
Inet4Range: &inet4Range,
Inet6Range: &inet6Range,
}
options.DNS.Servers = append(
options.DNS.Servers,
option.DNSServerOptions{
Tag: DNSFakeTag,
Address: "fakeip",
Strategy: option.DomainStrategy(dns.DomainStrategyUseIPv4),
},
)
options.DNS.Rules = append(
options.DNS.Rules,
option.DNSRule{
Type: C.RuleTypeDefault,
DefaultOptions: option.DefaultDNSRule{
Inbound: []string{InboundTUNTag},
Server: DNSFakeTag,
DisableCache: true,
},
},
)
}
}
func setRoutingOptions(options *option.Options, opt *HiddifyOptions) {
dnsRules := []option.DefaultDNSRule{}
routeRules := []option.Rule{}
rulesets := []option.RuleSet{}
if opt.EnableTun && runtime.GOOS == "android" {
routeRules = append(
routeRules,
option.Rule{
Type: C.RuleTypeDefault,
DefaultOptions: option.DefaultRule{
Inbound: []string{InboundTUNTag},
PackageName: []string{"app.brAccelerator.com"},
Outbound: OutboundBypassTag,
},
},
)
// routeRules = append(
// routeRules,
// option.Rule{
// Type: C.RuleTypeDefault,
// DefaultOptions: option.DefaultRule{
// ProcessName: []string{"Hiddify", "Hiddify.exe", "HiddifyCli", "HiddifyCli.exe"},
// Outbound: OutboundBypassTag,
// },
// },
// )
}
routeRules = append(routeRules, option.Rule{
Type: C.RuleTypeDefault,
DefaultOptions: option.DefaultRule{
Inbound: []string{InboundDNSTag},
Outbound: OutboundDNSTag,
},
})
routeRules = append(routeRules, option.Rule{
Type: C.RuleTypeDefault,
DefaultOptions: option.DefaultRule{
Port: []uint16{53},
Outbound: OutboundDNSTag,
},
})
// {
// Type: C.RuleTypeDefault,
// DefaultOptions: option.DefaultRule{
// ClashMode: "Direct",
// Outbound: OutboundDirectTag,
// },
// },
// {
// Type: C.RuleTypeDefault,
// DefaultOptions: option.DefaultRule{
// ClashMode: "Global",
// Outbound: OutboundMainProxyTag,
// },
// }, }
if opt.BypassLAN {
routeRules = append(
routeRules,
option.Rule{
Type: C.RuleTypeDefault,
DefaultOptions: option.DefaultRule{
// GeoIP: []string{"private"},
IPIsPrivate: true,
Outbound: OutboundBypassTag,
},
},
)
}
for _, rule := range opt.Rules {
routeRule := rule.MakeRule()
switch rule.Outbound {
case "bypass":
routeRule.Outbound = OutboundBypassTag
case "block":
routeRule.Outbound = OutboundBlockTag
case "proxy":
routeRule.Outbound = OutboundMainProxyTag
}
if routeRule.IsValid() {
routeRules = append(
routeRules,
option.Rule{
Type: C.RuleTypeDefault,
DefaultOptions: routeRule,
},
)
}
dnsRule := rule.MakeDNSRule()
switch rule.Outbound {
case "bypass":
dnsRule.Server = DNSDirectTag
case "block":
dnsRule.Server = DNSBlockTag
dnsRule.DisableCache = true
case "proxy":
if opt.EnableFakeDNS {
fakeDnsRule := dnsRule
fakeDnsRule.Server = DNSFakeTag
fakeDnsRule.Inbound = []string{InboundTUNTag, InboundMixedTag}
dnsRules = append(dnsRules, fakeDnsRule)
}
dnsRule.Server = DNSRemoteTag
}
dnsRules = append(dnsRules, dnsRule)
}
parsedURL, err := url.Parse(opt.ConnectionTestUrl)
if err == nil {
var dnsCPttl uint32 = 3000
dnsRules = append(dnsRules, option.DefaultDNSRule{
Domain: []string{parsedURL.Host},
Server: DNSRemoteTag,
RewriteTTL: &dnsCPttl,
DisableCache: false,
})
}
if opt.BlockAds {
rulesets = append(rulesets, option.RuleSet{
Type: C.RuleSetTypeRemote,
Tag: "geosite-ads",
Format: C.RuleSetFormatBinary,
RemoteOptions: option.RemoteRuleSet{
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-category-ads-all.srs",
UpdateInterval: option.Duration(5 * time.Hour * 24),
},
})
rulesets = append(rulesets, option.RuleSet{
Type: C.RuleSetTypeRemote,
Tag: "geosite-malware",
Format: C.RuleSetFormatBinary,
RemoteOptions: option.RemoteRuleSet{
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-malware.srs",
UpdateInterval: option.Duration(5 * time.Hour * 24),
},
})
rulesets = append(rulesets, option.RuleSet{
Type: C.RuleSetTypeRemote,
Tag: "geosite-phishing",
Format: C.RuleSetFormatBinary,
RemoteOptions: option.RemoteRuleSet{
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-phishing.srs",
UpdateInterval: option.Duration(5 * time.Hour * 24),
},
})
rulesets = append(rulesets, option.RuleSet{
Type: C.RuleSetTypeRemote,
Tag: "geosite-cryptominers",
Format: C.RuleSetFormatBinary,
RemoteOptions: option.RemoteRuleSet{
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geosite-cryptominers.srs",
UpdateInterval: option.Duration(5 * time.Hour * 24),
},
})
rulesets = append(rulesets, option.RuleSet{
Type: C.RuleSetTypeRemote,
Tag: "geoip-phishing",
Format: C.RuleSetFormatBinary,
RemoteOptions: option.RemoteRuleSet{
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geoip-phishing.srs",
UpdateInterval: option.Duration(5 * time.Hour * 24),
},
})
rulesets = append(rulesets, option.RuleSet{
Type: C.RuleSetTypeRemote,
Tag: "geoip-malware",
Format: C.RuleSetFormatBinary,
RemoteOptions: option.RemoteRuleSet{
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/block/geoip-malware.srs",
UpdateInterval: option.Duration(5 * time.Hour * 24),
},
})
routeRules = append(routeRules, option.Rule{
Type: C.RuleTypeDefault,
DefaultOptions: option.DefaultRule{
RuleSet: []string{
"geosite-ads",
"geosite-malware",
"geosite-phishing",
"geosite-cryptominers",
"geoip-malware",
"geoip-phishing",
},
Outbound: OutboundBlockTag,
},
})
dnsRules = append(dnsRules, option.DefaultDNSRule{
RuleSet: []string{
"geosite-ads",
"geosite-malware",
"geosite-phishing",
"geosite-cryptominers",
"geoip-malware",
"geoip-phishing",
},
Server: DNSBlockTag,
// DisableCache: true,
})
}
if opt.Region != "other" {
dnsRules = append(dnsRules, option.DefaultDNSRule{
DomainSuffix: []string{"." + opt.Region},
Server: DNSDirectTag,
})
routeRules = append(routeRules, option.Rule{
Type: C.RuleTypeDefault,
DefaultOptions: option.DefaultRule{
DomainSuffix: []string{"." + opt.Region},
Outbound: OutboundDirectTag,
},
})
dnsRules = append(dnsRules, option.DefaultDNSRule{
RuleSet: []string{
"geoip-" + opt.Region,
"geosite-" + opt.Region,
},
Server: DNSDirectTag,
})
rulesets = append(rulesets, option.RuleSet{
Type: C.RuleSetTypeRemote,
Tag: "geoip-" + opt.Region,
Format: C.RuleSetFormatBinary,
RemoteOptions: option.RemoteRuleSet{
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/country/geoip-" + opt.Region + ".srs",
UpdateInterval: option.Duration(5 * time.Hour * 24),
},
})
rulesets = append(rulesets, option.RuleSet{
Type: C.RuleSetTypeRemote,
Tag: "geosite-" + opt.Region,
Format: C.RuleSetFormatBinary,
RemoteOptions: option.RemoteRuleSet{
URL: "https://raw.githubusercontent.com/hiddify/hiddify-geo/rule-set/country/geosite-" + opt.Region + ".srs",
UpdateInterval: option.Duration(5 * time.Hour * 24),
},
})
routeRules = append(routeRules, option.Rule{
Type: C.RuleTypeDefault,
DefaultOptions: option.DefaultRule{
RuleSet: []string{
"geoip-" + opt.Region,
"geosite-" + opt.Region,
},
Outbound: OutboundDirectTag,
},
})
}
options.Route = &option.RouteOptions{
Rules: routeRules,
Final: OutboundMainProxyTag,
AutoDetectInterface: true,
OverrideAndroidVPN: true,
RuleSet: rulesets,
// GeoIP: &option.GeoIPOptions{
// Path: opt.GeoIPPath,
// },
// Geosite: &option.GeositeOptions{
// Path: opt.GeoSitePath,
// },
}
if opt.EnableDNSRouting {
for _, dnsRule := range dnsRules {
if dnsRule.IsValid() {
options.DNS.Rules = append(
options.DNS.Rules,
option.DNSRule{
Type: C.RuleTypeDefault,
DefaultOptions: dnsRule,
},
)
}
}
}
}
func patchHiddifyWarpFromConfig(out option.Outbound, opt HiddifyOptions) option.Outbound {
if opt.Warp.EnableWarp && opt.Warp.Mode == "proxy_over_warp" {
if out.DirectOptions.Detour == "" {
out.DirectOptions.Detour = "Hiddify Warp ✅"
}
if out.HTTPOptions.Detour == "" {
out.HTTPOptions.Detour = "Hiddify Warp ✅"
}
if out.Hysteria2Options.Detour == "" {
out.Hysteria2Options.Detour = "Hiddify Warp ✅"
}
if out.HysteriaOptions.Detour == "" {
out.HysteriaOptions.Detour = "Hiddify Warp ✅"
}
if out.SSHOptions.Detour == "" {
out.SSHOptions.Detour = "Hiddify Warp ✅"
}
if out.ShadowTLSOptions.Detour == "" {
out.ShadowTLSOptions.Detour = "Hiddify Warp ✅"
}
if out.ShadowsocksOptions.Detour == "" {
out.ShadowsocksOptions.Detour = "Hiddify Warp ✅"
}
if out.ShadowsocksROptions.Detour == "" {
out.ShadowsocksROptions.Detour = "Hiddify Warp ✅"
}
if out.SocksOptions.Detour == "" {
out.SocksOptions.Detour = "Hiddify Warp ✅"
}
if out.TUICOptions.Detour == "" {
out.TUICOptions.Detour = "Hiddify Warp ✅"
}
if out.TorOptions.Detour == "" {
out.TorOptions.Detour = "Hiddify Warp ✅"
}
if out.TrojanOptions.Detour == "" {
out.TrojanOptions.Detour = "Hiddify Warp ✅"
}
if out.VLESSOptions.Detour == "" {
out.VLESSOptions.Detour = "Hiddify Warp ✅"
}
if out.VMessOptions.Detour == "" {
out.VMessOptions.Detour = "Hiddify Warp ✅"
}
if out.WireGuardOptions.Detour == "" {
out.WireGuardOptions.Detour = "Hiddify Warp ✅"
}
}
return out
}
func getIPs(domains []string) []string {
res := []string{}
for _, d := range domains {
ips, err := net.LookupHost(d)
if err != nil {
continue
}
for _, ip := range ips {
if !strings.HasPrefix(ip, "10.") {
res = append(res, ip)
}
}
}
return res
}
func isBlockedDomain(domain string) bool {
if strings.HasPrefix("full:", domain) {
return false
}
ips, err := net.LookupHost(domain)
if err != nil {
// fmt.Println(err)
return true
}
// Print the IP addresses associated with the domain
fmt.Printf("IP addresses for %s:\n", domain)
for _, ip := range ips {
if strings.HasPrefix(ip, "10.") {
return true
}
}
return false
}
func removeDuplicateStr(strSlice []string) []string {
allKeys := make(map[string]bool)
list := []string{}
for _, item := range strSlice {
if _, value := allKeys[item]; !value {
allKeys[item] = true
list = append(list, item)
}
}
return list
}
func generateRandomString(length int) string {
// Determine the number of bytes needed
bytesNeeded := (length*6 + 7) / 8
// Generate random bytes
randomBytes := make([]byte, bytesNeeded)
_, err := rand.Read(randomBytes)
if err != nil {
return "hiddify"
}
// Encode random bytes to base64
randomString := base64.URLEncoding.EncodeToString(randomBytes)
// Trim padding characters and return the string
return randomString[:length]
}

View File

@ -1,8 +0,0 @@
{
"log": {},
"dns": {},
"inbounds": [],
"outbounds": [],
"route": {},
"experimental": {}
}

View File

@ -1,6 +0,0 @@
package config
const (
WarpOverProxy = "warp_over_proxy"
ProxyOverWarp = "proxy_over_warp"
)

View File

@ -1,389 +0,0 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.33.0
// protoc v4.25.3
// source: core.proto
package config
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ParseConfigRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
TempPath string `protobuf:"bytes,1,opt,name=tempPath,proto3" json:"tempPath,omitempty"`
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
Debug bool `protobuf:"varint,3,opt,name=debug,proto3" json:"debug,omitempty"`
}
func (x *ParseConfigRequest) Reset() {
*x = ParseConfigRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_core_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ParseConfigRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ParseConfigRequest) ProtoMessage() {}
func (x *ParseConfigRequest) ProtoReflect() protoreflect.Message {
mi := &file_core_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ParseConfigRequest.ProtoReflect.Descriptor instead.
func (*ParseConfigRequest) Descriptor() ([]byte, []int) {
return file_core_proto_rawDescGZIP(), []int{0}
}
func (x *ParseConfigRequest) GetTempPath() string {
if x != nil {
return x.TempPath
}
return ""
}
func (x *ParseConfigRequest) GetPath() string {
if x != nil {
return x.Path
}
return ""
}
func (x *ParseConfigRequest) GetDebug() bool {
if x != nil {
return x.Debug
}
return false
}
type ParseConfigResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Error *string `protobuf:"bytes,1,opt,name=error,proto3,oneof" json:"error,omitempty"`
}
func (x *ParseConfigResponse) Reset() {
*x = ParseConfigResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_core_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ParseConfigResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ParseConfigResponse) ProtoMessage() {}
func (x *ParseConfigResponse) ProtoReflect() protoreflect.Message {
mi := &file_core_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ParseConfigResponse.ProtoReflect.Descriptor instead.
func (*ParseConfigResponse) Descriptor() ([]byte, []int) {
return file_core_proto_rawDescGZIP(), []int{1}
}
func (x *ParseConfigResponse) GetError() string {
if x != nil && x.Error != nil {
return *x.Error
}
return ""
}
type GenerateConfigRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
Debug bool `protobuf:"varint,2,opt,name=debug,proto3" json:"debug,omitempty"`
}
func (x *GenerateConfigRequest) Reset() {
*x = GenerateConfigRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_core_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GenerateConfigRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GenerateConfigRequest) ProtoMessage() {}
func (x *GenerateConfigRequest) ProtoReflect() protoreflect.Message {
mi := &file_core_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GenerateConfigRequest.ProtoReflect.Descriptor instead.
func (*GenerateConfigRequest) Descriptor() ([]byte, []int) {
return file_core_proto_rawDescGZIP(), []int{2}
}
func (x *GenerateConfigRequest) GetPath() string {
if x != nil {
return x.Path
}
return ""
}
func (x *GenerateConfigRequest) GetDebug() bool {
if x != nil {
return x.Debug
}
return false
}
type GenerateConfigResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Config string `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"`
Error *string `protobuf:"bytes,2,opt,name=error,proto3,oneof" json:"error,omitempty"`
}
func (x *GenerateConfigResponse) Reset() {
*x = GenerateConfigResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_core_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GenerateConfigResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GenerateConfigResponse) ProtoMessage() {}
func (x *GenerateConfigResponse) ProtoReflect() protoreflect.Message {
mi := &file_core_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GenerateConfigResponse.ProtoReflect.Descriptor instead.
func (*GenerateConfigResponse) Descriptor() ([]byte, []int) {
return file_core_proto_rawDescGZIP(), []int{3}
}
func (x *GenerateConfigResponse) GetConfig() string {
if x != nil {
return x.Config
}
return ""
}
func (x *GenerateConfigResponse) GetError() string {
if x != nil && x.Error != nil {
return *x.Error
}
return ""
}
var File_core_proto protoreflect.FileDescriptor
var file_core_proto_rawDesc = []byte{
0x0a, 0x0a, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x43, 0x6f,
0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x5a, 0x0a, 0x12, 0x50,
0x61, 0x72, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x12, 0x1a, 0x0a, 0x08, 0x74, 0x65, 0x6d, 0x70, 0x50, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20,
0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x65, 0x6d, 0x70, 0x50, 0x61, 0x74, 0x68, 0x12, 0x12, 0x0a,
0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74,
0x68, 0x12, 0x14, 0x0a, 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08,
0x52, 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x22, 0x3a, 0x0a, 0x13, 0x50, 0x61, 0x72, 0x73, 0x65,
0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x19,
0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52,
0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x88, 0x01, 0x01, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x65, 0x72,
0x72, 0x6f, 0x72, 0x22, 0x41, 0x0a, 0x15, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x43,
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04,
0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68,
0x12, 0x14, 0x0a, 0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52,
0x05, 0x64, 0x65, 0x62, 0x75, 0x67, 0x22, 0x55, 0x0a, 0x16, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61,
0x74, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65,
0x12, 0x16, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x19, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f,
0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72,
0x88, 0x01, 0x01, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x32, 0xc6, 0x01,
0x0a, 0x0b, 0x43, 0x6f, 0x72, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x54, 0x0a,
0x0b, 0x50, 0x61, 0x72, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x21, 0x2e, 0x43,
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x50, 0x61, 0x72,
0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a,
0x22, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e,
0x50, 0x61, 0x72, 0x73, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f,
0x6e, 0x73, 0x65, 0x12, 0x61, 0x0a, 0x12, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x46,
0x75, 0x6c, 0x6c, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x24, 0x2e, 0x43, 0x6f, 0x6e, 0x66,
0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61,
0x74, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a,
0x25, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e,
0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x0b, 0x5a, 0x09, 0x2e, 0x2e, 0x2f, 0x63, 0x6f, 0x6e,
0x66, 0x69, 0x67, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_core_proto_rawDescOnce sync.Once
file_core_proto_rawDescData = file_core_proto_rawDesc
)
func file_core_proto_rawDescGZIP() []byte {
file_core_proto_rawDescOnce.Do(func() {
file_core_proto_rawDescData = protoimpl.X.CompressGZIP(file_core_proto_rawDescData)
})
return file_core_proto_rawDescData
}
var file_core_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_core_proto_goTypes = []interface{}{
(*ParseConfigRequest)(nil), // 0: HiddifyOptions.ParseConfigRequest
(*ParseConfigResponse)(nil), // 1: HiddifyOptions.ParseConfigResponse
(*GenerateConfigRequest)(nil), // 2: HiddifyOptions.GenerateConfigRequest
(*GenerateConfigResponse)(nil), // 3: HiddifyOptions.GenerateConfigResponse
}
var file_core_proto_depIdxs = []int32{
0, // 0: HiddifyOptions.CoreService.ParseConfig:input_type -> HiddifyOptions.ParseConfigRequest
2, // 1: HiddifyOptions.CoreService.GenerateFullConfig:input_type -> HiddifyOptions.GenerateConfigRequest
1, // 2: HiddifyOptions.CoreService.ParseConfig:output_type -> HiddifyOptions.ParseConfigResponse
3, // 3: HiddifyOptions.CoreService.GenerateFullConfig:output_type -> HiddifyOptions.GenerateConfigResponse
2, // [2:4] is the sub-list for method output_type
0, // [0:2] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_core_proto_init() }
func file_core_proto_init() {
if File_core_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_core_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ParseConfigRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_core_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ParseConfigResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_core_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GenerateConfigRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_core_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GenerateConfigResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
file_core_proto_msgTypes[1].OneofWrappers = []interface{}{}
file_core_proto_msgTypes[3].OneofWrappers = []interface{}{}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_core_proto_rawDesc,
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_core_proto_goTypes,
DependencyIndexes: file_core_proto_depIdxs,
MessageInfos: file_core_proto_msgTypes,
}.Build()
File_core_proto = out.File
file_core_proto_rawDesc = nil
file_core_proto_goTypes = nil
file_core_proto_depIdxs = nil
}

View File

@ -1,146 +0,0 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.3.0
// - protoc v4.25.3
// source: core.proto
package config
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
const (
CoreService_ParseConfig_FullMethodName = "/HiddifyOptions.CoreService/ParseConfig"
CoreService_GenerateFullConfig_FullMethodName = "/HiddifyOptions.CoreService/GenerateFullConfig"
)
// CoreServiceClient is the client API for CoreService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type CoreServiceClient interface {
ParseConfig(ctx context.Context, in *ParseConfigRequest, opts ...grpc.CallOption) (*ParseConfigResponse, error)
GenerateFullConfig(ctx context.Context, in *GenerateConfigRequest, opts ...grpc.CallOption) (*GenerateConfigResponse, error)
}
type coreServiceClient struct {
cc grpc.ClientConnInterface
}
func NewCoreServiceClient(cc grpc.ClientConnInterface) CoreServiceClient {
return &coreServiceClient{cc}
}
func (c *coreServiceClient) ParseConfig(ctx context.Context, in *ParseConfigRequest, opts ...grpc.CallOption) (*ParseConfigResponse, error) {
out := new(ParseConfigResponse)
err := c.cc.Invoke(ctx, CoreService_ParseConfig_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *coreServiceClient) GenerateFullConfig(ctx context.Context, in *GenerateConfigRequest, opts ...grpc.CallOption) (*GenerateConfigResponse, error) {
out := new(GenerateConfigResponse)
err := c.cc.Invoke(ctx, CoreService_GenerateFullConfig_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// CoreServiceServer is the server API for CoreService service.
// All implementations must embed UnimplementedCoreServiceServer
// for forward compatibility
type CoreServiceServer interface {
ParseConfig(context.Context, *ParseConfigRequest) (*ParseConfigResponse, error)
GenerateFullConfig(context.Context, *GenerateConfigRequest) (*GenerateConfigResponse, error)
mustEmbedUnimplementedCoreServiceServer()
}
// UnimplementedCoreServiceServer must be embedded to have forward compatible implementations.
type UnimplementedCoreServiceServer struct {
}
func (UnimplementedCoreServiceServer) ParseConfig(context.Context, *ParseConfigRequest) (*ParseConfigResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ParseConfig not implemented")
}
func (UnimplementedCoreServiceServer) GenerateFullConfig(context.Context, *GenerateConfigRequest) (*GenerateConfigResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GenerateFullConfig not implemented")
}
func (UnimplementedCoreServiceServer) mustEmbedUnimplementedCoreServiceServer() {}
// UnsafeCoreServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to CoreServiceServer will
// result in compilation errors.
type UnsafeCoreServiceServer interface {
mustEmbedUnimplementedCoreServiceServer()
}
func RegisterCoreServiceServer(s grpc.ServiceRegistrar, srv CoreServiceServer) {
s.RegisterService(&CoreService_ServiceDesc, srv)
}
func _CoreService_ParseConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ParseConfigRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CoreServiceServer).ParseConfig(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: CoreService_ParseConfig_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CoreServiceServer).ParseConfig(ctx, req.(*ParseConfigRequest))
}
return interceptor(ctx, in, info, handler)
}
func _CoreService_GenerateFullConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GenerateConfigRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CoreServiceServer).GenerateFullConfig(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: CoreService_GenerateFullConfig_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CoreServiceServer).GenerateFullConfig(ctx, req.(*GenerateConfigRequest))
}
return interceptor(ctx, in, info, handler)
}
// CoreService_ServiceDesc is the grpc.ServiceDesc for CoreService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var CoreService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "HiddifyOptions.CoreService",
HandlerType: (*CoreServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ParseConfig",
Handler: _CoreService_ParseConfig_Handler,
},
{
MethodName: "GenerateFullConfig",
Handler: _CoreService_GenerateFullConfig_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "core.proto",
}

View File

@ -1,45 +0,0 @@
package config
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime/debug"
"github.com/sagernet/sing-box/option"
)
func SaveCurrentConfig(path string, options option.Options) error {
json, err := ToJson(options)
if err != nil {
return err
}
p, err := filepath.Abs(path)
fmt.Printf("Saving config to %v %+v\n", p, err)
if err != nil {
return err
}
return os.WriteFile(p, []byte(json), 0644)
}
func ToJson(options option.Options) (string, error) {
var buffer bytes.Buffer
encoder := json.NewEncoder(&buffer)
encoder.SetIndent("", " ")
// fmt.Printf("%+v\n", options)
err := encoder.Encode(options)
if err != nil {
fmt.Printf("ERROR in coding:%+v\n", err)
return "", err
}
return buffer.String(), nil
}
func DeferPanicToError(name string, err func(error)) {
if r := recover(); r != nil {
s := fmt.Errorf("%s panic: %s\n%s", name, r, string(debug.Stack()))
err(s)
}
}

View File

@ -1,155 +0,0 @@
package config
import (
"github.com/sagernet/sing-box/option"
dns "github.com/sagernet/sing-dns"
)
type HiddifyOptions struct {
EnableFullConfig bool `json:"enable-full-config"`
LogLevel string `json:"log-level"`
LogFile string `json:"log-file"`
EnableClashApi bool `json:"enable-clash-api"`
ClashApiPort uint16 `json:"clash-api-port"`
ClashApiSecret string `json:"web-secret"`
Region string `json:"region"`
BlockAds bool `json:"block-ads"`
UseXrayCoreWhenPossible bool `json:"use-xray-core-when-possible"`
// GeoIPPath string `json:"geoip-path"`
// GeoSitePath string `json:"geosite-path"`
Rules []Rule `json:"rules"`
Warp WarpOptions `json:"warp"`
Warp2 WarpOptions `json:"warp2"`
Mux MuxOptions `json:"mux"`
TLSTricks TLSTricks `json:"tls-tricks"`
DNSOptions
InboundOptions
URLTestOptions
RouteOptions
}
type DNSOptions struct {
RemoteDnsAddress string `json:"remote-dns-address"`
RemoteDnsDomainStrategy option.DomainStrategy `json:"remote-dns-domain-strategy"`
DirectDnsAddress string `json:"direct-dns-address"`
DirectDnsDomainStrategy option.DomainStrategy `json:"direct-dns-domain-strategy"`
IndependentDNSCache bool `json:"independent-dns-cache"`
EnableFakeDNS bool `json:"enable-fake-dns"`
EnableDNSRouting bool `json:"enable-dns-routing"`
}
type InboundOptions struct {
EnableTun bool `json:"enable-tun"`
EnableTunService bool `json:"enable-tun-service"`
SetSystemProxy bool `json:"set-system-proxy"`
MixedPort uint16 `json:"mixed-port"`
TProxyPort uint16 `json:"tproxy-port"`
LocalDnsPort uint16 `json:"local-dns-port"`
MTU uint32 `json:"mtu"`
StrictRoute bool `json:"strict-route"`
TUNStack string `json:"tun-implementation"`
}
type URLTestOptions struct {
ConnectionTestUrl string `json:"connection-test-url"`
URLTestInterval DurationInSeconds `json:"url-test-interval"`
// URLTestIdleTimeout DurationInSeconds `json:"url-test-idle-timeout"`
}
type RouteOptions struct {
ResolveDestination bool `json:"resolve-destination"`
IPv6Mode option.DomainStrategy `json:"ipv6-mode"`
BypassLAN bool `json:"bypass-lan"`
AllowConnectionFromLAN bool `json:"allow-connection-from-lan"`
}
type TLSTricks struct {
EnableFragment bool `json:"enable-fragment"`
FragmentSize string `json:"fragment-size"`
FragmentSleep string `json:"fragment-sleep"`
MixedSNICase bool `json:"mixed-sni-case"`
EnablePadding bool `json:"enable-padding"`
PaddingSize string `json:"padding-size"`
}
type MuxOptions struct {
Enable bool `json:"enable"`
Padding bool `json:"padding"`
MaxStreams int `json:"max-streams"`
Protocol string `json:"protocol"`
}
type WarpOptions struct {
Id string `json:"id"`
EnableWarp bool `json:"enable"`
Mode string `json:"mode"`
WireguardConfigStr string `json:"wireguard-config"`
WireguardConfig WarpWireguardConfig `json:"wireguardConfig"` // TODO check
FakePackets string `json:"noise"`
FakePacketSize string `json:"noise-size"`
FakePacketDelay string `json:"noise-delay"`
FakePacketMode string `json:"noise-mode"`
CleanIP string `json:"clean-ip"`
CleanPort uint16 `json:"clean-port"`
Account WarpAccount
}
func DefaultHiddifyOptions() *HiddifyOptions {
return &HiddifyOptions{
DNSOptions: DNSOptions{
RemoteDnsAddress: "1.1.1.1",
RemoteDnsDomainStrategy: option.DomainStrategy(dns.DomainStrategyAsIS),
DirectDnsAddress: "1.1.1.1",
DirectDnsDomainStrategy: option.DomainStrategy(dns.DomainStrategyAsIS),
IndependentDNSCache: false,
EnableFakeDNS: false,
EnableDNSRouting: false,
},
InboundOptions: InboundOptions{
EnableTun: false,
SetSystemProxy: false,
MixedPort: 12334,
TProxyPort: 12335,
LocalDnsPort: 16450,
MTU: 9000,
StrictRoute: true,
TUNStack: "mixed",
},
URLTestOptions: URLTestOptions{
ConnectionTestUrl: "http://cp.cloudflare.com/",
URLTestInterval: DurationInSeconds(600),
// URLTestIdleTimeout: DurationInSeconds(6000),
},
RouteOptions: RouteOptions{
ResolveDestination: false,
IPv6Mode: option.DomainStrategy(dns.DomainStrategyAsIS),
BypassLAN: false,
AllowConnectionFromLAN: false,
},
LogLevel: "warn",
// LogFile: "/dev/null",
LogFile: "box.log",
Region: "other",
EnableClashApi: true,
ClashApiPort: 16756,
ClashApiSecret: "",
// GeoIPPath: "geoip.db",
// GeoSitePath: "geosite.db",
Rules: []Rule{},
Mux: MuxOptions{
Enable: false,
Padding: true,
MaxStreams: 8,
Protocol: "h2mux",
},
TLSTricks: TLSTricks{
EnableFragment: false,
FragmentSize: "10-100",
FragmentSleep: "50-200",
MixedSNICase: false,
EnablePadding: false,
PaddingSize: "1200-1500",
},
UseXrayCoreWhenPossible: false,
}
}

View File

@ -1,185 +0,0 @@
package config
import (
"encoding/json"
"fmt"
"net"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/option"
)
type outboundMap map[string]interface{}
func patchOutboundMux(base option.Outbound, configOpt HiddifyOptions, obj outboundMap) outboundMap {
if configOpt.Mux.Enable {
multiplex := option.OutboundMultiplexOptions{
Enabled: true,
Padding: configOpt.Mux.Padding,
MaxStreams: configOpt.Mux.MaxStreams,
Protocol: configOpt.Mux.Protocol,
}
obj["multiplex"] = multiplex
// } else {
// delete(obj, "multiplex")
}
return obj
}
func patchOutboundTLSTricks(base option.Outbound, configOpt HiddifyOptions, obj outboundMap) outboundMap {
if base.Type == C.TypeSelector || base.Type == C.TypeURLTest || base.Type == C.TypeBlock || base.Type == C.TypeDNS {
return obj
}
if isOutboundReality(base) {
return obj
}
var tls *option.OutboundTLSOptions
var transport *option.V2RayTransportOptions
if base.VLESSOptions.OutboundTLSOptionsContainer.TLS != nil {
tls = base.VLESSOptions.OutboundTLSOptionsContainer.TLS
transport = base.VLESSOptions.Transport
} else if base.TrojanOptions.OutboundTLSOptionsContainer.TLS != nil {
tls = base.TrojanOptions.OutboundTLSOptionsContainer.TLS
transport = base.TrojanOptions.Transport
} else if base.VMessOptions.OutboundTLSOptionsContainer.TLS != nil {
tls = base.VMessOptions.OutboundTLSOptionsContainer.TLS
transport = base.VMessOptions.Transport
}
if base.Type == C.TypeXray {
if configOpt.TLSTricks.EnableFragment {
if obj["xray_fragment"] == nil || obj["xray_fragment"].(map[string]any)["packets"] == "" {
obj["xray_fragment"] = map[string]any{
"packets": "tlshello",
"length": configOpt.TLSTricks.FragmentSize,
"interval": configOpt.TLSTricks.FragmentSleep,
}
}
}
}
if base.Type == C.TypeDirect {
return patchOutboundFragment(base, configOpt, obj)
}
if tls == nil || !tls.Enabled || transport == nil {
return obj
}
if transport.Type != C.V2RayTransportTypeWebsocket && transport.Type != C.V2RayTransportTypeGRPC && transport.Type != C.V2RayTransportTypeHTTPUpgrade {
return obj
}
if outtls, ok := obj["tls"].(map[string]interface{}); ok {
obj = patchOutboundFragment(base, configOpt, obj)
tlsTricks := tls.TLSTricks
if tlsTricks == nil {
tlsTricks = &option.TLSTricksOptions{}
}
tlsTricks.MixedCaseSNI = tlsTricks.MixedCaseSNI || configOpt.TLSTricks.MixedSNICase
if configOpt.TLSTricks.EnablePadding {
tlsTricks.PaddingMode = "random"
tlsTricks.PaddingSize = configOpt.TLSTricks.PaddingSize
// fmt.Printf("--------------------%+v----%+v", tlsTricks.PaddingSize, configOpt)
outtls["utls"] = map[string]interface{}{
"enabled": true,
"fingerprint": "custom",
}
}
outtls["tls_tricks"] = tlsTricks
// if tlsTricks.MixedCaseSNI || tlsTricks.PaddingMode != "" {
// // } else {
// // tls["tls_tricks"] = nil
// }
// fmt.Printf("-------%+v------------- ", tlsTricks)
}
return obj
}
func patchOutboundFragment(base option.Outbound, configOpt HiddifyOptions, obj outboundMap) outboundMap {
if configOpt.TLSTricks.EnableFragment {
obj["tcp_fast_open"] = false
obj["tls_fragment"] = option.TLSFragmentOptions{
Enabled: configOpt.TLSTricks.EnableFragment,
Size: configOpt.TLSTricks.FragmentSize,
Sleep: configOpt.TLSTricks.FragmentSleep,
}
}
return obj
}
func isOutboundReality(base option.Outbound) bool {
// this function checks reality status ONLY FOR VLESS.
// Some other protocols can also use reality, but it's discouraged as stated in the reality document
if base.Type != C.TypeVLESS {
return false
}
if base.VLESSOptions.OutboundTLSOptionsContainer.TLS == nil {
return false
}
if base.VLESSOptions.OutboundTLSOptionsContainer.TLS.Reality == nil {
return false
}
return base.VLESSOptions.OutboundTLSOptionsContainer.TLS.Reality.Enabled
}
func patchOutbound(base option.Outbound, configOpt HiddifyOptions, staticIpsDns map[string][]string) (*option.Outbound, string, error) {
formatErr := func(err error) error {
return fmt.Errorf("error patching outbound[%s][%s]: %w", base.Tag, base.Type, err)
}
err := patchWarp(&base, &configOpt, true, staticIpsDns)
if err != nil {
return nil, "", formatErr(err)
}
var outbound option.Outbound
jsonData, err := base.MarshalJSON()
if err != nil {
return nil, "", formatErr(err)
}
var obj outboundMap
err = json.Unmarshal(jsonData, &obj)
if err != nil {
return nil, "", formatErr(err)
}
var serverDomain string
if detour, ok := obj["detour"].(string); !ok || detour == "" {
if server, ok := obj["server"].(string); ok {
if server != "" && net.ParseIP(server) == nil {
serverDomain = fmt.Sprintf("full:%s", server)
}
}
}
obj = patchOutboundTLSTricks(base, configOpt, obj)
switch base.Type {
case C.TypeVMess, C.TypeVLESS, C.TypeTrojan, C.TypeShadowsocks:
obj = patchOutboundMux(base, configOpt, obj)
}
modifiedJson, err := json.Marshal(obj)
if err != nil {
return nil, "", formatErr(err)
}
err = outbound.UnmarshalJSON(modifiedJson)
if err != nil {
return nil, "", formatErr(err)
}
return &outbound, serverDomain, nil
}
// func (o outboundMap) transportType() string {
// if transport, ok := o["transport"].(map[string]interface{}); ok {
// if transportType, ok := transport["type"].(string); ok {
// return transportType
// }
// }
// return ""
// }

View File

@ -1,142 +0,0 @@
package config
import (
"bytes"
"context"
_ "embed"
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/hiddify/ray2sing/ray2sing"
"github.com/sagernet/sing-box/experimental/libbox"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common/batch"
SJ "github.com/sagernet/sing/common/json"
"github.com/xmdhs/clash2singbox/convert"
"github.com/xmdhs/clash2singbox/model/clash"
"gopkg.in/yaml.v3"
)
//go:embed config.json.template
var configByte []byte
func ParseConfig(path string, debug bool) ([]byte, error) {
content, err := os.ReadFile(path)
os.Chdir(filepath.Dir(path))
if err != nil {
return nil, err
}
return ParseConfigContent(string(content), debug, nil, false)
}
func ParseConfigContentToOptions(contentstr string, debug bool, configOpt *HiddifyOptions, fullConfig bool) (*option.Options, error) {
content, err := ParseConfigContent(contentstr, debug, configOpt, fullConfig)
if err != nil {
return nil, err
}
var options option.Options
err = json.Unmarshal(content, &options)
if err != nil {
return nil, err
}
return &options, nil
}
func ParseConfigContent(contentstr string, debug bool, configOpt *HiddifyOptions, fullConfig bool) ([]byte, error) {
if configOpt == nil {
configOpt = DefaultHiddifyOptions()
}
content := []byte(contentstr)
var jsonObj map[string]interface{} = make(map[string]interface{})
fmt.Printf("Convert using json\n")
var tmpJsonResult any
jsonDecoder := json.NewDecoder(SJ.NewCommentFilter(bytes.NewReader(content)))
if err := jsonDecoder.Decode(&tmpJsonResult); err == nil {
if tmpJsonObj, ok := tmpJsonResult.(map[string]interface{}); ok {
if tmpJsonObj["outbounds"] == nil {
jsonObj["outbounds"] = []interface{}{jsonObj}
} else {
if fullConfig || (configOpt != nil && configOpt.EnableFullConfig) {
jsonObj = tmpJsonObj
} else {
jsonObj["outbounds"] = tmpJsonObj["outbounds"]
}
}
} else if jsonArray, ok := tmpJsonResult.([]map[string]interface{}); ok {
jsonObj["outbounds"] = jsonArray
} else {
return nil, fmt.Errorf("[SingboxParser] Incorrect Json Format")
}
newContent, _ := json.MarshalIndent(jsonObj, "", " ")
return patchConfig(newContent, "SingboxParser", configOpt)
}
v2rayStr, err := ray2sing.Ray2Singbox(string(content), configOpt.UseXrayCoreWhenPossible)
if err == nil {
return patchConfig([]byte(v2rayStr), "V2rayParser", configOpt)
}
fmt.Printf("Convert using clash\n")
clashObj := clash.Clash{}
if err := yaml.Unmarshal(content, &clashObj); err == nil && clashObj.Proxies != nil {
if len(clashObj.Proxies) == 0 {
return nil, fmt.Errorf("[ClashParser] no outbounds found")
}
converted, err := convert.Clash2sing(clashObj)
if err != nil {
return nil, fmt.Errorf("[ClashParser] converting clash to sing-box error: %w", err)
}
output := configByte
output, err = convert.Patch(output, converted, "", "", nil)
if err != nil {
return nil, fmt.Errorf("[ClashParser] patching clash config error: %w", err)
}
return patchConfig(output, "ClashParser", configOpt)
}
return nil, fmt.Errorf("unable to determine config format")
}
func patchConfig(content []byte, name string, configOpt *HiddifyOptions) ([]byte, error) {
options := option.Options{}
err := json.Unmarshal(content, &options)
if err != nil {
return nil, fmt.Errorf("[SingboxParser] unmarshal error: %w", err)
}
b, _ := batch.New(context.Background(), batch.WithConcurrencyNum[*option.Outbound](2))
for _, base := range options.Outbounds {
out := base
b.Go(base.Tag, func() (*option.Outbound, error) {
err := patchWarp(&out, configOpt, false, nil)
if err != nil {
return nil, fmt.Errorf("[Warp] patch warp error: %w", err)
}
// options.Outbounds[i] = base
return &out, nil
})
}
if res, err := b.WaitAndGetResult(); err != nil {
return nil, err
} else {
for i, base := range options.Outbounds {
options.Outbounds[i] = *res[base.Tag].Value
}
}
content, _ = json.MarshalIndent(options, "", " ")
fmt.Printf("%s\n", content)
return validateResult(content, name)
}
func validateResult(content []byte, name string) ([]byte, error) {
err := libbox.CheckConfig(string(content))
if err != nil {
return nil, fmt.Errorf("[%s] invalid sing-box config: %w", name, err)
}
return content, nil
}

View File

@ -1,96 +0,0 @@
package config
import (
"strconv"
"strings"
"github.com/sagernet/sing-box/option"
)
type Rule struct {
RuleSetUrl string `json:"rule-set-url"`
Domains string `json:"domains"`
IP string `json:"ip"`
Port string `json:"port"`
Network string `json:"network"`
Protocol string `json:"protocol"`
Outbound string `json:"outbound"`
}
func (r *Rule) MakeRule() option.DefaultRule {
rule := option.DefaultRule{}
if len(r.Domains) > 0 {
rule = makeDomainRule(rule, strings.Split(r.Domains, ","))
}
if len(r.IP) > 0 {
rule = makeIpRule(rule, strings.Split(r.IP, ","))
}
if len(r.Port) > 0 {
rule = makePortRule(rule, strings.Split(r.Port, ","))
}
if len(r.Network) > 0 {
rule.Network = append(rule.Network, r.Network)
}
if len(r.Protocol) > 0 {
rule.Protocol = append(rule.Protocol, strings.Split(r.Protocol, ",")...)
}
return rule
}
func (r *Rule) MakeDNSRule() option.DefaultDNSRule {
rule := option.DefaultDNSRule{}
domains := strings.Split(r.Domains, ",")
for _, item := range domains {
if strings.HasPrefix(item, "geosite:") {
rule.Geosite = append(rule.Geosite, strings.TrimPrefix(item, "geosite:"))
} else if strings.HasPrefix(item, "full:") {
rule.Domain = append(rule.Domain, strings.ToLower(strings.TrimPrefix(item, "full:")))
} else if strings.HasPrefix(item, "domain:") {
rule.DomainSuffix = append(rule.DomainSuffix, strings.ToLower(strings.TrimPrefix(item, "domain:")))
} else if strings.HasPrefix(item, "regexp:") {
rule.DomainRegex = append(rule.DomainRegex, strings.ToLower(strings.TrimPrefix(item, "regexp:")))
} else if strings.HasPrefix(item, "keyword:") {
rule.DomainKeyword = append(rule.DomainKeyword, strings.ToLower(strings.TrimPrefix(item, "keyword:")))
}
}
return rule
}
func makeDomainRule(options option.DefaultRule, list []string) option.DefaultRule {
for _, item := range list {
if strings.HasPrefix(item, "geosite:") {
options.Geosite = append(options.Geosite, strings.TrimPrefix(item, "geosite:"))
} else if strings.HasPrefix(item, "full:") {
options.Domain = append(options.Domain, strings.ToLower(strings.TrimPrefix(item, "full:")))
} else if strings.HasPrefix(item, "domain:") {
options.DomainSuffix = append(options.DomainSuffix, strings.ToLower(strings.TrimPrefix(item, "domain:")))
} else if strings.HasPrefix(item, "regexp:") {
options.DomainRegex = append(options.DomainRegex, strings.ToLower(strings.TrimPrefix(item, "regexp:")))
} else if strings.HasPrefix(item, "keyword:") {
options.DomainKeyword = append(options.DomainKeyword, strings.ToLower(strings.TrimPrefix(item, "keyword:")))
}
}
return options
}
func makeIpRule(options option.DefaultRule, list []string) option.DefaultRule {
for _, item := range list {
if strings.HasPrefix(item, "geoip:") {
options.GeoIP = append(options.GeoIP, strings.TrimPrefix(item, "geoip:"))
} else {
options.IPCIDR = append(options.IPCIDR, item)
}
}
return options
}
func makePortRule(options option.DefaultRule, list []string) option.DefaultRule {
for _, item := range list {
if strings.Contains(item, ":") {
options.PortRange = append(options.PortRange, item)
} else if i, err := strconv.Atoi(item); err == nil {
options.Port = append(options.Port, uint16(i))
}
}
return options
}

View File

@ -1,75 +0,0 @@
package config
import (
context "context"
"fmt"
"log"
"net"
"os"
"path/filepath"
"github.com/sagernet/sing-box/option"
"google.golang.org/grpc"
)
type server struct {
UnimplementedCoreServiceServer
}
func String(s string) *string {
return &s
}
func (s *server) ParseConfig(ctx context.Context, in *ParseConfigRequest) (*ParseConfigResponse, error) {
config, err := ParseConfig(in.TempPath, in.Debug)
if err != nil {
return &ParseConfigResponse{Error: String(err.Error())}, nil
}
err = os.WriteFile(in.Path, config, 0o644)
if err != nil {
return nil, err
}
return &ParseConfigResponse{Error: String("")}, nil
}
func (s *server) GenerateFullConfig(ctx context.Context, in *GenerateConfigRequest) (*GenerateConfigResponse, error) {
os.Chdir(filepath.Dir(in.Path))
content, err := os.ReadFile(in.Path)
if err != nil {
return nil, err
}
var options option.Options
err = options.UnmarshalJSON(content)
if err != nil {
return nil, err
}
if err != nil {
return nil, err
}
config, err := BuildConfigJson(*DefaultHiddifyOptions(), options)
if err != nil {
return nil, err
}
return &GenerateConfigResponse{
Config: config,
}, nil
}
func StartGRPCServer(port uint16) error {
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatalf("Failed to listen: %v", err)
}
s := grpc.NewServer()
RegisterCoreServiceServer(s, &server{})
log.Println("Server started on :", port)
go func() {
if err := s.Serve(lis); err != nil {
log.Fatalf("Failed to serve: %v", err)
}
}()
return nil
}

View File

@ -1,25 +0,0 @@
package config
import (
"encoding/json"
"time"
)
type DurationInSeconds int
func (d DurationInSeconds) MarshalJSON() ([]byte, error) {
return json.Marshal(int64(d))
}
func (d *DurationInSeconds) UnmarshalJSON(bytes []byte) error {
var v int64
if err := json.Unmarshal(bytes, &v); err != nil {
return err
}
*d = DurationInSeconds(v)
return nil
}
func (d DurationInSeconds) Duration() time.Duration {
return time.Duration(d) * time.Second
}

View File

@ -1,270 +0,0 @@
package config
import (
"encoding/base64"
"fmt"
"log/slog"
"net/netip"
"os"
"strings"
"github.com/bepass-org/warp-plus/warp"
"github.com/hiddify/hiddify-core/v2/common"
C "github.com/sagernet/sing-box/constant"
// "github.com/bepass-org/wireguard-go/warp"
"github.com/hiddify/hiddify-core/v2/db"
"github.com/sagernet/sing-box/option"
T "github.com/sagernet/sing-box/option"
)
type SingboxConfig struct {
Type string `json:"type"`
Tag string `json:"tag"`
Server string `json:"server"`
ServerPort int `json:"server_port"`
LocalAddress []string `json:"local_address"`
PrivateKey string `json:"private_key"`
PeerPublicKey string `json:"peer_public_key"`
Reserved []int `json:"reserved"`
MTU int `json:"mtu"`
}
func wireGuardToSingbox(wgConfig WarpWireguardConfig, server string, port uint16) (*T.Outbound, error) {
clientID, _ := base64.StdEncoding.DecodeString(wgConfig.ClientID)
if len(clientID) < 2 {
clientID = []byte{0, 0, 0}
}
out := T.Outbound{
Type: "wireguard",
Tag: "WARP",
WireGuardOptions: T.WireGuardOutboundOptions{
ServerOptions: T.ServerOptions{
Server: server,
ServerPort: port,
},
PrivateKey: wgConfig.PrivateKey,
PeerPublicKey: wgConfig.PeerPublicKey,
Reserved: []uint8{clientID[0], clientID[1], clientID[2]},
// Reserved: []uint8{0, 0, 0},
MTU: 1330,
},
}
ips := []string{wgConfig.LocalAddressIPv4 + "/24", wgConfig.LocalAddressIPv6 + "/128"}
for _, addr := range ips {
if addr == "" {
continue
}
prefix, err := netip.ParsePrefix(addr)
if err != nil {
return nil, err // Handle the error appropriately
}
out.WireGuardOptions.LocalAddress = append(out.WireGuardOptions.LocalAddress, prefix)
}
return &out, nil
}
func getRandomIP() string {
ipPort, err := warp.RandomWarpEndpoint(true, true)
if err == nil {
return ipPort.Addr().String()
}
return "engage.cloudflareclient.com"
}
func generateWarp(license string, host string, port uint16, fakePackets string, fakePacketsSize string, fakePacketsDelay string, fakePacketsMode string) (*T.Outbound, error) {
_, _, wgConfig, err := GenerateWarpInfo(license, "", "")
if err != nil {
return nil, err
}
if wgConfig == nil {
return nil, fmt.Errorf("invalid warp config")
}
return GenerateWarpSingbox(*wgConfig, host, port, fakePackets, fakePacketsSize, fakePacketsDelay, fakePacketsMode)
}
func GenerateWarpSingbox(wgConfig WarpWireguardConfig, host string, port uint16, fakePackets string, fakePacketsSize string, fakePacketsDelay string, fakePacketMode string) (*T.Outbound, error) {
if host == "" {
host = "auto4"
}
if (host == "auto" || host == "auto4" || host == "auto6") && fakePackets == "" {
fakePackets = "1-3"
}
if fakePackets != "" && fakePacketsSize == "" {
fakePacketsSize = "10-30"
}
if fakePackets != "" && fakePacketsDelay == "" {
fakePacketsDelay = "10-30"
}
singboxConfig, err := wireGuardToSingbox(wgConfig, host, port)
if err != nil {
fmt.Printf("%v %v", singboxConfig, err)
return nil, err
}
singboxConfig.WireGuardOptions.FakePackets = fakePackets
singboxConfig.WireGuardOptions.FakePacketsSize = fakePacketsSize
singboxConfig.WireGuardOptions.FakePacketsDelay = fakePacketsDelay
singboxConfig.WireGuardOptions.FakePacketsMode = fakePacketMode
return singboxConfig, nil
}
func GenerateWarpInfo(license string, oldAccountId string, oldAccessToken string) (*warp.Identity, string, *WarpWireguardConfig, error) {
if oldAccountId != "" && oldAccessToken != "" {
err := warp.DeleteDevice(oldAccessToken, oldAccountId)
if err != nil {
fmt.Printf("Error in removing old device: %v\n", err)
} else {
fmt.Printf("Old Device Removed")
}
}
l := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
identity, err := warp.CreateIdentityOnly(l, license)
res := "Error!"
var warpcfg WarpWireguardConfig
if err == nil {
res = "Success"
res = fmt.Sprintf("Warp+ enabled: %t\n", identity.Account.WarpPlus)
res += fmt.Sprintf("\nAccount type: %s\n", identity.Account.AccountType)
warpcfg = WarpWireguardConfig{
PrivateKey: identity.PrivateKey,
PeerPublicKey: identity.Config.Peers[0].PublicKey,
LocalAddressIPv4: identity.Config.Interface.Addresses.V4,
LocalAddressIPv6: identity.Config.Interface.Addresses.V6,
ClientID: identity.Config.ClientID,
}
}
return &identity, res, &warpcfg, err
}
func getOrGenerateWarpLocallyIfNeeded(warpOptions *WarpOptions) WarpWireguardConfig {
if warpOptions.WireguardConfig.PrivateKey != "" {
return warpOptions.WireguardConfig
}
table := db.GetTable[WarpOptions]()
dbWarpOptions, err := table.Get(warpOptions.Id)
if err == nil && dbWarpOptions.WireguardConfig.PrivateKey != "" {
return warpOptions.WireguardConfig
}
license := ""
if len(warpOptions.Id) == 26 { // warp key is 26 characters long
license = warpOptions.Id
} else if len(warpOptions.Id) > 28 && warpOptions.Id[2] == '_' { // warp key is 26 characters long
license = warpOptions.Id[3:]
}
accountidentity, _, wireguardConfig, err := GenerateWarpInfo(license, warpOptions.Account.AccountID, warpOptions.Account.AccessToken)
if err != nil {
return WarpWireguardConfig{}
}
warpOptions.Account = WarpAccount{
AccountID: accountidentity.ID,
AccessToken: accountidentity.Token,
}
warpOptions.WireguardConfig = *wireguardConfig
table.UpdateInsert(warpOptions)
return *wireguardConfig
}
func patchWarp(base *option.Outbound, configOpt *HiddifyOptions, final bool, staticIpsDns map[string][]string) error {
if base.Type == C.TypeCustom {
if warp, ok := base.CustomOptions["warp"].(map[string]interface{}); ok {
key, _ := warp["key"].(string)
host, _ := warp["host"].(string)
port, _ := warp["port"].(uint16)
detour, _ := warp["detour"].(string)
fakePackets, _ := warp["fake_packets"].(string)
fakePacketsSize, _ := warp["fake_packets_size"].(string)
fakePacketsDelay, _ := warp["fake_packets_delay"].(string)
fakePacketsMode, _ := warp["fake_packets_mode"].(string)
var warpOutbound *T.Outbound
var err error
is_saved_key := len(key) > 1 && key[0] == 'p'
if (configOpt == nil || !final) && is_saved_key {
return nil
}
var wireguardConfig WarpWireguardConfig
if is_saved_key {
var warpOpt *WarpOptions
if key == "p1" {
warpOpt = &configOpt.Warp
} else if key == "p2" {
warpOpt = &configOpt.Warp2
} else {
warpOpt = &WarpOptions{
Id: key,
}
}
warpOpt.Id = key
wireguardConfig = getOrGenerateWarpLocallyIfNeeded(warpOpt)
} else {
_, _, wgConfig, err := GenerateWarpInfo(key, "", "")
if err != nil {
return err
}
wireguardConfig = *wgConfig
}
warpOutbound, err = GenerateWarpSingbox(wireguardConfig, host, port, fakePackets, fakePacketsSize, fakePacketsDelay, fakePacketsMode)
if err != nil {
fmt.Printf("Error generating warp config: %v", err)
return err
}
warpOutbound.WireGuardOptions.Detour = detour
base.Type = C.TypeWireGuard
base.WireGuardOptions = warpOutbound.WireGuardOptions
}
}
if final && base.Type == C.TypeWireGuard {
host := base.WireGuardOptions.Server
if host == "default" || host == "random" || host == "auto" || host == "auto4" || host == "auto6" || isBlockedDomain(host) {
// if base.WireGuardOptions.Detour != "" {
// base.WireGuardOptions.Server = "162.159.192.1"
// } else {
rndDomain := strings.ToLower(generateRandomString(20))
staticIpsDns[rndDomain] = []string{}
if host != "auto4" {
if host == "auto6" || common.CanConnectIPv6() {
randomIpPort, _ := warp.RandomWarpEndpoint(false, true)
staticIpsDns[rndDomain] = append(staticIpsDns[rndDomain], randomIpPort.Addr().String())
}
}
if host != "auto6" {
randomIpPort, _ := warp.RandomWarpEndpoint(true, false)
staticIpsDns[rndDomain] = append(staticIpsDns[rndDomain], randomIpPort.Addr().String())
}
base.WireGuardOptions.Server = rndDomain
// }
}
if base.WireGuardOptions.ServerPort == 0 {
port := warp.RandomWarpPort()
base.WireGuardOptions.ServerPort = port
}
if base.WireGuardOptions.Detour != "" {
if base.WireGuardOptions.MTU < 100 {
base.WireGuardOptions.MTU = 1280
}
base.WireGuardOptions.FakePackets = ""
base.WireGuardOptions.FakePacketsDelay = ""
base.WireGuardOptions.FakePacketsSize = ""
}
// if base.WireGuardOptions.Detour == "" {
// base.WireGuardOptions.GSO = runtime.GOOS != "windows"
// }
}
return nil
}

View File

@ -1,50 +0,0 @@
package config
import (
"encoding/json"
)
type WarpAccount struct {
AccountID string `json:"account-id"`
AccessToken string `json:"access-token"`
}
type WarpWireguardConfig struct {
PrivateKey string `json:"private-key"`
LocalAddressIPv4 string `json:"local-address-ipv4"`
LocalAddressIPv6 string `json:"local-address-ipv6"`
PeerPublicKey string `json:"peer-public-key"`
ClientID string `json:"client-id"`
}
type WarpGenerationResponse struct {
WarpAccount
Log string `json:"log"`
Config WarpWireguardConfig `json:"config"`
}
func GenerateWarpAccount(licenseKey string, accountId string, accessToken string) (string, error) {
identity, log, wg, err := GenerateWarpInfo(licenseKey, accountId, accessToken)
if err != nil {
return "", err
}
warpAccount := WarpAccount{
AccountID: identity.ID,
AccessToken: identity.Token,
}
warpConfig := WarpWireguardConfig{
PrivateKey: wg.PrivateKey,
LocalAddressIPv4: wg.LocalAddressIPv4,
LocalAddressIPv6: wg.LocalAddressIPv6,
PeerPublicKey: wg.PeerPublicKey,
ClientID: wg.ClientID,
}
response := WarpGenerationResponse{warpAccount, log, warpConfig}
responseJson, err := json.Marshal(response)
if err != nil {
return "", err
}
return string(responseJson), nil
}

View File

@ -1,26 +0,0 @@
package main
/*
#include <stdlib.h>
*/
import "C"
import (
"unsafe"
"github.com/hiddify/hiddify-core/cmd"
)
//export parseCli
func parseCli(argc C.int, argv **C.char) *C.char {
args := make([]string, argc)
for i := 0; i < int(argc); i++ {
// fmt.Println("parseCli", C.GoString(*argv))
args[i] = C.GoString(*argv)
argv = (**C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(argv)) + uintptr(unsafe.Sizeof(*argv))))
}
err := cmd.ParseCli(args[1:])
if err != nil {
return C.CString(err.Error())
}
return C.CString("")
}

View File

@ -1,169 +0,0 @@
package main
/*
#include "stdint.h"
*/
import "C"
import (
"encoding/json"
"fmt"
"os"
"unsafe"
"github.com/hiddify/hiddify-core/bridge"
"github.com/hiddify/hiddify-core/config"
pb "github.com/hiddify/hiddify-core/hiddifyrpc"
v2 "github.com/hiddify/hiddify-core/v2"
"github.com/sagernet/sing-box/log"
)
//export setupOnce
func setupOnce(api unsafe.Pointer) {
bridge.InitializeDartApi(api)
}
//export setup
func setup(baseDir *C.char, workingDir *C.char, tempDir *C.char, statusPort C.longlong, debug bool) (CErr *C.char) {
err := v2.Setup(C.GoString(baseDir), C.GoString(workingDir), C.GoString(tempDir), int64(statusPort), debug)
return emptyOrErrorC(err)
}
//export parse
func parse(path *C.char, tempPath *C.char, debug bool) (CErr *C.char) {
res, err := v2.Parse(&pb.ParseRequest{
ConfigPath: C.GoString(path),
TempPath: C.GoString(tempPath),
})
if err != nil {
log.Error(err.Error())
return C.CString(err.Error())
}
err = os.WriteFile(C.GoString(path), []byte(res.Content), 0o644)
return emptyOrErrorC(err)
}
//export changeHiddifyOptions
func changeHiddifyOptions(HiddifyOptionsJson *C.char) (CErr *C.char) {
_, err := v2.ChangeHiddifySettings(&pb.ChangeHiddifySettingsRequest{
HiddifySettingsJson: C.GoString(HiddifyOptionsJson),
})
return emptyOrErrorC(err)
}
//export generateConfig
func generateConfig(path *C.char) (res *C.char) {
conf, err := v2.GenerateConfig(&pb.GenerateConfigRequest{
Path: C.GoString(path),
})
if err != nil {
return emptyOrErrorC(err)
}
fmt.Printf("Config: %+v\n", conf)
fmt.Printf("ConfigContent: %+v\n", conf.ConfigContent)
return C.CString(conf.ConfigContent)
}
//export start
func start(configPath *C.char, disableMemoryLimit bool) (CErr *C.char) {
_, err := v2.Start(&pb.StartRequest{
ConfigPath: C.GoString(configPath),
EnableOldCommandServer: true,
DisableMemoryLimit: disableMemoryLimit,
})
return emptyOrErrorC(err)
}
//export stop
func stop() (CErr *C.char) {
_, err := v2.Stop()
return emptyOrErrorC(err)
}
//export restart
func restart(configPath *C.char, disableMemoryLimit bool) (CErr *C.char) {
_, err := v2.Restart(&pb.StartRequest{
ConfigPath: C.GoString(configPath),
EnableOldCommandServer: true,
DisableMemoryLimit: disableMemoryLimit,
})
return emptyOrErrorC(err)
}
//export startCommandClient
func startCommandClient(command C.int, port C.longlong) *C.char {
err := v2.StartCommand(int32(command), int64(port))
return emptyOrErrorC(err)
}
//export stopCommandClient
func stopCommandClient(command C.int) *C.char {
err := v2.StopCommand(int32(command))
return emptyOrErrorC(err)
}
//export selectOutbound
func selectOutbound(groupTag *C.char, outboundTag *C.char) (CErr *C.char) {
_, err := v2.SelectOutbound(&pb.SelectOutboundRequest{
GroupTag: C.GoString(groupTag),
OutboundTag: C.GoString(outboundTag),
})
return emptyOrErrorC(err)
}
//export urlTest
func urlTest(groupTag *C.char) (CErr *C.char) {
_, err := v2.UrlTest(&pb.UrlTestRequest{
GroupTag: C.GoString(groupTag),
})
return emptyOrErrorC(err)
}
func emptyOrErrorC(err error) *C.char {
if err == nil {
return C.CString("")
}
log.Error(err.Error())
return C.CString(err.Error())
}
//export generateWarpConfig
func generateWarpConfig(licenseKey *C.char, accountId *C.char, accessToken *C.char) (CResp *C.char) {
res, err := v2.GenerateWarpConfig(&pb.GenerateWarpConfigRequest{
LicenseKey: C.GoString(licenseKey),
AccountId: C.GoString(accountId),
AccessToken: C.GoString(accessToken),
})
if err != nil {
return C.CString(fmt.Sprint("error: ", err.Error()))
}
warpAccount := config.WarpAccount{
AccountID: res.Account.AccountId,
AccessToken: res.Account.AccessToken,
}
warpConfig := config.WarpWireguardConfig{
PrivateKey: res.Config.PrivateKey,
LocalAddressIPv4: res.Config.LocalAddressIpv4,
LocalAddressIPv6: res.Config.LocalAddressIpv6,
PeerPublicKey: res.Config.PeerPublicKey,
ClientID: res.Config.ClientId,
}
log := res.Log
response := &config.WarpGenerationResponse{
WarpAccount: warpAccount,
Log: log,
Config: warpConfig,
}
responseJson, err := json.Marshal(response)
if err != nil {
return C.CString("")
}
return C.CString(string(responseJson))
}
func main() {}

View File

@ -1,10 +0,0 @@
package main
import "C"
import v2 "github.com/hiddify/hiddify-core/v2"
//export StartCoreGrpcServer
func StartCoreGrpcServer(listenAddress *C.char) (CErr *C.char) {
_, err := v2.StartCoreGrpcServer(C.GoString(listenAddress))
return emptyOrErrorC(err)
}

View File

@ -1,72 +0,0 @@
#!/bin/bash
set -e
echo "安装构建依赖..."
apt-get update -qq
apt-get install -y -qq wget unzip openjdk-17-jdk build-essential npm
echo "创建Android SDK目录结构..."
mkdir -p /opt/android-sdk/cmdline-tools
echo "下载Android SDK命令行工具..."
cd /tmp
wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
unzip -q commandlinetools-linux-11076708_latest.zip
mv cmdline-tools /opt/android-sdk/cmdline-tools/latest
export ANDROID_HOME=/opt/android-sdk
export PATH=$PATH:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools
echo "接受Android SDK许可..."
yes | sdkmanager --licenses > /dev/null 2>&1 || true
echo "安装Android SDK Platform 21和Build Tools..."
sdkmanager "platforms;android-21" "build-tools;30.0.3" "platform-tools"
echo "安装Android NDK..."
cd /tmp
wget -q https://dl.google.com/android/repository/android-ndk-r26c-linux.zip
unzip -q android-ndk-r26c-linux.zip
export ANDROID_NDK_HOME=/tmp/android-ndk-r26c
echo "安装gomobile..."
go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.1.1
go install -v github.com/sagernet/gomobile/cmd/gobind@v0.1.1
export PATH=$PATH:/root/go/bin
echo "安装npm依赖..."
npm install --silent
echo "初始化gomobile..."
gomobile init -ndk $ANDROID_NDK_HOME
cd /workspace
echo "开始使用gomobile编译..."
gomobile bind -v \
-androidapi=21 \
-javapkg=io.nekohasekai \
-libname=box \
-tags="with_gvisor,with_quic,with_wireguard,with_ech,with_utls,with_clash_api,with_grpc" \
-trimpath \
-target=android/arm64 \
-o libcore.aar \
github.com/sagernet/sing-box/experimental/libbox ./mobile
if [ ! -f libcore.aar ]; then
echo "❌ 编译失败: libcore.aar未生成"
exit 1
fi
echo "提取libbox.so..."
unzip -j libcore.aar jni/arm64-v8a/libbox.so -d /tmp/
if [ -f /tmp/libbox.so ]; then
cp /tmp/libbox.so /workspace/libbox-new.so
echo "✅ 编译成功!"
ls -lh /workspace/libbox-new.so
md5sum /workspace/libbox-new.so
else
echo "❌ 提取失败: libbox.so未找到"
exit 1
fi

View File

@ -1,30 +0,0 @@
FROM alpine:latest
ENV CONFIG='https://raw.githubusercontent.com/ircfspace/warpsub/main/export/warp#WARP%20(IRCF)'
ENV VERSION=v3.1.7
WORKDIR /hiddify
RUN apk add curl tar gzip libc6-compat # iptables ip6tables
RUN echo "architecture: $(apk --print-arch)" && \
case "$(apk --print-arch)" in \
x86_64) ARCH=amd64 ;; \
i386|x86) ARCH=386 ;; \
aarch64) ARCH=arm64 ;; \
armv7) ARCH=armv7 ;; \
armv6|armhf) ARCH=armv6 ;; \
armv5) ARCH=armv5 ;; \
s390x) ARCH=s390x ;; \
*) echo "Unsupported architecture: $(apk --print-arch) $(uname -m)" && exit 1 ;; \
esac && \
echo "Downloading https://github.com/hiddify/hiddify-core/releases/download/${VERSION}/hiddify-cli-linux-$ARCH.tar.gz" && \
curl -L -o hiddify-cli.tar.gz https://github.com/hiddify/hiddify-core/releases/download/${VERSION}/hiddify-cli-linux-$ARCH.tar.gz && \
tar -xzf hiddify-cli.tar.gz && rm hiddify-cli.tar.gz
COPY hiddify.sh .
RUN chmod +x hiddify.sh
EXPOSE 12334
EXPOSE 12335
EXPOSE 16756
EXPOSE 16450
ENTRYPOINT [ "/hiddify/hiddify.sh" ]

View File

@ -1,11 +0,0 @@
version: '3.8'
services:
hiddify:
image: ghcr.io/hiddify/hiddify-core:latest
network_mode: host
environment:
CONFIG: "https://github.com/hiddify/hiddify-next/raw/refs/heads/main/test.configs/warp"
volumes:
- ./hiddify.json:/hiddify/hiddify.json
command: ["/opt/hiddify.sh"]

View File

@ -1,42 +0,0 @@
{
"region":"other",
"service-mode": "proxy",
"log-level": "info",
"resolve-destination": true,
"ipv6-mode": "prefer_ipv4",
"remote-dns-address": "tcp://1.1.1.1",
"remote-dns-domain-strategy": "",
"direct-dns-address": "1.1.1.1",
"direct-dns-domain-strategy": "",
"mixed-port": 12334,
"local-dns-port": 16450,
"tun-implementation": "mixed",
"mtu": 9000,
"strict-route": false,
"connection-test-url": "https://www.gstatic.com/generate_204",
"url-test-interval": 600,
"enable-clash-api": true,
"clash-api-port": 16756,
"bypass-lan": false,
"allow-connection-from-lan": true,
"enable-fake-dns": false,
"enable-dns-routing": true,
"independent-dns-cache": true,
"enable-tls-fragment": false,
"tls-fragment-size": "20-70",
"tls-fragment-sleep": "10-30",
"enable-tls-mixed-sni-case": false,
"enable-tls-padding": false,
"tls-padding-size": "15-30",
"enable-mux": false,
"mux-padding": false,
"mux-max-streams": 4,
"mux-protocol": "h2mux",
"enable-warp": false,
"warp-detour-mode": "outbound",
"warp-license-key": "",
"warp-clean-ip": "auto",
"warp-port": 0,
"warp-noise": "5-10",
"warp-noise-delay": "20-200"
}

View File

@ -1,40 +0,0 @@
#!/bin/sh
# sysctl -w net.ipv4.ip_forward=1
# sysctl -w net.ipv6.ip_forward=1
# ip rule add fwmark 1 table 100 ;
# ip route add local 0.0.0.0/0 dev lo table 100
# # CREATE TABLE
# iptables -t mangle -N hiddify
# # RETURN LOCAL AND LANS
# iptables -t mangle -A OUTPUT -j RETURN
# iptables -t nat -A hiddify --dport 2334 -j RETURN
# iptables -t mangle -A hiddify -d 10.0.0.0/8 -j RETURN
# iptables -t mangle -A hiddify -d 127.0.0.0/8 -j RETURN
# iptables -t mangle -A hiddify -d 169.254.0.0/16 -j RETURN
# iptables -t mangle -A hiddify -d 172.16.0.0/12 -j RETURN
# iptables -t mangle -A hiddify -d 192.168.50.0/16 -j RETURN
# iptables -t mangle -A hiddify -d 192.168.9.0/16 -j RETURN
# iptables -t mangle -A hiddify -d 224.0.0.0/4 -j RETURN
# iptables -t mangle -A hiddify -d 240.0.0.0/4 -j RETURN
# iptables -t mangle -A hiddify -p udp -j TPROXY --on-port 2334 --tproxy-mark 1
# iptables -t mangle -A hiddify -p tcp -j TPROXY --on-port 2334 --tproxy-mark 1
# # HIJACK ICMP (untested)
# # iptables -t mangle -A hiddify -p icmp -j DNAT --to-destination 127.0.0.1
# # REDIRECT
# iptables -t mangle -A PREROUTING -j hiddify
if [ -f "/hiddify/hiddify.json" ]; then
/hiddify/HiddifyCli run --config "$CONFIG" -d /hiddify/hiddify.json
else
/hiddify/HiddifyCli run --config "$CONFIG"
fi

View File

@ -1,143 +0,0 @@
package extension
import (
"encoding/json"
"github.com/hiddify/hiddify-core/config"
"github.com/hiddify/hiddify-core/extension/ui"
pb "github.com/hiddify/hiddify-core/hiddifyrpc"
"github.com/hiddify/hiddify-core/v2/db"
"github.com/jellydator/validation"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
)
type Extension interface {
GetUI() ui.Form
SubmitData(button string, data map[string]string) error
Close() error
UpdateUI(form ui.Form) error
BeforeAppConnect(hiddifySettings *config.HiddifyOptions, singconfig *option.Options) error
StoreData()
init(id string)
getQueue() chan *pb.ExtensionResponse
getId() string
}
type Base[T any] struct {
id string
// responseStream grpc.ServerStreamingServer[pb.ExtensionResponse]
queue chan *pb.ExtensionResponse
Data T
}
// func (b *Base) mustEmbdedBaseExtension() {
// }
func (b *Base[T]) BeforeAppConnect(hiddifySettings *config.HiddifyOptions, singconfig *option.Options) error {
return nil
}
func (b *Base[T]) StoreData() {
table := db.GetTable[extensionData]()
ed, err := table.Get(b.id)
if err != nil {
log.Warn("error: ", err)
return
}
res, err := json.Marshal(b.Data)
if err != nil {
log.Warn("error: ", err)
return
}
ed.JsonData = (res)
table.UpdateInsert(ed)
}
func (b *Base[T]) init(id string) {
b.id = id
b.queue = make(chan *pb.ExtensionResponse, 1)
table := db.GetTable[extensionData]()
extdata, err := table.Get(b.id)
if err != nil {
log.Warn("error: ", err)
return
}
if extdata == nil {
log.Warn("extension data not found ", id)
return
}
if extdata.JsonData != nil {
var t T
if err := json.Unmarshal(extdata.JsonData, &t); err != nil {
log.Warn("error loading data of ", id, " : ", err)
} else {
b.Data = t
}
}
}
func (b *Base[T]) getQueue() chan *pb.ExtensionResponse {
return b.queue
}
func (b *Base[T]) getId() string {
return b.id
}
func (e *Base[T]) ShowMessage(title string, msg string) error {
return e.ShowDialog(ui.Form{
Title: title,
Description: msg,
Fields: [][]ui.FormField{
{{
Type: ui.FieldButton,
Key: ui.ButtonDialogOk,
Label: "Ok",
}},
},
// Buttons: []string{ui.Button_Ok},
})
}
func (p *Base[T]) UpdateUI(form ui.Form) error {
p.queue <- &pb.ExtensionResponse{
ExtensionId: p.id,
Type: pb.ExtensionResponseType_UPDATE_UI,
JsonUi: form.ToJSON(),
}
return nil
}
func (p *Base[T]) ShowDialog(form ui.Form) error {
p.queue <- &pb.ExtensionResponse{
ExtensionId: p.id,
Type: pb.ExtensionResponseType_SHOW_DIALOG,
JsonUi: form.ToJSON(),
}
// log.Printf("Updated UI for extension %s: %s", err, p.id)
return nil
}
func (base *Base[T]) ValName(fieldPtr interface{}) string {
val, err := validation.ErrorFieldName(&base.Data, fieldPtr)
if err != nil {
log.Warn(err)
return ""
}
if val == "" {
log.Warn("Field not found")
return ""
}
return val
}
type ExtensionFactory struct {
Id string
Title string
Description string
Builder func() Extension
}

View File

@ -1,146 +0,0 @@
package extension
import (
"context"
"fmt"
"log"
pb "github.com/hiddify/hiddify-core/hiddifyrpc"
"github.com/hiddify/hiddify-core/v2/db"
"google.golang.org/grpc"
)
type ExtensionHostService struct {
pb.UnimplementedExtensionHostServiceServer
}
func (ExtensionHostService) ListExtensions(ctx context.Context, empty *pb.Empty) (*pb.ExtensionList, error) {
extensionList := &pb.ExtensionList{
Extensions: make([]*pb.Extension, 0),
}
allext, err := db.GetTable[extensionData]().All()
if err != nil {
return nil, err
}
for _, dbext := range allext {
if ext, ok := allExtensionsMap[dbext.Id]; ok {
extensionList.Extensions = append(extensionList.Extensions, &pb.Extension{
Id: ext.Id,
Title: ext.Title,
Description: ext.Description,
Enable: dbext.Enable,
})
}
}
return extensionList, nil
}
func getExtension(id string) (*Extension, error) {
if !isEnable(id) {
return nil, fmt.Errorf("Extension with ID %s is not enabled", id)
}
if extension, ok := enabledExtensionsMap[id]; ok {
return extension, nil
}
return nil, fmt.Errorf("Extension with ID %s not found", id)
}
func (e ExtensionHostService) Connect(req *pb.ExtensionRequest, stream grpc.ServerStreamingServer[pb.ExtensionResponse]) error {
extension, err := getExtension(req.GetExtensionId())
if err != nil {
log.Printf("Error connecting stream for extension %s: %v", req.GetExtensionId(), err)
return err
}
log.Printf("Connecting stream for extension %s", req.GetExtensionId())
log.Printf("Extension data: %+v", extension)
if err := (*extension).UpdateUI((*extension).GetUI()); err != nil {
log.Printf("Error updating UI for extension %s: %v", req.GetExtensionId(), err)
}
for {
select {
case <-stream.Context().Done():
return nil
case info := <-(*extension).getQueue():
stream.Send(info)
if info.GetType() == pb.ExtensionResponseType_END {
return nil
}
}
}
}
func (e ExtensionHostService) SubmitForm(ctx context.Context, req *pb.SendExtensionDataRequest) (*pb.ExtensionActionResult, error) {
extension, err := getExtension(req.GetExtensionId())
if err != nil {
log.Println(err)
return &pb.ExtensionActionResult{
ExtensionId: req.ExtensionId,
Code: pb.ResponseCode_FAILED,
Message: err.Error(),
}, err
}
(*extension).SubmitData(req.Button, req.GetData())
return &pb.ExtensionActionResult{
ExtensionId: req.ExtensionId,
Code: pb.ResponseCode_OK,
Message: "Success",
}, nil
}
func (e ExtensionHostService) Close(ctx context.Context, req *pb.ExtensionRequest) (*pb.ExtensionActionResult, error) {
extension, err := getExtension(req.GetExtensionId())
if err != nil {
log.Println(err)
return &pb.ExtensionActionResult{
ExtensionId: req.ExtensionId,
Code: pb.ResponseCode_FAILED,
Message: err.Error(),
}, err
}
(*extension).Close()
(*extension).StoreData()
return &pb.ExtensionActionResult{
ExtensionId: req.ExtensionId,
Code: pb.ResponseCode_OK,
Message: "Success",
}, nil
}
func (e ExtensionHostService) EditExtension(ctx context.Context, req *pb.EditExtensionRequest) (*pb.ExtensionActionResult, error) {
if !req.Enable {
extension, _ := getExtension(req.GetExtensionId())
if extension != nil {
(*extension).Close()
(*extension).StoreData()
}
delete(enabledExtensionsMap, req.GetExtensionId())
}
table := db.GetTable[extensionData]()
data, err := table.Get(req.GetExtensionId())
if err != nil {
return nil, err
}
data.Enable = req.Enable
table.UpdateInsert(data)
if req.Enable {
loadExtension(allExtensionsMap[req.GetExtensionId()])
}
return &pb.ExtensionActionResult{
ExtensionId: req.ExtensionId,
Code: pb.ResponseCode_OK,
Message: "Success",
}, nil
}
type extensionData struct {
Id string `json:"id"`
Enable bool `json:"enable"`
JsonData []byte
}

View File

@ -1,12 +0,0 @@
import * as a from "./rpc/extension_grpc_web_pb.js";
const client = new ExtensionHostServiceClient('http://localhost:8080');
const request = new GetHelloRequest();
export const getHello = (name) => {
request.setName(name)
client.getHello(request, {}, (err, response) => {
console.log(request.getName());
console.log(response.toObject());
});
}
getHello("D")

View File

@ -1,82 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hiddify Extensions</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" integrity="sha512-jnSuA4Ss2PkkikSOLtYs8BlYIeeIK1h99ty4YfvRPAlzr377vr3CXDb7sb7eEEBYjDtcYj+AjBH3FLv5uSJuXg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
pre {
background-color: black !important; overflow: auto;
color: white!important; }
</style>
</head>
<body>
<div class="container mt-5">
<div id="connection-page" class="card p-4">
<div id="connection-before-connect" class="card-body">
<h2 class="card-title mb-4">Connection Settings</h2>
<div class="mb-3">
<label for="config-content" class="form-label">Config String</label>
<textarea id="config-content" class="form-control" placeholder="Enter config string here..." rows="3"></textarea>
</div>
<div class="mb-3">
<label for="hiddify-settings" class="form-label">Hiddify Settings</label>
<textarea id="hiddify-settings" class="form-control" placeholder="Enter Hiddify settings here..." rows="3"></textarea>
</div>
<div class="d-flex justify-content-between">
<button id="connect-button" class="btn btn-success">Connect</button>
</div>
</div>
<div id="connection-connecting" class="card-body d-none">
<h2 id="connection-status" class="card-title mb-4">Connecting...</h2>
<button id="disconnect-button" class="btn btn-danger">Disconnect</button>
</div>
</div>
<div id="extension-list-container" class="card p-4">
<h1 class="mb-4">
Extension List
</h1>
<div id="extension-list" class="list-group">
</div>
</div>
<div id="extension-page-container" class="card p-4">
<div id="extension-page"></div>
</div>
</div>
<div class="modal fade" id="extension-dialog" style="display: none;" tabindex="-1" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Extension List</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div id="extension-page-containerdialog"></div>
</div>
<div class="modal-footer" id="modal-footer">
</div>
</div>
</div>
</div>
<script src="https://unpkg.com/ansi_up@5.0.0/ansi_up.js"></script>
<script src="https://cdn.jsdelivr.net/npm/protobufjs@7.X.X/dist/protobuf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js" integrity="sha512-7Pi/otdlbbCR+LnW+F7PwFcSDJOuUJB3OxtEHbg4vSMvzvJjde4Po1v4BR9Gdc9aXNUNFVUY+SK51wWT8WF0Gg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="rpc.js?1"></script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@ -1,460 +0,0 @@
// source: base.proto
/**
* @fileoverview
* @enhanceable
* @suppress {missingRequire} reports error on implicit type usages.
* @suppress {messageConventions} JS Compiler reports an error if a variable or
* field starts with 'MSG_' and isn't a translatable message.
* @public
*/
// GENERATED CODE -- DO NOT EDIT!
/* eslint-disable */
// @ts-nocheck
var jspb = require('google-protobuf');
var goog = jspb;
var global =
(typeof globalThis !== 'undefined' && globalThis) ||
(typeof window !== 'undefined' && window) ||
(typeof global !== 'undefined' && global) ||
(typeof self !== 'undefined' && self) ||
(function () { return this; }).call(null) ||
Function('return this')();
goog.exportSymbol('proto.hiddifyrpc.Empty', null, global);
goog.exportSymbol('proto.hiddifyrpc.HelloRequest', null, global);
goog.exportSymbol('proto.hiddifyrpc.HelloResponse', null, global);
goog.exportSymbol('proto.hiddifyrpc.ResponseCode', null, global);
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.hiddifyrpc.HelloRequest = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.hiddifyrpc.HelloRequest, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.hiddifyrpc.HelloRequest.displayName = 'proto.hiddifyrpc.HelloRequest';
}
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.hiddifyrpc.HelloResponse = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.hiddifyrpc.HelloResponse, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.hiddifyrpc.HelloResponse.displayName = 'proto.hiddifyrpc.HelloResponse';
}
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.hiddifyrpc.Empty = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.hiddifyrpc.Empty, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.hiddifyrpc.Empty.displayName = 'proto.hiddifyrpc.Empty';
}
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.hiddifyrpc.HelloRequest.prototype.toObject = function(opt_includeInstance) {
return proto.hiddifyrpc.HelloRequest.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.hiddifyrpc.HelloRequest} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.hiddifyrpc.HelloRequest.toObject = function(includeInstance, msg) {
var f, obj = {
name: jspb.Message.getFieldWithDefault(msg, 1, "")
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.hiddifyrpc.HelloRequest}
*/
proto.hiddifyrpc.HelloRequest.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.hiddifyrpc.HelloRequest;
return proto.hiddifyrpc.HelloRequest.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.hiddifyrpc.HelloRequest} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.hiddifyrpc.HelloRequest}
*/
proto.hiddifyrpc.HelloRequest.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = /** @type {string} */ (reader.readString());
msg.setName(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.hiddifyrpc.HelloRequest.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.hiddifyrpc.HelloRequest.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.hiddifyrpc.HelloRequest} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.hiddifyrpc.HelloRequest.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getName();
if (f.length > 0) {
writer.writeString(
1,
f
);
}
};
/**
* optional string name = 1;
* @return {string}
*/
proto.hiddifyrpc.HelloRequest.prototype.getName = function() {
return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, ""));
};
/**
* @param {string} value
* @return {!proto.hiddifyrpc.HelloRequest} returns this
*/
proto.hiddifyrpc.HelloRequest.prototype.setName = function(value) {
return jspb.Message.setProto3StringField(this, 1, value);
};
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.hiddifyrpc.HelloResponse.prototype.toObject = function(opt_includeInstance) {
return proto.hiddifyrpc.HelloResponse.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.hiddifyrpc.HelloResponse} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.hiddifyrpc.HelloResponse.toObject = function(includeInstance, msg) {
var f, obj = {
message: jspb.Message.getFieldWithDefault(msg, 1, "")
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.hiddifyrpc.HelloResponse}
*/
proto.hiddifyrpc.HelloResponse.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.hiddifyrpc.HelloResponse;
return proto.hiddifyrpc.HelloResponse.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.hiddifyrpc.HelloResponse} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.hiddifyrpc.HelloResponse}
*/
proto.hiddifyrpc.HelloResponse.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = /** @type {string} */ (reader.readString());
msg.setMessage(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.hiddifyrpc.HelloResponse.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.hiddifyrpc.HelloResponse.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.hiddifyrpc.HelloResponse} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.hiddifyrpc.HelloResponse.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getMessage();
if (f.length > 0) {
writer.writeString(
1,
f
);
}
};
/**
* optional string message = 1;
* @return {string}
*/
proto.hiddifyrpc.HelloResponse.prototype.getMessage = function() {
return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, ""));
};
/**
* @param {string} value
* @return {!proto.hiddifyrpc.HelloResponse} returns this
*/
proto.hiddifyrpc.HelloResponse.prototype.setMessage = function(value) {
return jspb.Message.setProto3StringField(this, 1, value);
};
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.hiddifyrpc.Empty.prototype.toObject = function(opt_includeInstance) {
return proto.hiddifyrpc.Empty.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.hiddifyrpc.Empty} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.hiddifyrpc.Empty.toObject = function(includeInstance, msg) {
var f, obj = {
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.hiddifyrpc.Empty}
*/
proto.hiddifyrpc.Empty.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.hiddifyrpc.Empty;
return proto.hiddifyrpc.Empty.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.hiddifyrpc.Empty} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.hiddifyrpc.Empty}
*/
proto.hiddifyrpc.Empty.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.hiddifyrpc.Empty.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.hiddifyrpc.Empty.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.hiddifyrpc.Empty} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.hiddifyrpc.Empty.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
};
/**
* @enum {number}
*/
proto.hiddifyrpc.ResponseCode = {
OK: 0,
FAILED: 1
};
goog.object.extend(exports, proto.hiddifyrpc);

View File

@ -1,8 +0,0 @@
const hiddify = require("./hiddify_grpc_web_pb.js");
const extension = require("./extension_grpc_web_pb.js");
const grpcServerAddress = '/';
const extensionClient = new extension.ExtensionHostServicePromiseClient(grpcServerAddress, null, null);
const hiddifyClient = new hiddify.CorePromiseClient(grpcServerAddress, null, null);
module.exports = { extensionClient ,hiddifyClient};

View File

@ -1,109 +0,0 @@
const { hiddifyClient } = require('./client.js');
const hiddify = require("./hiddify_grpc_web_pb.js");
function openConnectionPage() {
$("#extension-list-container").show();
$("#extension-page-container").hide();
$("#connection-page").show();
connect();
$("#connect-button").click(async () => {
const hsetting_request = new hiddify.ChangeHiddifySettingsRequest();
hsetting_request.setHiddifySettingsJson($("#hiddify-settings").val());
try{
const hres=await hiddifyClient.changeHiddifySettings(hsetting_request, {});
}catch(err){
$("#hiddify-settings").val("")
console.log(err)
}
const parse_request = new hiddify.ParseRequest();
parse_request.setContent($("#config-content").val());
try{
const pres=await hiddifyClient.parse(parse_request, {});
if (pres.getResponseCode() !== hiddify.ResponseCode.OK){
alert(pres.getMessage());
return
}
$("#config-content").val(pres.getContent());
}catch(err){
console.log(err)
alert(JSON.stringify(err))
return
}
const request = new hiddify.StartRequest();
request.setConfigContent($("#config-content").val());
request.setEnableRawConfig(false);
try{
const res=await hiddifyClient.start(request, {});
console.log(res.getCoreState(),res.getMessage())
handleCoreStatus(res.getCoreState());
}catch(err){
console.log(err)
alert(JSON.stringify(err))
return
}
})
$("#disconnect-button").click(async () => {
const request = new hiddify.Empty();
try{
const res=await hiddifyClient.stop(request, {});
console.log(res.getCoreState(),res.getMessage())
handleCoreStatus(res.getCoreState());
}catch(err){
console.log(err)
alert(JSON.stringify(err))
return
}
})
}
function connect(){
const request = new hiddify.Empty();
const stream = hiddifyClient.coreInfoListener(request, {});
stream.on('data', (response) => {
console.log('Receving ',response);
handleCoreStatus(response);
});
stream.on('error', (err) => {
console.error('Error opening extension page:', err);
// openExtensionPage(extensionId);
});
stream.on('end', () => {
console.log('Stream ended');
setTimeout(connect, 1000);
});
}
function handleCoreStatus(status){
if (status == hiddify.CoreState.STOPPED){
$("#connection-before-connect").show();
$("#connection-connecting").hide();
}else{
$("#connection-before-connect").hide();
$("#connection-connecting").show();
if (status == hiddify.CoreState.STARTING){
$("#connection-status").text("Starting");
$("#connection-status").css("color", "yellow");
}else if (status == hiddify.CoreState.STOPPING){
$("#connection-status").text("Stopping");
$("#connection-status").css("color", "red");
}else if (status == hiddify.CoreState.STARTED){
$("#connection-status").text("Connected");
$("#connection-status").css("color", "green");
}
}
}
module.exports = { openConnectionPage };

View File

@ -1,8 +0,0 @@
const { listExtensions } = require('./extensionList.js');
const { openConnectionPage } = require('./connectionPage.js');
window.onload = () => {
listExtensions();
openConnectionPage();
};

View File

@ -1,90 +0,0 @@
const { extensionClient } = require('./client.js');
const extension = require("./extension_grpc_web_pb.js");
async function listExtensions() {
$("#extension-list-container").show();
$("#extension-page-container").hide();
$("#connection-page").show();
try {
const extensionListContainer = document.getElementById('extension-list');
extensionListContainer.innerHTML = ''; // Clear previous entries
const response = await extensionClient.listExtensions(new extension.Empty(), {});
const extensionList = response.getExtensionsList();
extensionList.forEach(ext => {
const listItem = createExtensionListItem(ext);
extensionListContainer.appendChild(listItem);
});
} catch (err) {
console.error('Error listing extensions:', err);
}
}
function createExtensionListItem(ext) {
const listItem = document.createElement('li');
listItem.className = 'list-group-item d-flex justify-content-between align-items-center';
listItem.setAttribute('data-extension-id', ext.getId());
const contentDiv = document.createElement('div');
const titleElement = document.createElement('span');
titleElement.innerHTML = `<strong>${ext.getTitle()}</strong>`;
contentDiv.appendChild(titleElement);
const descriptionElement = document.createElement('p');
descriptionElement.className = 'mb-0';
descriptionElement.textContent = ext.getDescription();
contentDiv.appendChild(descriptionElement);
contentDiv.style.width="100%";
listItem.appendChild(contentDiv);
const switchDiv = createSwitchElement(ext);
listItem.appendChild(switchDiv);
const {openExtensionPage} = require('./extensionPage.js');
contentDiv.addEventListener('click', () =>{
if (!ext.getEnable() ){
alert("Extension is not enabled")
return
}
openExtensionPage(ext.getId())
});
return listItem;
}
function createSwitchElement(ext) {
const switchDiv = document.createElement('div');
switchDiv.className = 'form-check form-switch';
const switchButton = document.createElement('input');
switchButton.type = 'checkbox';
switchButton.className = 'form-check-input';
switchButton.checked = ext.getEnable();
switchButton.addEventListener('change', (e) => {
toggleExtension(ext.getId(), switchButton.checked)
});
switchDiv.appendChild(switchButton);
return switchDiv;
}
async function toggleExtension(extensionId, enable) {
const request = new extension.EditExtensionRequest();
request.setExtensionId(extensionId);
request.setEnable(enable);
try {
await extensionClient.editExtension(request, {});
console.log(`Extension ${extensionId} updated to ${enable ? 'enabled' : 'disabled'}`);
} catch (err) {
console.error('Error updating extension status:', err);
}
listExtensions();
}
module.exports = { listExtensions };

View File

@ -1,87 +0,0 @@
const { extensionClient } = require('./client.js');
const extension = require("./extension_grpc_web_pb.js");
const { renderForm } = require('./formRenderer.js');
const { listExtensions } = require('./extensionList.js');
var currentExtensionId = undefined;
function openExtensionPage(extensionId) {
currentExtensionId = extensionId;
$("#extension-list-container").hide();
$("#extension-page-container").show();
$("#connection-page").hide();
connect()
}
function connect() {
const request = new extension.ExtensionRequest();
request.setExtensionId(currentExtensionId);
const stream = extensionClient.connect(request, {});
stream.on('data', (response) => {
console.log('Receiving ', response);
if (response.getExtensionId() === currentExtensionId) {
ui = JSON.parse(response.getJsonUi())
if (response.getType() == proto.hiddifyrpc.ExtensionResponseType.SHOW_DIALOG) {
renderForm(ui, "dialog", handleSubmitButtonClick, undefined);
} else {
renderForm(ui, "", handleSubmitButtonClick, handleStopButtonClick);
}
}
});
stream.on('error', (err) => {
console.error('Error opening extension page:', err);
// openExtensionPage(extensionId);
});
stream.on('end', () => {
console.log('Stream ended');
setTimeout(connect, 1000);
});
}
async function handleSubmitButtonClick(event, button) {
event.preventDefault();
bootstrap.Modal.getOrCreateInstance("#extension-dialog").hide();
const request = new extension.SendExtensionDataRequest();
request.setButton(button);
if (event.type != 'hidden.bs.modal') {
const formData = new FormData(event.target.closest('form'));
const datamap = request.getDataMap()
formData.forEach((value, key) => {
datamap.set(key, value);
});
}
request.setExtensionId(currentExtensionId);
try {
await extensionClient.submitForm(request, {});
console.log('Form submitted successfully.');
} catch (err) {
console.error('Error submitting form:', err);
}
}
async function handleStopButtonClick(event) {
event.preventDefault();
const request = new extension.ExtensionRequest();
request.setExtensionId(currentExtensionId);
bootstrap.Modal.getOrCreateInstance("#extension-dialog").hide();
try {
await extensionClient.close(request, {});
console.log('Extension stopped successfully.');
currentExtensionId = undefined;
listExtensions(); // Return to the extension list
} catch (err) {
console.error('Error stopping extension:', err);
}
}
module.exports = { openExtensionPage };

View File

@ -1,441 +0,0 @@
/**
* @fileoverview gRPC-Web generated client stub for hiddifyrpc
* @enhanceable
* @public
*/
// Code generated by protoc-gen-grpc-web. DO NOT EDIT.
// versions:
// protoc-gen-grpc-web v1.5.0
// protoc v5.28.0
// source: extension.proto
/* eslint-disable */
// @ts-nocheck
const grpc = {};
grpc.web = require('grpc-web');
var base_pb = require('./base_pb.js')
const proto = {};
proto.hiddifyrpc = require('./extension_pb.js');
/**
* @param {string} hostname
* @param {?Object} credentials
* @param {?grpc.web.ClientOptions} options
* @constructor
* @struct
* @final
*/
proto.hiddifyrpc.ExtensionHostServiceClient =
function(hostname, credentials, options) {
if (!options) options = {};
options.format = 'text';
/**
* @private @const {!grpc.web.GrpcWebClientBase} The client
*/
this.client_ = new grpc.web.GrpcWebClientBase(options);
/**
* @private @const {string} The hostname
*/
this.hostname_ = hostname.replace(/\/+$/, '');
};
/**
* @param {string} hostname
* @param {?Object} credentials
* @param {?grpc.web.ClientOptions} options
* @constructor
* @struct
* @final
*/
proto.hiddifyrpc.ExtensionHostServicePromiseClient =
function(hostname, credentials, options) {
if (!options) options = {};
options.format = 'text';
/**
* @private @const {!grpc.web.GrpcWebClientBase} The client
*/
this.client_ = new grpc.web.GrpcWebClientBase(options);
/**
* @private @const {string} The hostname
*/
this.hostname_ = hostname.replace(/\/+$/, '');
};
/**
* @const
* @type {!grpc.web.MethodDescriptor<
* !proto.hiddifyrpc.Empty,
* !proto.hiddifyrpc.ExtensionList>}
*/
const methodDescriptor_ExtensionHostService_ListExtensions = new grpc.web.MethodDescriptor(
'/hiddifyrpc.ExtensionHostService/ListExtensions',
grpc.web.MethodType.UNARY,
base_pb.Empty,
proto.hiddifyrpc.ExtensionList,
/**
* @param {!proto.hiddifyrpc.Empty} request
* @return {!Uint8Array}
*/
function(request) {
return request.serializeBinary();
},
proto.hiddifyrpc.ExtensionList.deserializeBinary
);
/**
* @param {!proto.hiddifyrpc.Empty} request The
* request proto
* @param {?Object<string, string>} metadata User defined
* call metadata
* @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionList)}
* callback The callback function(error, response)
* @return {!grpc.web.ClientReadableStream<!proto.hiddifyrpc.ExtensionList>|undefined}
* The XHR Node Readable Stream
*/
proto.hiddifyrpc.ExtensionHostServiceClient.prototype.listExtensions =
function(request, metadata, callback) {
return this.client_.rpcCall(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/ListExtensions',
request,
metadata || {},
methodDescriptor_ExtensionHostService_ListExtensions,
callback);
};
/**
* @param {!proto.hiddifyrpc.Empty} request The
* request proto
* @param {?Object<string, string>=} metadata User defined
* call metadata
* @return {!Promise<!proto.hiddifyrpc.ExtensionList>}
* Promise that resolves to the response
*/
proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.listExtensions =
function(request, metadata) {
return this.client_.unaryCall(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/ListExtensions',
request,
metadata || {},
methodDescriptor_ExtensionHostService_ListExtensions);
};
/**
* @const
* @type {!grpc.web.MethodDescriptor<
* !proto.hiddifyrpc.ExtensionRequest,
* !proto.hiddifyrpc.ExtensionResponse>}
*/
const methodDescriptor_ExtensionHostService_Connect = new grpc.web.MethodDescriptor(
'/hiddifyrpc.ExtensionHostService/Connect',
grpc.web.MethodType.SERVER_STREAMING,
proto.hiddifyrpc.ExtensionRequest,
proto.hiddifyrpc.ExtensionResponse,
/**
* @param {!proto.hiddifyrpc.ExtensionRequest} request
* @return {!Uint8Array}
*/
function(request) {
return request.serializeBinary();
},
proto.hiddifyrpc.ExtensionResponse.deserializeBinary
);
/**
* @param {!proto.hiddifyrpc.ExtensionRequest} request The request proto
* @param {?Object<string, string>=} metadata User defined
* call metadata
* @return {!grpc.web.ClientReadableStream<!proto.hiddifyrpc.ExtensionResponse>}
* The XHR Node Readable Stream
*/
proto.hiddifyrpc.ExtensionHostServiceClient.prototype.connect =
function(request, metadata) {
return this.client_.serverStreaming(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/Connect',
request,
metadata || {},
methodDescriptor_ExtensionHostService_Connect);
};
/**
* @param {!proto.hiddifyrpc.ExtensionRequest} request The request proto
* @param {?Object<string, string>=} metadata User defined
* call metadata
* @return {!grpc.web.ClientReadableStream<!proto.hiddifyrpc.ExtensionResponse>}
* The XHR Node Readable Stream
*/
proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.connect =
function(request, metadata) {
return this.client_.serverStreaming(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/Connect',
request,
metadata || {},
methodDescriptor_ExtensionHostService_Connect);
};
/**
* @const
* @type {!grpc.web.MethodDescriptor<
* !proto.hiddifyrpc.EditExtensionRequest,
* !proto.hiddifyrpc.ExtensionActionResult>}
*/
const methodDescriptor_ExtensionHostService_EditExtension = new grpc.web.MethodDescriptor(
'/hiddifyrpc.ExtensionHostService/EditExtension',
grpc.web.MethodType.UNARY,
proto.hiddifyrpc.EditExtensionRequest,
proto.hiddifyrpc.ExtensionActionResult,
/**
* @param {!proto.hiddifyrpc.EditExtensionRequest} request
* @return {!Uint8Array}
*/
function(request) {
return request.serializeBinary();
},
proto.hiddifyrpc.ExtensionActionResult.deserializeBinary
);
/**
* @param {!proto.hiddifyrpc.EditExtensionRequest} request The
* request proto
* @param {?Object<string, string>} metadata User defined
* call metadata
* @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)}
* callback The callback function(error, response)
* @return {!grpc.web.ClientReadableStream<!proto.hiddifyrpc.ExtensionActionResult>|undefined}
* The XHR Node Readable Stream
*/
proto.hiddifyrpc.ExtensionHostServiceClient.prototype.editExtension =
function(request, metadata, callback) {
return this.client_.rpcCall(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/EditExtension',
request,
metadata || {},
methodDescriptor_ExtensionHostService_EditExtension,
callback);
};
/**
* @param {!proto.hiddifyrpc.EditExtensionRequest} request The
* request proto
* @param {?Object<string, string>=} metadata User defined
* call metadata
* @return {!Promise<!proto.hiddifyrpc.ExtensionActionResult>}
* Promise that resolves to the response
*/
proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.editExtension =
function(request, metadata) {
return this.client_.unaryCall(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/EditExtension',
request,
metadata || {},
methodDescriptor_ExtensionHostService_EditExtension);
};
/**
* @const
* @type {!grpc.web.MethodDescriptor<
* !proto.hiddifyrpc.SendExtensionDataRequest,
* !proto.hiddifyrpc.ExtensionActionResult>}
*/
const methodDescriptor_ExtensionHostService_SubmitForm = new grpc.web.MethodDescriptor(
'/hiddifyrpc.ExtensionHostService/SubmitForm',
grpc.web.MethodType.UNARY,
proto.hiddifyrpc.SendExtensionDataRequest,
proto.hiddifyrpc.ExtensionActionResult,
/**
* @param {!proto.hiddifyrpc.SendExtensionDataRequest} request
* @return {!Uint8Array}
*/
function(request) {
return request.serializeBinary();
},
proto.hiddifyrpc.ExtensionActionResult.deserializeBinary
);
/**
* @param {!proto.hiddifyrpc.SendExtensionDataRequest} request The
* request proto
* @param {?Object<string, string>} metadata User defined
* call metadata
* @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)}
* callback The callback function(error, response)
* @return {!grpc.web.ClientReadableStream<!proto.hiddifyrpc.ExtensionActionResult>|undefined}
* The XHR Node Readable Stream
*/
proto.hiddifyrpc.ExtensionHostServiceClient.prototype.submitForm =
function(request, metadata, callback) {
return this.client_.rpcCall(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/SubmitForm',
request,
metadata || {},
methodDescriptor_ExtensionHostService_SubmitForm,
callback);
};
/**
* @param {!proto.hiddifyrpc.SendExtensionDataRequest} request The
* request proto
* @param {?Object<string, string>=} metadata User defined
* call metadata
* @return {!Promise<!proto.hiddifyrpc.ExtensionActionResult>}
* Promise that resolves to the response
*/
proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.submitForm =
function(request, metadata) {
return this.client_.unaryCall(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/SubmitForm',
request,
metadata || {},
methodDescriptor_ExtensionHostService_SubmitForm);
};
/**
* @const
* @type {!grpc.web.MethodDescriptor<
* !proto.hiddifyrpc.ExtensionRequest,
* !proto.hiddifyrpc.ExtensionActionResult>}
*/
const methodDescriptor_ExtensionHostService_Close = new grpc.web.MethodDescriptor(
'/hiddifyrpc.ExtensionHostService/Close',
grpc.web.MethodType.UNARY,
proto.hiddifyrpc.ExtensionRequest,
proto.hiddifyrpc.ExtensionActionResult,
/**
* @param {!proto.hiddifyrpc.ExtensionRequest} request
* @return {!Uint8Array}
*/
function(request) {
return request.serializeBinary();
},
proto.hiddifyrpc.ExtensionActionResult.deserializeBinary
);
/**
* @param {!proto.hiddifyrpc.ExtensionRequest} request The
* request proto
* @param {?Object<string, string>} metadata User defined
* call metadata
* @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)}
* callback The callback function(error, response)
* @return {!grpc.web.ClientReadableStream<!proto.hiddifyrpc.ExtensionActionResult>|undefined}
* The XHR Node Readable Stream
*/
proto.hiddifyrpc.ExtensionHostServiceClient.prototype.close =
function(request, metadata, callback) {
return this.client_.rpcCall(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/Close',
request,
metadata || {},
methodDescriptor_ExtensionHostService_Close,
callback);
};
/**
* @param {!proto.hiddifyrpc.ExtensionRequest} request The
* request proto
* @param {?Object<string, string>=} metadata User defined
* call metadata
* @return {!Promise<!proto.hiddifyrpc.ExtensionActionResult>}
* Promise that resolves to the response
*/
proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.close =
function(request, metadata) {
return this.client_.unaryCall(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/Close',
request,
metadata || {},
methodDescriptor_ExtensionHostService_Close);
};
/**
* @const
* @type {!grpc.web.MethodDescriptor<
* !proto.hiddifyrpc.ExtensionRequest,
* !proto.hiddifyrpc.ExtensionActionResult>}
*/
const methodDescriptor_ExtensionHostService_GetUI = new grpc.web.MethodDescriptor(
'/hiddifyrpc.ExtensionHostService/GetUI',
grpc.web.MethodType.UNARY,
proto.hiddifyrpc.ExtensionRequest,
proto.hiddifyrpc.ExtensionActionResult,
/**
* @param {!proto.hiddifyrpc.ExtensionRequest} request
* @return {!Uint8Array}
*/
function(request) {
return request.serializeBinary();
},
proto.hiddifyrpc.ExtensionActionResult.deserializeBinary
);
/**
* @param {!proto.hiddifyrpc.ExtensionRequest} request The
* request proto
* @param {?Object<string, string>} metadata User defined
* call metadata
* @param {function(?grpc.web.RpcError, ?proto.hiddifyrpc.ExtensionActionResult)}
* callback The callback function(error, response)
* @return {!grpc.web.ClientReadableStream<!proto.hiddifyrpc.ExtensionActionResult>|undefined}
* The XHR Node Readable Stream
*/
proto.hiddifyrpc.ExtensionHostServiceClient.prototype.getUI =
function(request, metadata, callback) {
return this.client_.rpcCall(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/GetUI',
request,
metadata || {},
methodDescriptor_ExtensionHostService_GetUI,
callback);
};
/**
* @param {!proto.hiddifyrpc.ExtensionRequest} request The
* request proto
* @param {?Object<string, string>=} metadata User defined
* call metadata
* @return {!Promise<!proto.hiddifyrpc.ExtensionActionResult>}
* Promise that resolves to the response
*/
proto.hiddifyrpc.ExtensionHostServicePromiseClient.prototype.getUI =
function(request, metadata) {
return this.client_.unaryCall(this.hostname_ +
'/hiddifyrpc.ExtensionHostService/GetUI',
request,
metadata || {},
methodDescriptor_ExtensionHostService_GetUI);
};
module.exports = proto.hiddifyrpc;

File diff suppressed because it is too large Load Diff

View File

@ -1,239 +0,0 @@
const ansi_up = new AnsiUp({
escape_html: false,
});
function renderForm(json, dialog, submitAction, stopAction) {
const container = document.getElementById(`extension-page-container${dialog}`);
const formId = `dynamicForm${json.id}${dialog}`;
const existingForm = document.getElementById(formId);
if (existingForm) {
existingForm.remove();
}
const form = document.createElement('form');
container.appendChild(form);
form.id = formId;
if (dialog === "dialog") {
document.getElementById("modalLabel").textContent = json.title;
} else {
const titleElement = createTitleElement(json);
const stopBtn = document.createElement('button');
stopBtn.type = 'button';
stopBtn.className = 'btn btn-danger';
stopBtn.textContent = 'Close';
stopBtn.addEventListener('click', stopAction);
form.appendChild(stopBtn);
form.appendChild(titleElement);
}
addElementsToForm(form, json,submitAction);
if (dialog === "dialog") {
document.getElementById("modal-footer").innerHTML = '';
// if ($(form.lastChild).find("button").length > 0) {
// document.getElementById("modal-footer").appendChild(form.lastChild);
// }
const extensionDialog = document.getElementById("extension-dialog");
const dialog = bootstrap.Modal.getOrCreateInstance(extensionDialog);
dialog.show();
extensionDialog.addEventListener("hidden.bs.modal", (e)=>submitAction(e,"CloseDialog"));
}
}
function addElementsToForm(form, json,submitAction) {
const description = document.createElement('p');
description.textContent = json.description;
form.appendChild(description);
if (json.fields) {
json.fields.forEach(field => {
div=document.createElement("div")
div.classList.add("row")
form.appendChild(div)
for (let i = 0; i < field.length; i++) {
const formGroup = createFormGroup(field[i], submitAction);
formGroup.classList.add("col")
div.appendChild(formGroup);
}
});
}
return form;
}
function createTitleElement(json) {
const title = document.createElement('h1');
title.textContent = json.title;
return title;
}
function createFormGroup(field, submitAction) {
const formGroup = document.createElement('div');
formGroup.classList.add('mb-3');
if (field.type == "Button") {
const button = document.createElement('button');
button.textContent = field.label;
button.name=field.key
button.classList.add('btn');
if (field.key == "Submit") {
button.classList.add('btn-primary');
} else if (field.key == "Cancel") {
button.classList.add('btn-secondary');
}else{
button.classList.add('btn', 'btn-outline-secondary');
}
button.addEventListener('click', (e) => submitAction(e,field.key));
formGroup.appendChild(button);
} else {
if (field.label && !field.labelHidden) {
const label = document.createElement('label');
label.textContent = field.label;
label.setAttribute('for', field.key);
formGroup.appendChild(label);
}
const input = createInputElement(field);
formGroup.appendChild(input);
}
return formGroup;
}
function createInputElement(field) {
let input;
switch (field.type) {
case "Console":
input = document.createElement('pre');
input.innerHTML = ansi_up.ansi_to_html(field.value || field.placeholder || '');
input.style.maxHeight = field.lines * 20 + 'px';
break;
case "TextArea":
input = document.createElement('textarea');
input.rows = field.lines || 3;
input.textContent = field.value || '';
break;
case "Checkbox":
case "RadioButton":
input = createCheckboxOrRadioGroup(field);
break;
case "Switch":
input = createSwitchElement(field);
break;
case "Select":
input = document.createElement('select');
field.items.forEach(item => {
const option = document.createElement('option');
option.value = item.value;
option.text = item.label;
input.appendChild(option);
});
break;
default:
input = document.createElement('input');
input.type = field.type.toLowerCase();
input.value = field.value;
break;
}
input.id = field.key;
input.name = field.key;
if (field.readOnly) input.readOnly = true;
if (field.type == "Checkbox" || field.type == "RadioButton" || field.type == "Switch") {
} else {
if (field.required) input.required = true;
input.classList.add('form-control');
if (field.placeholder) input.placeholder = field.placeholder;
}
return input;
}
function createCheckboxOrRadioGroup(field) {
const wrapper = document.createDocumentFragment();
field.items.forEach(item => {
const inputWrapper = document.createElement('div');
inputWrapper.classList.add('form-check');
const input = document.createElement('input');
input.type = field.type === "Checkbox" ? 'checkbox' : 'radio';
input.classList.add('form-check-input');
input.id = `${field.key}_${item.value}`;
input.name = field.key; // Grouping by name for radio buttons
input.value = item.value;
input.checked = field.value === item.value;
const itemLabel = document.createElement('label');
itemLabel.classList.add('form-check-label');
itemLabel.setAttribute('for', input.id);
itemLabel.textContent = item.label;
inputWrapper.appendChild(input);
inputWrapper.appendChild(itemLabel);
wrapper.appendChild(inputWrapper);
});
return wrapper;
}
function createSwitchElement(field) {
const switchWrapper = document.createElement('div');
switchWrapper.classList.add('form-check', 'form-switch');
const input = document.createElement('input');
input.type = 'checkbox';
input.classList.add('form-check-input');
input.setAttribute('role', 'switch');
input.id = field.key;
input.checked = field.value === "true";
const label = document.createElement('label');
label.classList.add('form-check-label');
label.setAttribute('for', field.key);
label.textContent = field.label;
switchWrapper.appendChild(input);
switchWrapper.appendChild(label);
return switchWrapper;
}
function createButtonGroup(json, submitAction, cancelAction) {
const buttonGroup = document.createElement('div');
buttonGroup.classList.add('btn-group');
json.buttons.forEach(buttonText => {
const btn = document.createElement('button');
btn.classList.add('btn', "btn-default");
buttonGroup.appendChild(btn);
btn.textContent = buttonText
if (buttonText == "Cancel") {
btn.classList.add('btn-secondary');
btn.addEventListener('click', cancelAction);
} else {
if (buttonText == "Submit" || buttonText == "Ok")
btn.classList.add('btn-primary');
btn.addEventListener('click', submitAction);
}
})
return buttonGroup;
}
module.exports = { renderForm };

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,91 +0,0 @@
package extension
import (
"fmt"
"github.com/hiddify/hiddify-core/v2/db"
"github.com/sagernet/sing-box/log"
"github.com/hiddify/hiddify-core/v2/service_manager"
)
var (
allExtensionsMap = make(map[string]ExtensionFactory)
enabledExtensionsMap = make(map[string]*Extension)
)
func RegisterExtension(factory ExtensionFactory) error {
if _, ok := allExtensionsMap[factory.Id]; ok {
err := fmt.Errorf("Extension with ID %s already exists", factory.Id)
log.Warn(err)
return err
}
allExtensionsMap[factory.Id] = factory
return nil
}
func isEnable(id string) bool {
table := db.GetTable[extensionData]()
extdata, err := table.Get(id)
if err != nil {
return false
}
return extdata.Enable
}
func loadExtension(factory ExtensionFactory) error {
if !isEnable(factory.Id) {
return fmt.Errorf("Extension with ID %s is not enabled", factory.Id)
}
extension := factory.Builder()
extension.init(factory.Id)
// fmt.Printf("Registered extension: %+v\n", extension)
enabledExtensionsMap[factory.Id] = &extension
return nil
}
type extensionService struct {
// Storage *CacheFile
}
func (s *extensionService) Start() error {
table := db.GetTable[extensionData]()
for _, factory := range allExtensionsMap {
data, err := table.Get(factory.Id)
if data == nil || err != nil {
log.Warn("Data of Extension ", factory.Id, " not found, creating new one")
data = &extensionData{Id: factory.Id, Enable: false}
if err := table.UpdateInsert(data); err != nil {
log.Warn("Failed to create new extension data: ", err, " ", factory.Id)
return err
}
}
if data.Enable {
if err := loadExtension(factory); err != nil {
return fmt.Errorf("failed to load extension %s: %w", data.Id, err)
}
}
}
return nil
}
func (s *extensionService) Close() error {
for _, extension := range enabledExtensionsMap {
if err := (*extension).Close(); err != nil {
return err
}
}
return nil
}
func init() {
service_manager.Register(&extensionService{})
}

View File

@ -1,6 +0,0 @@
package repository
import (
_ "github.com/hiddify/hiddify-app-demo-extension/hiddify_extension"
_ "github.com/hiddify/hiddify-ip-scanner-extension/hiddify_extension"
)

View File

@ -1,47 +0,0 @@
package sdk
import (
"fmt"
"io/ioutil"
"net/http"
"runtime"
"strings"
"github.com/hiddify/hiddify-core/config"
v2 "github.com/hiddify/hiddify-core/v2"
"github.com/sagernet/sing-box/option"
)
func RunInstance(hiddifySettings *config.HiddifyOptions, singconfig *option.Options) (*v2.HiddifyService, error) {
return v2.RunInstance(hiddifySettings, singconfig)
}
func ParseConfig(hiddifySettings *config.HiddifyOptions, configStr string) (*option.Options, error) {
if hiddifySettings == nil {
hiddifySettings = config.DefaultHiddifyOptions()
}
if strings.HasPrefix(configStr, "http://") || strings.HasPrefix(configStr, "https://") {
client := &http.Client{}
configPath := strings.Split(configStr, "\n")[0]
// Create a new request
req, err := http.NewRequest("GET", configPath, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return nil, err
}
req.Header.Set("User-Agent", "HiddifyNext/2.3.1 ("+runtime.GOOS+") like ClashMeta v2ray sing-box")
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error making GET request:", err)
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read config body: %w", err)
}
configStr = string(body)
}
return config.ParseConfigContentToOptions(configStr, true, hiddifySettings, false)
}

View File

@ -1,117 +0,0 @@
package server
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
v2 "github.com/hiddify/hiddify-core/v2"
"github.com/hiddify/hiddify-core/utils"
"github.com/improbable-eng/grpc-web/go/grpcweb"
"google.golang.org/grpc"
)
func StartTestExtensionServer() {
v2.Setup("./tmp", "./", "./tmp", 0, false)
StartExtensionServer()
}
func StartExtensionServer() {
grpc_server, _ := v2.StartCoreGrpcServer("127.0.0.1:12345")
fmt.Printf("Waiting for CTRL+C to stop\n")
runWebserver(grpc_server)
}
func allowCors(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("Access-Control-Allow-Origin", "*")
resp.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
resp.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if req.Method == "OPTIONS" {
resp.WriteHeader(http.StatusOK)
return
}
}
func runWebserver(grpcServer *grpc.Server) {
// Context for cancellation
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Channels to signal termination
grpcTerminated := make(chan struct{})
grpcWebTerminated := make(chan struct{})
// Specify the directory to serve static files
dir := "./extension/html/"
// Wrapping gRPC server with grpc-web
grpcWeb := grpcweb.WrapServer(grpcServer)
// HTTP multiplexer
mux := http.NewServeMux()
mux.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) {
allowCors(resp, req)
if grpcWeb.IsGrpcWebRequest(req) || grpcWeb.IsAcceptableGrpcCorsRequest(req) {
grpcWeb.ServeHTTP(resp, req)
} else {
http.DefaultServeMux.ServeHTTP(resp, req)
}
})
// File server for static files
fs := http.FileServer(http.Dir(dir))
http.Handle("/", http.StripPrefix("/", fs))
// HTTP server for grpc-web
rpcWebServer := &http.Server{
Handler: mux,
Addr: ":12346",
}
log.Println("Serving grpc-web from https://localhost:12346/")
// Add a goroutine for the grpc-web server
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
utils.GenerateCertificate("cert/server-cert.pem", "cert/server-key.pem", true, true)
if err := rpcWebServer.ListenAndServeTLS("cert/server-cert.pem", "cert/server-key.pem"); err != nil && err != http.ErrServerClosed {
// if err := rpcWebServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Printf("Web server (gRPC-web) shutdown with error: %s", err)
}
grpcServer.Stop()
close(grpcWebTerminated) // Server terminated
}()
// Signal handling to gracefully shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
select {
case <-ctx.Done(): // Context canceled
log.Println("Context canceled, shutting down servers...")
case sig := <-sigChan: // OS signal received
log.Printf("Received signal: %s, shutting down servers...", sig)
case <-grpcTerminated: // Unexpected gRPC termination
log.Println("gRPC server terminated unexpectedly")
case <-grpcWebTerminated: // Unexpected gRPC-web termination
log.Println("gRPC-web server terminated unexpectedly")
}
// Graceful shutdown of the servers
if err := rpcWebServer.Shutdown(ctx); err != nil {
log.Printf("gRPC-web server shutdown with error: %s", err)
}
<-grpcWebTerminated
// Ensure all routines finish
wg.Wait()
log.Println("Server shutdown complete")
}

View File

@ -1,42 +0,0 @@
package ui
// // Field is an interface that all specific field types implement.
// type Field interface {
// GetType() string
// }
// // GenericField holds common field properties.
// const (
// Select string = "Select"
// Email string = "Email"
// Input string = "Input"
// Password string = "Password"
// TextArea string = "TextArea"
// Switch string = "Switch"
// Checkbox string = "Checkbox"
// RadioButton string = "RadioButton"
// DigitsOnly string = "digitsOnly"
// )
// // FormField extends GenericField with additional common properties.
// type FormField struct {
// Key string `json:"key"`
// Type string `json:"type"`
// Label string `json:"label,omitempty"`
// LabelHidden bool `json:"labelHidden"`
// Required bool `json:"required,omitempty"`
// Placeholder string `json:"placeholder,omitempty"`
// Readonly bool `json:"readonly,omitempty"`
// Value string `json:"value"`
// Validator string `json:"validator,omitempty"`
// Items []SelectItem `json:"items,omitempty"`
// Lines int `json:"lines,omitempty"`
// VerticalScroll bool `json:"verticalScroll,omitempty"`
// HorizontalScroll bool `json:"horizontalScroll,omitempty"`
// Monospace bool `json:"monospace,omitempty"`
// }
// // GetType returns the type of the field.
// func (gf FormField) GetType() string {
// return gf.Type
// }

View File

@ -1,75 +0,0 @@
package ui
// import (
// "encoding/json"
// "testing"
// )
// // Test UnmarshalJSON for different field types
// func TestFormUnmarshalJSON(t *testing.T) {
// formJSON := `{
// "title": "Form Example",
// "description": "This is a sample form.",
// "fields": [
// {
// "key": "inputKey",
// "type": "Input",
// "label": "Hi Group",
// "placeholder": "Hi Group flutter",
// "required": true,
// "value": "D"
// },
// {
// "key": "passwordKey",
// "type": "Password",
// "label": "Password",
// "required": true,
// "value": "secret"
// },
// {
// "key": "emailKey",
// "type": "Email",
// "label": "Email Label",
// "placeholder": "Enter your email",
// "required": true,
// "value": "example@example.com"
// }
// ]
// }`
// var form Form
// err := json.Unmarshal([]byte(formJSON), &form)
// if err != nil {
// t.Fatalf("Error unmarshaling form JSON: %v", err)
// }
// if form.Title != "Form Example" {
// t.Errorf("Expected Title to be 'Form Example', got '%s'", form.Title)
// }
// if form.Description != "This is a sample form." {
// t.Errorf("Expected Description to be 'This is a sample form.', got '%s'", form.Description)
// }
// if len(form.Fields) != 3 {
// t.Fatalf("Expected 3 fields, got %d", len(form.Fields))
// }
// for i, field := range form.Fields {
// switch f := field.(type) {
// case InputField:
// if f.Type != "Input" {
// t.Errorf("Field %d: Expected Type to be 'Input', got '%s'", i+1, f.Type)
// }
// case PasswordField:
// if f.Type != "Password" {
// t.Errorf("Field %d: Expected Type to be 'Password', got '%s'", i+1, f.Type)
// }
// case EmailField:
// if f.Type != "Email" {
// t.Errorf("Field %d: Expected Type to be 'Email', got '%s'", i+1, f.Type)
// }
// default:
// t.Errorf("Field %d: Unexpected field type %T", i+1, f)
// }
// }
// }

View File

@ -1,88 +0,0 @@
package ui
import (
"encoding/json"
"fmt"
)
// Field is an interface that all specific field types implement.
type Field interface {
GetType() string
}
// GenericField holds common field properties.
const (
FieldSelect string = "Select"
FieldEmail string = "Email"
FieldInput string = "Input"
FieldPassword string = "Password"
FieldTextArea string = "TextArea"
FieldSwitch string = "Switch"
FieldCheckbox string = "Checkbox"
FieldRadioButton string = "RadioButton"
FieldConsole string = "Console"
FieldButton string = "Button"
ValidatorDigitsOnly string = "digitsOnly"
ButtonSubmit string = "Submit"
ButtonCancel string = "Cancel"
ButtonDialogClose string = "CloseDialog"
ButtonDialogOk string = "OkDialog"
)
// FormField extends GenericField with additional common properties.
type FormField struct {
Key string `json:"key"`
Type string `json:"type"`
Label string `json:"label,omitempty"`
LabelHidden bool `json:"labelHidden"`
Required bool `json:"required,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
Readonly bool `json:"readonly,omitempty"`
Value string `json:"value"`
Validator string `json:"validator,omitempty"`
Items []SelectItem `json:"items,omitempty"`
Lines int `json:"lines,omitempty"`
}
// GetType returns the type of the field.
func (gf FormField) GetType() string {
return gf.Type
}
type InputField struct {
FormField
Validator string `json:"validator,omitempty"`
}
type SelectItem struct {
Label string `json:"label"`
Value string `json:"value"`
}
type Form struct {
Title string `json:"title"`
Description string `json:"description"`
Fields [][]FormField `json:"fields"`
// Buttons []string `json:"buttons"`
}
func (f *Form) ToJSON() string {
formJson, err := json.MarshalIndent(f, "", " ")
if err != nil {
fmt.Println("Error encoding to JSON:", err)
return ""
}
return (string(formJson))
}
// UnmarshalJSON custom unmarshals JSON data into a Form.
func (f *Form) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &f); err != nil {
return err
}
return nil
}

View File

@ -1,25 +0,0 @@
package ui
// // ContentField represents a label with additional properties.
// type ContentField struct {
// GenericField
// Lines int `json:"lines,omitempty"`
// VerticalScroll bool `json:"verticalScroll,omitempty"`
// HorizontalScroll bool `json:"horizontalScroll,omitempty"`
// Monospace bool `json:"monospace,omitempty"`
// }
// // NewContentField creates a new ContentField.
// func NewContentField(key, label string, lines int, monospace, horizontalScroll, verticalScroll bool) ContentField {
// return ContentField{
// GenericField: GenericField{
// Key: key,
// Type: "Content",
// Label: label,
// },
// Lines: lines,
// VerticalScroll: verticalScroll,
// HorizontalScroll: horizontalScroll,
// Monospace: monospace,
// }
// }

View File

@ -1 +0,0 @@
package ui

View File

@ -1,244 +0,0 @@
package ui
// import (
// "encoding/json"
// "fmt"
// )
// // InputField represents a text input field.
// type InputField struct {
// FormField
// Validator string `json:"validator,omitempty"`
// }
// // // NewInputField creates a new InputField.
// // func NewInputField(key, label, placeholder string, required bool, value string) InputField {
// // return InputField{
// // FormField: FormField{
// // GenericField: GenericField{
// // Key: key,
// // Type: "Input",
// // Label: label,
// // },
// // Placeholder: placeholder,
// // Required: required,
// // Value: value,
// // },
// // }
// // }
// // // PasswordField represents a password field.
// // type PasswordField struct {
// // FormField
// // }
// // // NewPasswordField creates a new PasswordField.
// // func NewPasswordField(key, label string, required bool, value string) PasswordField {
// // return PasswordField{
// // FormField: FormField{
// // GenericField: GenericField{
// // Key: key,
// // Type: "Password",
// // Label: label,
// // },
// // Required: required,
// // Value: value,
// // },
// // }
// // }
// // // EmailField represents an email field.
// // type EmailField struct {
// // FormField
// // }
// // // NewEmailField creates a new EmailField.
// // func NewEmailField(key, label, placeholder string, required bool, value string) EmailField {
// // return EmailField{
// // FormField: FormField{
// // GenericField: GenericField{
// // Key: key,
// // Type: "Email",
// // Label: label,
// // },
// // Placeholder: placeholder,
// // Required: required,
// // Value: value,
// // },
// // }
// // }
// // // TextAreaField represents a multi-line text area field.
// // type TextAreaField struct {
// // FormField
// // }
// // // NewTextAreaField creates a new TextAreaField.
// // func NewTextAreaField(key, label, placeholder string, required bool, value string) TextAreaField {
// // return TextAreaField{
// // FormField: FormField{
// // GenericField: GenericField{
// // Key: key,
// // Type: "TextArea",
// // Label: label,
// // },
// // Placeholder: placeholder,
// // Required: required,
// // Value: value,
// // },
// // }
// // }
// // // SelectField represents a dropdown selection field.
// // type SelectField struct {
// // FormField
// // Items []SelectItem `json:"items"`
// // }
// // // SelectItem represents an item in a dropdown.
// type SelectItem struct {
// Label string `json:"label"`
// Value string `json:"value"`
// }
// // // NewSelectField creates a new SelectField.
// // func NewSelectField(key, label, value string, items []SelectItem) SelectField {
// // return SelectField{
// // FormField: FormField{
// // GenericField: GenericField{
// // Key: key,
// // Type: "Select",
// // Label: label,
// // },
// // Value: value,
// // },
// // Items: items,
// // }
// // }
// // Form represents a collection of fields with metadata.
// type Form struct {
// Title string `json:"title"`
// Description string `json:"description"`
// Fields []FormField `json:"fields"`
// }
// func (f *Form) ToJSON() string {
// formJson, err := json.MarshalIndent(f, "", " ")
// if err != nil {
// fmt.Println("Error encoding to JSON:", err)
// return ""
// }
// return (string(formJson))
// }
// // UnmarshalJSON custom unmarshals JSON data into a Form.
// func (f *Form) UnmarshalJSON(data []byte) error {
// if err := json.Unmarshal(data, &f); err != nil {
// return err
// }
// // f.Title = raw.Title
// // f.Description = raw.Description
// // for _, fieldData := range raw.Fields {
// // var base FormField
// // if err := json.Unmarshal(fieldData, &base); err != nil {
// // return err
// // }
// // var field Field
// // switch base.Type {
// // case "Input":
// // var inputField InputField
// // if err := json.Unmarshal(fieldData, &inputField); err != nil {
// // return err
// // }
// // field = inputField
// // case "Password":
// // var passwordField PasswordField
// // if err := json.Unmarshal(fieldData, &passwordField); err != nil {
// // return err
// // }
// // field = passwordField
// // case "Email":
// // var emailField EmailField
// // if err := json.Unmarshal(fieldData, &emailField); err != nil {
// // return err
// // }
// // field = emailField
// // case "TextArea":
// // var textAreaField TextAreaField
// // if err := json.Unmarshal(fieldData, &textAreaField); err != nil {
// // return err
// // }
// // field = textAreaField
// // case "Select":
// // var selectField SelectField
// // if err := json.Unmarshal(fieldData, &selectField); err != nil {
// // return err
// // }
// // field = selectField
// // case "Content":
// // var contentField ContentField
// // if err := json.Unmarshal(fieldData, &contentField); err != nil {
// // return err
// // }
// // field = contentField
// // default:
// // return fmt.Errorf("unsupported field type: %s", base.Type)
// // }
// // f.Fields = append(f.Fields, field)
// // }
// return nil
// }
// // func main() {
// // // Example form JSON
// // formJSON := `{
// // "title": "Form Example",
// // "description": "",
// // "fields": [
// // {
// // "key": "inputKey",
// // "type": "Input",
// // "label": "Hi Group",
// // "placeholder": "Hi Group flutter",
// // "required": true,
// // "value": "D"
// // },
// // {
// // "key": "passwordKey",
// // "type": "Password",
// // "label": "Password",
// // "required": true,
// // "value": "secret"
// // },
// // {
// // "key": "emailKey",
// // "type": "Email",
// // "label": "Email Label",
// // "placeholder": "Enter your email",
// // "required": true,
// // "value": "example@example.com"
// // }
// // ]
// // }`
// // var form Form
// // // Decode the form JSON
// // if err := json.Unmarshal([]byte(formJSON), &form); err != nil {
// // fmt.Println("Error decoding form:", err)
// // return
// // }
// // // Print decoded form fields
// // fmt.Println("Form Title:", form.Title)
// // for i, field := range form.Fields {
// // fmt.Printf("Field %d: %T\n", i+1, field)
// // }
// // }

View File

@ -1,162 +0,0 @@
module github.com/hiddify/hiddify-core
go 1.22.0
toolchain go1.22.3
require (
github.com/bepass-org/warp-plus v1.2.4
github.com/fatih/color v1.16.0 // indirect
github.com/hiddify/hiddify-app-demo-extension v0.0.0-20241001070003-26039f960ad6
github.com/hiddify/hiddify-ip-scanner-extension v0.0.0-20241001070353-7ffd688b96b2
github.com/improbable-eng/grpc-web v0.15.0
github.com/jellydator/validation v1.1.0
github.com/kardianos/service v1.2.2
github.com/sagernet/gomobile v0.1.4
github.com/sagernet/sing v0.4.3
github.com/sagernet/sing-box v1.8.9
github.com/sagernet/sing-dns v0.2.3
github.com/spf13/cobra v1.8.0
github.com/xmdhs/clash2singbox v0.0.2
golang.org/x/sys v0.25.0
google.golang.org/grpc v1.66.0
google.golang.org/protobuf v1.34.2
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/Yiwen-Chan/tinydb v0.0.0-20230129042445-3321642f0674
github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca
github.com/tendermint/tm-db v0.6.7
)
require (
github.com/DataDog/zstd v1.4.1 // indirect
github.com/cenkalti/backoff/v4 v4.1.1 // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cosmos/gorocksdb v1.2.0 // indirect
github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect
github.com/dgraph-io/badger/v2 v2.2007.2 // indirect
github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de // indirect
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 // indirect
github.com/dustin/go-humanize v1.0.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/metacubex/tfo-go v0.0.0-20240821025650-e9be0afd5e7d // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rodaine/table v1.1.1 // indirect
github.com/rs/cors v1.7.0 // indirect
go.etcd.io/bbolt v1.3.6 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
nhooyr.io/websocket v1.8.6 // indirect
)
require (
berty.tech/go-libtor v1.0.385 // indirect
github.com/ajg/form v1.5.1 // indirect
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/caddyserver/certmagic v0.20.0 // indirect
github.com/cloudflare/circl v1.4.0 // indirect
github.com/cretz/bine v0.2.0 // indirect
github.com/dgryski/go-metro v0.0.0-20211217172704-adc40b04c140 // indirect
github.com/francoispqt/gojay v1.2.13 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/gaukas/godicttls v0.0.4 // indirect
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 // indirect
github.com/go-chi/chi/v5 v5.0.12 // indirect
github.com/go-chi/cors v1.2.1 // indirect
github.com/go-chi/render v1.0.3 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gofrs/uuid/v5 v5.2.0 // indirect
github.com/google/btree v1.1.2 // indirect
github.com/google/pprof v0.0.0-20240528025155-186aa0362fba // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/hashicorp/yamux v0.1.1 // indirect
github.com/hiddify/ray2sing v0.0.0-20240804185422-f340989b59a0
github.com/imkira/go-observer/v2 v2.0.0-20230629064422-8e0b61f11f1b // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/insomniacslk/dhcp v0.0.0-20231206064809-8c70d406f6d2 // indirect
github.com/josharian/native v1.1.0 // indirect
github.com/klauspost/compress v1.17.8 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/libdns/alidns v1.0.3 // indirect
github.com/libdns/cloudflare v0.1.1 // indirect
github.com/libdns/libdns v0.2.2 // indirect
github.com/logrusorgru/aurora v2.0.3+incompatible // indirect
github.com/mholt/acmez v1.2.0 // indirect
github.com/miekg/dns v1.1.62 // indirect
github.com/onsi/ginkgo/v2 v2.19.0 // indirect
github.com/ooni/go-libtor v1.1.8 // indirect
github.com/oschwald/maxminddb-golang v1.12.0 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pierrec/lz4/v4 v4.1.14 // indirect
github.com/pion/dtls/v2 v2.2.7 // indirect
github.com/pion/logging v0.2.2 // indirect
github.com/pion/randutil v0.1.0 // indirect
github.com/pion/stun/v2 v2.0.0 // indirect
github.com/pion/transport/v2 v2.2.3 // indirect
github.com/pion/transport/v3 v3.0.1 // indirect
github.com/pion/turn/v3 v3.0.1 // indirect
github.com/pires/go-proxyproto v0.7.0 // indirect
github.com/quic-go/qpack v0.4.0 // indirect
github.com/quic-go/qtls-go1-20 v0.4.1 // indirect
github.com/quic-go/quic-go v0.46.0 // indirect
github.com/refraction-networking/utls v1.6.7 // indirect
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 // indirect
github.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a // indirect
github.com/sagernet/cloudflare-tls v0.0.0-20231208171750-a4483c1b7cd1 // indirect
github.com/sagernet/gvisor v0.0.0-20240428053021-e691de28565f // indirect
github.com/sagernet/netlink v0.0.0-20240523065131-45e60152f9ba // indirect
github.com/sagernet/quic-go v0.47.0-beta.2 // indirect
github.com/sagernet/reality v0.0.0-20230406110435-ee17307e7691 // indirect
github.com/sagernet/sing-mux v0.2.0 // indirect
github.com/sagernet/sing-quic v0.2.2 // indirect
github.com/sagernet/sing-shadowsocks v0.2.7 // indirect
github.com/sagernet/sing-shadowsocks2 v0.2.0 // indirect
github.com/sagernet/sing-shadowtls v0.1.4 // indirect
github.com/sagernet/sing-tun v0.3.3 // indirect
github.com/sagernet/sing-vmess v0.1.12 // indirect
github.com/sagernet/smux v0.0.0-20231208180855-7041f6ea79e7 // indirect
github.com/sagernet/utls v1.5.4 // indirect
github.com/sagernet/wireguard-go v0.0.0-20231215174105-89dec3b2f3e8 // indirect
github.com/sagernet/ws v0.0.0-20231204124109-acfe8907c854 // indirect
github.com/seiflotfy/cuckoofilter v0.0.0-20240715131351-a2f2c23f1771 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/u-root/uio v0.0.0-20230220225925-ffce2a382923 // indirect
github.com/v2fly/ss-bloomring v0.0.0-20210312155135-28617310f63e // indirect
github.com/vishvananda/netns v0.0.4 // indirect
github.com/xtls/reality v0.0.0-20240712055506-48f0b2d5ed6d // indirect
github.com/xtls/xray-core v1.8.21 // indirect
github.com/zeebo/blake3 v0.2.3 // indirect
go.uber.org/mock v0.4.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc // indirect
golang.org/x/mod v0.18.0 // indirect
golang.org/x/net v0.28.0
golang.org/x/sync v0.8.0 // indirect
golang.org/x/text v0.18.0 // indirect
golang.org/x/time v0.5.0 // indirect
golang.org/x/tools v0.22.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
lukechampine.com/blake3 v1.3.0 // indirect
)
replace github.com/sagernet/sing-box => github.com/hiddify/hiddify-sing-box v1.8.9-0.20240928213625-7b79bf0c814d
replace github.com/xtls/xray-core => github.com/hiddify/xray-core v0.0.0-20240902024714-0fcb0895bb4b
replace github.com/sagernet/wireguard-go => github.com/hiddify/wireguard-go v0.0.0-20240727191222-383c1da14ff1
replace github.com/bepass-org/warp-plus => github.com/hiddify/warp-plus v0.0.0-20240717223357-4f3122e0d11d
replace github.com/hiddify/ray2sing => github.com/hiddify/ray2sing v0.0.0-20240928221833-190b549d5222

Some files were not shown because too many files have changed in this diff Show More