Full Code of dejavuzhou/felix for AI

main 9e5c6c479449 cached
48 files
69.3 KB
22.2k tokens
142 symbols
1 requests
Download .txt
Repository: dejavuzhou/felix
Branch: main
Commit: 9e5c6c479449
Files: 48
Total size: 69.3 KB

Directory structure:
gitextract_4c84voe0/

├── .gitattributes
├── .github/
│   └── workflows/
│       └── codeql-analysis.yml
├── .gitignore
├── .travis.yml
├── GeoLite2-Country.mmdb
├── LICENSE
├── Makefile
├── README.md
├── README_zh.md
├── SECURITY.md
├── api/
│   ├── api_cfip.go
│   ├── api_meta.go
│   ├── api_proxy.go
│   └── app.go
├── go.mod
├── go.sum
├── main.go
├── model/
│   ├── config.go
│   ├── db.go
│   ├── helper.go
│   ├── migrate.go
│   ├── t_cfip.go
│   ├── t_meta.go
│   └── t_proxy.go
├── socks5ws/
│   ├── app.go
│   ├── const.go
│   ├── relay_svr.go
│   ├── relay_tcp_direct.go
│   ├── relay_tcp_socks5e.go
│   ├── relay_udp_direct.go
│   ├── socks5_bind.go
│   ├── socks5_connect.go
│   ├── socks5_req.go
│   ├── socks5_udp_associate.go
│   └── websocket.go
└── util/
    ├── browse_open.go
    ├── cf_ip.go
    ├── cf_ip_test.go
    ├── crypt_aes.go
    ├── crypt_aes_test.go
    ├── crypt_des.go
    ├── enable_socks5_darwin.go
    ├── enable_socks5_linux.go
    ├── enable_socks5_windows.go
    ├── geo_ip.go
    ├── geo_ip_test.go
    ├── random_string.go
    └── vless_data.go

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitattributes
================================================
* linguist-vendored
*.go linguist-vendored=false

================================================
FILE: .github/workflows/codeql-analysis.yml
================================================
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"

on:
  push:
    branches: [ master ]
  pull_request:
    # The branches below must be a subset of the branches above
    branches: [ master ]
  schedule:
    - cron: '29 4 * * 2'

jobs:
  analyze:
    name: Analyze
    runs-on: ubuntu-latest
    permissions:
      actions: read
      contents: read
      security-events: write

    strategy:
      fail-fast: false
      matrix:
        language: [ 'go' ]
        # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
        # Learn more:
        # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed

    steps:
    - name: Checkout repository
      uses: actions/checkout@v2

    # Initializes the CodeQL tools for scanning.
    - name: Initialize CodeQL
      uses: github/codeql-action/init@v1
      with:
        languages: ${{ matrix.language }}
        # If you wish to specify custom queries, you can do so here or in a config file.
        # By default, queries listed here will override any specified in a config file.
        # Prefix the list here with "+" to use these queries and those in the config file.
        # queries: ./path/to/local/query, your-org/your-repo/queries@main

    # Autobuild attempts to build any compiled languages  (C/C++, C#, or Java).
    # If this step fails, then you should remove it and run the build manually (see below)
    - name: Autobuild
      uses: github/codeql-action/autobuild@v1

    # ℹ️ Command-line programs to run using the OS shell.
    # 📚 https://git.io/JvXDl

    # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
    #    and modify them (or add more) to build your code if your project
    #    uses a compiled language

    #- run: |
    #   make bootstrap
    #   make release

    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze@v1


================================================
FILE: .gitignore
================================================
felix
.idea
builds
builds/*
test*
_build*
*.exe
release
dist
_book
_release
.vscode
_nes
dist/
*sqlite3

================================================
FILE: .travis.yml
================================================
language: go
os:
  - linux
  - osx


matrix:
  fast_finish: true
  include:
    - go: 1.12.x
      env: CGO_ENABLED=0 GO111MODULE=on
\

git:
  depth: 1


before_install:
  - go build
script:
  - ./felix sshw

notifications:
  email:
    recipients:
      - neochau@gmail.com
    on_success: never

================================================
FILE: LICENSE
================================================

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: Makefile
================================================
LDFLAGS := "-s -w -X main.buildTime=$(shell date -u '+%Y-%m-%dT%I:%M:%S%p') -X main.gitHash=$(shell git rev-parse HEAD)"
GO ?= go
GOFMT ?= gofmt "-s"
PACKAGES ?= $(shell $(GO) list ./... | grep -v /vendor/)
VETPACKAGES ?= $(shell $(GO) list ./... | grep -v /vendor/ | grep -v /examples/)
GOFILES := $(shell find . -name "*.go" -type f -not -path "./vendor/*")


run: install
	./build/felix -V
install:
	go install -ldflags $(LDFLAGS)
vuejs:
	felix ginbin -s dist -p felixbin

build:vuejs
	go build -race -ldflags $(LDFLAGS)  -o build/felix *.go

release:vuejs
	CGO_ENABLED=1 GOOS=windows GOARCH=amd64  CXX_FOR_TARGET=i686-w64-mingw32-g++ CC_FOR_TARGET=i686-w64-mingw32-gcc go build -ldflags $(LDFLAGS) -o _release/felix-amd64-win.exe *.go
	CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -ldflags $(LDFLAGS) -o _release/felix-amd64-linux *.go
	CGO_ENABLED=1 GOOS=linux GOARCH=arm go build -ldflags $(LDFLAGS) -o _release/felix-amd64-linux-arm *.go
	CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 go build -ldflags $(LDFLAGS) -o _release/felix-amd64-darwin *.go


.PHONY: release



================================================
FILE: README.md
================================================
# Felix [中文](README_zh.md)


================================================
FILE: README_zh.md
================================================
# Felix
[![Build Status](https://travis-ci.org/libragen/felix.svg?branch=master)](https://travis-ci.org/libragen/felix)


================================================
FILE: SECURITY.md
================================================
# Security Policy

## Supported Versions

Use this section to tell people about which versions of your project are
currently being supported with security updates.

| Version | Supported          |
| ------- | ------------------ |
| 5.1.x   | :white_check_mark: |
| 5.0.x   | :x:                |
| 4.0.x   | :white_check_mark: |
| < 4.0   | :x:                |

## Reporting a Vulnerability

Use this section to tell people how to report a vulnerability.

Tell them where to go, how often they can expect to get an update on a
reported vulnerability, what to expect if the vulnerability is accepted or
declined, etc.


================================================
FILE: api/api_cfip.go
================================================
package api

import (
	"encoding/json"
	"fmt"
	"github.com/mojocn/felix/model"
	"github.com/mojocn/felix/util"
	"net/http"
)

func apiCfIpInit(w http.ResponseWriter, req *http.Request) {
	client, err := util.NewCfIP()
	if checkErr(w, err) {
		return
	}
	var rows []model.CfIp
	client.AllIps(func(ip, cidr string) {
		ins := model.CfIp{
			IP:   ip,
			Cidr: cidr,
		}
		rows = append(rows, ins)
	})
	err = model.DB().CreateInBatches(rows, 200).Error
	if checkErr(w, err) {
		return
	}
	responseJson(w, http.StatusOK, "ok")
}

func apiCfIpList(w http.ResponseWriter, req *http.Request) {
	var rows []model.CfIp
	err := model.DB().Limit(100).Find(&rows).Error
	if checkErr(w, err) {
		return
	}
	responseJson(w, http.StatusOK, rows)
}

func apiCfIpUpdate(w http.ResponseWriter, req *http.Request) {
	ins := new(model.CfIp)
	err := json.NewDecoder(req.Body).Decode(ins)
	if checkErr(w, err) {
		return
	}
	err = model.DB().Save(ins).Error
	if checkErr(w, err) {
		return
	}
	responseJson(w, http.StatusOK, ins)
}

func apiCfIpCreate(w http.ResponseWriter, req *http.Request) {
	ins := new(model.CfIp)
	err := json.NewDecoder(req.Body).Decode(ins)
	if checkErr(w, err) {
		return
	}
	ins.ID = 0
	err = model.DB().Save(ins).Error
	if checkErr(w, err) {
		return
	}
	responseJson(w, http.StatusOK, ins)
}

func apiCfIpDelete(w http.ResponseWriter, req *http.Request) {
	ins := new(model.CfIp)
	err := json.NewDecoder(req.Body).Decode(ins)
	if checkErr(w, err) {
		return
	}
	if ins.ID == 0 {
		err = fmt.Errorf("id can not be 0")
	}
	if checkErr(w, err) {
		return
	}
	err = model.DB().Delete(ins).Error
	if checkErr(w, err) {
		return
	}
	responseJson(w, http.StatusOK, ins)
}


================================================
FILE: api/api_meta.go
================================================
package api

import (
	"encoding/json"
	"github.com/mojocn/felix/model"
	"net/http"
)

func responseJson(w http.ResponseWriter, code int, data any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	err := json.NewEncoder(w).Encode(data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
func checkErr(w http.ResponseWriter, err error) (shouldReturn bool) {
	if err != nil {
		http.Error(w, err.Error(), http.StatusTeapot)
		return true
	}
	return false
}

func apiMeta(w http.ResponseWriter, req *http.Request) {
	row := new(model.Meta)
	err := model.DB().First(row).Error
	if checkErr(w, err) {
		return
	}
	responseJson(w, http.StatusOK, row)
}


================================================
FILE: api/api_proxy.go
================================================
package api

import (
	"encoding/json"
	"fmt"
	"github.com/mojocn/felix/model"
	"net/http"
)

func apiProxyList(w http.ResponseWriter, req *http.Request) {
	rows := []model.Proxy{}
	err := model.DB().Find(&rows).Error
	if checkErr(w, err) {
		return
	}
	responseJson(w, http.StatusOK, rows)
}

func apiProxyUpdate(w http.ResponseWriter, req *http.Request) {
	ins := new(model.Proxy)
	err := json.NewDecoder(req.Body).Decode(ins)
	if checkErr(w, err) {
		return
	}
	err = model.DB().Save(ins).Error
	if checkErr(w, err) {
		return
	}
	responseJson(w, http.StatusOK, ins)
}

func apiProxyCreate(w http.ResponseWriter, req *http.Request) {
	ins := new(model.Proxy)
	err := json.NewDecoder(req.Body).Decode(ins)
	if checkErr(w, err) {
		return
	}
	ins.ID = 0
	err = model.DB().Save(ins).Error
	if checkErr(w, err) {
		return
	}
	responseJson(w, http.StatusOK, ins)
}

func apiProxyDelete(w http.ResponseWriter, req *http.Request) {
	ins := new(model.Proxy)
	err := json.NewDecoder(req.Body).Decode(ins)
	if checkErr(w, err) {
		return
	}
	if ins.ID == 0 {
		err = fmt.Errorf("id can not be 0")
	}
	if checkErr(w, err) {
		return
	}
	err = model.DB().Delete(ins).Error
	if checkErr(w, err) {
		return
	}
	responseJson(w, http.StatusOK, ins)
}


================================================
FILE: api/app.go
================================================
package api

import (
	"log"
	"net/http"
)

type apiHandler struct{}

func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {}

func AdminServer(addr string) *http.Server {
	log.Println("http api server starting on", addr)
	mux := http.NewServeMux()
	mux.Handle("/api/foo", apiHandler{})
	mux.HandleFunc("GET /api/meta", apiMeta)

	mux.HandleFunc("GET /api/proxies", apiProxyList)
	mux.HandleFunc("PATCH /api/proxies", apiProxyUpdate)
	mux.HandleFunc("POST /api/proxies", apiProxyCreate)
	mux.HandleFunc("DELETE /api/proxies", apiProxyDelete)

	mux.HandleFunc("GET /api/cfip-init", apiCfIpInit)
	mux.HandleFunc("GET /api/cfips", apiCfIpList)
	mux.HandleFunc("PATCH /api/cfips", apiCfIpUpdate)
	mux.HandleFunc("POST /api/cfips", apiCfIpCreate)
	mux.HandleFunc("DELETE /api/cfips", apiCfIpDelete)

	server := &http.Server{
		Addr:    addr,
		Handler: mux,
	}
	return server
}


================================================
FILE: go.mod
================================================
module github.com/mojocn/felix

go 1.22

require (
	github.com/google/uuid v1.6.0
	github.com/gorilla/websocket v1.5.3
	github.com/oschwald/geoip2-golang v1.11.0
	golang.org/x/sys v0.27.0
	gorm.io/driver/sqlite v1.5.6
	gorm.io/gorm v1.25.12
)

require (
	github.com/jinzhu/inflection v1.0.0 // indirect
	github.com/jinzhu/now v1.1.5 // indirect
	github.com/mattn/go-sqlite3 v1.14.22 // indirect
	github.com/oschwald/maxminddb-golang v1.13.0 // indirect
	golang.org/x/text v0.20.0 // indirect
)


================================================
FILE: go.sum
================================================
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/oschwald/geoip2-golang v1.11.0 h1:hNENhCn1Uyzhf9PTmquXENiWS6AlxAEnBII6r8krA3w=
github.com/oschwald/geoip2-golang v1.11.0/go.mod h1:P9zG+54KPEFOliZ29i7SeYZ/GM6tfEL+rgSn03hYuUo=
github.com/oschwald/maxminddb-golang v1.13.0 h1:R8xBorY71s84yO06NgTmQvqvTvlS/bnYZrrWX1MElnU=
github.com/oschwald/maxminddb-golang v1.13.0/go.mod h1:BU0z8BfFVhi1LQaonTwwGQlsHUEu9pWNdMfmq4ztm0o=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s=
golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.5.6 h1:fO/X46qn5NUEEOZtnjJRWRzZMe8nqJiQ9E+0hi+hKQE=
gorm.io/driver/sqlite v1.5.6/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=


================================================
FILE: main.go
================================================
package main

import (
	"context"
	"fmt"
	"github.com/mojocn/felix/api"
	"github.com/mojocn/felix/model"
	"github.com/mojocn/felix/socks5ws"
	"log"
	"log/slog"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var (
	buildTime, gitHash string
	userUUID           = "53881505-c10c-464a-8949-e57184a576a9"
	url                = "ws://demo.libragen.cn/5sdfasdf"
	protocol           = "socks5e" // or vless
)

func main() {
	log.SetFlags(log.Lmicroseconds | log.Lshortfile)
	slog.SetLogLoggerLevel(slog.LevelDebug)

	model.DB()
	appCfg := model.Cfg()

	app, err := socks5ws.NewClientLocalSocks5Server(fmt.Sprintf("127.0.0.1:%d", appCfg.PortSocks5), "GeoLite2-Country.mmdb")
	if err != nil {
		log.Fatal(err)
	}

	slog.With("socks5", app.AddrSocks5).Info("socks5 server listening on")

	ctx, cancel := context.WithCancel(context.Background())
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGABRT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGKILL)

	httpS := api.AdminServer(fmt.Sprintf("127.0.0.1:%d", appCfg.PortHttp))
	go func() {
		if err := httpS.ListenAndServe(); err != nil {
			log.Fatal(err)
		}
	}()

	go func() {
		sig := <-signalChan
		fmt.Printf("\nReceived signal: %s\n", sig)
		cancel() // Cancel the context

		// Shutdown the server with a timeout
		shutdownCtx, shutdownCancel := context.WithTimeout(ctx, 2*time.Second)
		defer shutdownCancel()
		if err := httpS.Shutdown(shutdownCtx); err != nil {
			log.Fatalf("Server Shutdown Failed:%+v", err)
		}
	}()

	app.Run(ctx)
}


================================================
FILE: model/config.go
================================================
package model

import "log/slog"

type Config struct {
	PortSocks5 int    `json:"port_socks5"`
	PortHttp   int    `json:"port_http"`
	AuthUser   string `json:"auth_user"`
	AuthPass   string `json:"auth_pass"`
}

var (
	cfg    *Config
	defCfg = Config{
		PortSocks5: 1080,
		PortHttp:   1080 + 5,
		AuthUser:   "admin",
		AuthPass:   "admin",
	}
)

func Cfg() *Config {
	if cfg == nil {
		row := new(Meta)
		row.Config = defCfg
		err := db.FirstOrCreate(&row).Error
		if err != nil {
			slog.Error("get config error", "err", err)
		} else {
			cfg = &defCfg
		}
	}
	return cfg
}


================================================
FILE: model/db.go
================================================
package model

import (
	"gorm.io/driver/sqlite" // Sqlite driver based on CGO
	"gorm.io/gorm"
)

var db *gorm.DB

func initDb() {
	var err error
	db, err = gorm.Open(sqlite.Open("felix.sqlite3"), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	migrate()
}

func DB() *gorm.DB {
	if db == nil {
		initDb()
	}
	return db
}


================================================
FILE: model/helper.go
================================================
package model

import (
	"errors"
	"gorm.io/gorm"
)

// PaginationQ gin handler query binding struct
type PaginationQ struct {
	Ok    bool        `json:"ok"`
	Size  int         `form:"size" json:"size"`
	Page  int         `form:"page" json:"page"`
	Data  interface{} `json:"data" comment:"muster be a pointer of slice gorm.Model"` // save pagination list
	Total int64       `json:"total"`
}

// SearchAll optimized pagination method for gorm
func (p *PaginationQ) SearchAll(queryTx *gorm.DB) (data *PaginationQ, err error) {
	//99999 magic number for get all list without pagination
	if p.Size == 9999 || p.Size == 99999 {
		err = queryTx.Find(p.Data).Error
		p.Ok = err == nil
		return p, err
	}

	if p.Size < 1 {
		p.Size = 10
	}
	if p.Page < 1 {
		p.Page = 1
	}
	offset := p.Size * (p.Page - 1)
	err = queryTx.Count(&p.Total).Error
	if err != nil {
		return p, err
	}
	err = queryTx.Limit(p.Size).Offset(offset).Find(p.Data).Error
	p.Ok = err == nil
	return p, err
}

func crudAll(p *PaginationQ, queryTx *gorm.DB, list interface{}) (int64, error) {
	if p.Size < 1 {
		p.Size = 10
	}
	if p.Page < 1 {
		p.Page = 1
	}

	var total int64
	err := queryTx.Count(&total).Error
	if err != nil {
		return 0, err
	}
	offset := p.Size * (p.Page - 1)
	err = queryTx.Limit(p.Size).Offset(offset).Find(list).Error
	if err != nil {
		return 0, err
	}
	return total, err
}

func crudOne(m interface{}) (err error) {
	if err := db.First(m).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("resource is not found")
	}
	return nil
}

func crudDelete(m interface{}) (err error) {
	//WARNING When delete a record, you need to ensure it’s primary field has value, and GORM will use the primary key to delete the record, if primary field’s blank, GORM will delete all records for the model
	//primary key must be not zero value
	db := db.Unscoped().Delete(m)
	if err = db.Error; err != nil {
		return
	}
	if db.RowsAffected != 1 {
		return errors.New("resource is not found to destroy")
	}
	return nil
}


================================================
FILE: model/migrate.go
================================================
package model

import "log"

func migrate() {
	if db == nil {
		log.Print("db is nil")
		return
	}
	for _, m := range []interface{}{&CfIp{}, &Meta{}, &Proxy{}} {
		if err := db.AutoMigrate(m); err != nil {
			log.Print(err)
		}
	}
}


================================================
FILE: model/t_cfip.go
================================================
package model

import (
	"gorm.io/gorm"
	"time"
)

type ModelBase struct {
	ID        uint           `gorm:"primarykey" json:"id"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"deleted_at,omitempty"  gorm:"index"`
}

type CfIp struct {
	ModelBase
	IP    string `json:"ip" gorm:"type:varchar(15)"`
	Cidr  string `json:"cidr" gorm:"type:varchar(18)"`
	Ports []int  `json:"ports" gorm:"type:json;serializer:json"`
}


================================================
FILE: model/t_meta.go
================================================
package model

type Meta struct {
	ModelBase
	Config Config `json:"config" gorm:"type:json;serializer:json"`
}


================================================
FILE: model/t_proxy.go
================================================
package model

import (
	"fmt"
	"strings"
)

type Proxy struct {
	ModelBase
	Name string `json:"name" gorm:"varchar(255)"`

	Protocol string `json:"protocol" gorm:"varchar(16)"` //ws,wss,http2,tls,http3
	Host     string `json:"host" gorm:"varchar(255)"`
	Uri      string `json:"uri" gorm:"varchar(255)"`
	Sni      string `json:"sni" gorm:"varchar(255)"`
	Version  string `json:"version" gorm:"varchar(16)"` // one socks5

	UserID    string `json:"user_id"`
	Password  string `json:"password"`
	TrafficKb int64  `json:"traffic_kb" gorm:"default:0"`
	SpeedMs   int64  `json:"speed_ms" gorm:"default:0"`
	Status    string `json:"status" gorm:"varchar(16);default:''"` //active, inactive
}

func (p *Proxy) IsActive() bool {
	return p.Status == "active"
}
func (p *Proxy) RelayURL() string {
	switch p.Protocol {
	case "ws":
		return fmt.Sprintf("ws://%s/%s", p.Host, strings.TrimPrefix(p.Uri, "/"))
	case "wss":
		return fmt.Sprintf("wss://%s/%s", p.Host, strings.TrimPrefix(p.Uri, "/"))
	case "tcp+tls":
		return fmt.Sprintf("tcp-tls://%s/%s", p.Host, strings.TrimPrefix(p.Uri, "/"))
	default:
		return ""
	}
}


================================================
FILE: socks5ws/app.go
================================================
package socks5ws

import (
	"context"
	"errors"
	"fmt"
	"github.com/mojocn/felix/model"
	"github.com/mojocn/felix/util"
	"io"
	"log"
	"log/slog"
	"net"
	"sync"
	"time"
)

type ClientLocalSocks5Server struct {
	AddrSocks5 string
	geo        *util.GeoIP
	Timeout    time.Duration
	proxy      *model.Proxy
}

func NewClientLocalSocks5Server(addr, geoIpPath string) (*ClientLocalSocks5Server, error) {
	geo, err := util.NewGeoIP(geoIpPath)
	if err != nil {
		return nil, err
	}
	return &ClientLocalSocks5Server{
		AddrSocks5: addr,
		geo:        geo,
		Timeout:    5 * time.Minute,
	}, nil

}

func (ss *ClientLocalSocks5Server) fetchActiveProxy() {
	var proxies []model.Proxy
	err := model.DB().Find(&proxies).Error
	if err != nil {
		slog.Error("failed to get proxy setting", "err", err.Error())
		return
	}
	if len(proxies) == 0 {
		slog.Error("no proxy setting found")
		return
	}
	ss.proxy = &proxies[0]
	for _, proxy := range proxies {
		if proxy.IsActive() {
			ss.proxy = &proxy
			break
		}
	}
}

func (ss *ClientLocalSocks5Server) Run(ctx context.Context) {
	ss.fetchActiveProxy()

	listener, err := net.Listen("tcp", ss.AddrSocks5)
	if err != nil {
		listener, err = net.Listen("tcp4", "127.0.0.1:0")
	}
	if err != nil {
		log.Fatalf("Failed to listen on %s: %v", ss.AddrSocks5, err)
	}
	ss.AddrSocks5 = listener.Addr().String()
	slog.Info("socks5 server listening on", "addr", ss.AddrSocks5)

	defer listener.Close()
	log.Println("SOCKS5 server listening on: " + ss.AddrSocks5)
	//proxySettingOn(ss.AddrSocks5)
	//defer proxySettingOff()
	for {
		select {
		case <-ctx.Done():
			log.Println("socks5 server exit")
			return
		default:
			conn, err := listener.Accept()
			if err != nil {
				log.Printf("Failed to accept connection: %v", err)
				continue
			}
			go ss.handleConnection(ctx, conn)
		}
	}
}

func (ss *ClientLocalSocks5Server) socks5HandShake(conn net.Conn) error {
	buf := make([]byte, 2)
	if _, err := io.ReadFull(conn, buf); err != nil {
		return fmt.Errorf("failed to read version and nmethods: %w", err)
	}
	if buf[0] != socks5Version {
		return fmt.Errorf("socks5 only. unsupported SOCKS version: %d", buf[0])
	}

	// Read the supported authentication methods
	nMethods := int(buf[1])
	nMethodsData := make([]byte, nMethods)
	if _, err := io.ReadFull(conn, nMethodsData); err != nil {
		return fmt.Errorf("failed to read methods: %w", err)
	}

	// Select no authentication (0x00)
	if _, err := conn.Write([]byte{socks5Version, 0x00}); err != nil {
		return fmt.Errorf("failed to write method selection: %w", err)
	}
	return nil
}

func (ss *ClientLocalSocks5Server) socks5Request(conn net.Conn) (*Socks5Request, error) {
	buf := make([]byte, 8<<10)
	n, err := conn.Read(buf)
	if err != nil {
		return nil, fmt.Errorf("failed to read request: %w", err)
	}
	data := buf[:n]
	if len(data) < 4 {
		return nil, fmt.Errorf("request too short")
	}
	return parseSocks5Request(data, ss.geo)
}

func (ss *ClientLocalSocks5Server) handleConnection(outerCtx context.Context, conn net.Conn) {
	defer conn.Close() // the outer for loop is not suitable for defer, so defer close here
	ctx, cf := context.WithTimeout(outerCtx, ss.Timeout)
	defer cf()

	err := ss.socks5HandShake(conn)
	if err != nil {
		slog.Error("failed to handshake", "err", err.Error())
		socks5Response(conn, net.IPv4zero, 0, socks5ReplyFail)
		return
	}
	req, err := ss.socks5Request(conn)
	if err != nil {
		slog.Error("failed to parse socks5 request", "err", err.Error())
		socks5Response(conn, net.IPv4zero, 0, socks5ReplyFail)
		return
	}
	req.Logger().Info("remote target")
	if req.socks5Cmd == socks5CmdConnect { //tcp
		relayTcpSvr, err := ss.dispatchRelayTcpServer(ctx, req)
		if err != nil {
			slog.Error("failed to dispatch relay tcp server", "err", err.Error())
			socks5Response(conn, net.IPv4zero, 0, socks5ReplyFail)
			return
		}
		socks5Response(conn, net.IPv4zero, 0, socks5ReplyOkay)
		defer relayTcpSvr.Close()
		ss.pipeTcp(ctx, conn, relayTcpSvr)
		return
	} else if req.socks5Cmd == socks5CmdUdpAssoc {
		udpH, err := NewRelayUdpDirect(conn)
		if err != nil {
			slog.Error("failed to create udp handler", "err", err.Error())
			socks5Response(conn, net.IPv4zero, 0, socks5ReplyFail)
			return
		}

		defer udpH.Close()
		udpH.PipeUdp()
		return
	} else if req.socks5Cmd == socks5CmdBind {
		relayBind(conn, req)
		return
	} else {
		err = fmt.Errorf("unknown command: %d", req.socks5Cmd)
		slog.Error("unknown command", "err", err.Error())
		socks5Response(conn, net.IPv4zero, 0, socks5ReplyFail)
	}
}

func (ss *ClientLocalSocks5Server) shouldGoDirect(req *Socks5Request) (goDirect bool) {

	if req.CountryCode == "CN" || req.CountryCode == "" {
		//empty means geo ip failed or local address
		return true
	}

	return false
}

func (ss *ClientLocalSocks5Server) dispatchRelayTcpServer(ctx context.Context, req *Socks5Request) (io.ReadWriteCloser, error) {
	if ss.shouldGoDirect(req) {
		req.Logger().Info("go direct")
		return NewRelayTcpDirect(req)
	}
	return NewRelayTcpSocks5e(ctx, ss.proxy, req)
}

func (ss *ClientLocalSocks5Server) pipeTcp(ctx context.Context, s5 net.Conn, relayRw io.ReadWriter) {
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		span := slog.With("fn", "ws -> s5")
		defer func() {
			span.Debug("wg1 done")
			wg.Done()
		}()
		for {
			select {
			case <-ctx.Done():
				span.Info("ctx.Done exit")
				return
			default:
				//ws.SetReadDeadline(time.Now().Add(1 * time.Second))
				buf := make([]byte, 8<<10)
				n, err := relayRw.Read(buf)
				if err != nil {
					span.Error("relay read", "err", err.Error())
					return
				}
				_, err = s5.Write(buf[:n])
				if err != nil {
					span.Error("s5 write", "err", err.Error())
					return
				}
			}
		}
	}()
	go func() { // s5 -> ws
		span := slog.With("fn", "s5 -> ws")
		defer func() {
			span.Debug("wg2 done")
			wg.Done()
		}()
		for {
			select {
			case <-ctx.Done():
				span.Debug("ctx.Done exit")
				return
			default:
				buf := make([]byte, 8<<10)
				//s5.SetReadDeadline(time.Now().Add(20 * time.Millisecond))
				n, err := s5.Read(buf)
				if errors.Is(err, io.EOF) {
					slog.Info("s5 read EOF")
					return
				}
				if err != nil {
					et := fmt.Sprintf("%T", err)
					span.With("errType", et).Error("s5 read", "err", err.Error())
					return
				}
				//ws.SetWriteDeadline(time.Now().Add(1 * time.Second))
				n, err = relayRw.Write(buf[:n])
				if err != nil {
					span.Error("relay write", "err", err.Error())
					return
				}
			}
		}
	}()
	wg.Wait()
	slog.Debug("2 goroutines is Done")
}


================================================
FILE: socks5ws/const.go
================================================
package socks5ws

import (
	"log/slog"
	"net"
)

const (
	socks5Version             = 0x05
	socks5ReplyOkay           = 0x00
	socks5ReplyFail           = 0x01
	socks5ReplyReserved       = 0x00
	socks5CmdConnect          = 0x01
	socks5CmdBind             = 0x02
	socks5CmdUdpAssoc         = 0x03
	socks5AtypeIPv4           = 0x01
	socks5AtypeDomain         = 0x03
	socks5AtypeIPv6           = 0x04
	socks5UdpFragNotSupported = 0x00
	socks5UdpFragEnd          = 0x80

	bufferSize = 64 << 10
)

func socks5Response(conn net.Conn, ipv4 net.IP, port int, socks5OkayOrFail byte) {
	if socks5OkayOrFail != socks5ReplyOkay {
		ipv4 = net.IPv4zero
		port = 0
	}
	if ipv4 == nil {
		ipv4 = net.IPv4zero
	}
	if port < 0 || port > 65535 {
		port = 0
	}
	response := []byte{socks5Version, socks5OkayOrFail, socks5ReplyReserved, socks5AtypeIPv4, ipv4[0], ipv4[1], ipv4[2], ipv4[3], byte(port >> 8), byte(port & 0xff)}
	_, err := conn.Write(response)
	if err != nil {
		slog.Error("socks5 request rely failed to write", "err", err.Error())
	}
}


================================================
FILE: socks5ws/relay_svr.go
================================================
package socks5ws

import "io"

type RelayTcp interface {
	io.Reader
	io.Writer
	io.Closer
}


================================================
FILE: socks5ws/relay_tcp_direct.go
================================================
package socks5ws

import "net"

var _ RelayTcp = (*RelayTcpDirect)(nil)

type RelayTcpDirect struct {
	conn net.Conn
}

func NewRelayTcpDirect(req *Socks5Request) (*RelayTcpDirect, error) {
	conn, err := net.Dial("tcp", req.addr())
	if err != nil {
		return nil, err
	}
	return &RelayTcpDirect{conn: conn}, nil
}

func (r *RelayTcpDirect) Read(p []byte) (n int, err error) {
	return r.conn.Read(p)
}

func (r *RelayTcpDirect) Write(p []byte) (n int, err error) {
	return r.conn.Write(p)
}

func (r *RelayTcpDirect) Close() error {
	return r.conn.Close()
}


================================================
FILE: socks5ws/relay_tcp_socks5e.go
================================================
package socks5ws

import (
	"context"
	"github.com/gorilla/websocket"
	"github.com/mojocn/felix/model"
	"log/slog"
	"time"
)

var _ RelayTcp = (*RelayTcpSocks5e)(nil)

type RelayTcpSocks5e struct {
	cfg  *model.Proxy
	req  *Socks5Request
	conn *websocket.Conn
}

func NewRelayTcpSocks5e(ctx context.Context, cfg *model.Proxy, req *Socks5Request) (*RelayTcpSocks5e, error) {
	ws, err := webSocketConn(ctx, cfg, req)
	if err != nil {
		return nil, err
	}
	ws.SetCloseHandler(func(code int, text string) error {
		slog.Debug("ws has closed", "code", code, "text", text)
		return nil
	})
	return &RelayTcpSocks5e{cfg: cfg, req: req, conn: ws}, nil
}

func (r RelayTcpSocks5e) Read(data []byte) (n int, err error) {
	if r.conn != nil {
		_, p, err := r.conn.ReadMessage()
		if err != nil {
			slog.Error("failed to read ws", "err", err.Error())
		}
		return copy(data, p), err
	}
	return 0, nil
}

func (r RelayTcpSocks5e) Write(data []byte) (n int, err error) {
	if r.conn != nil {
		err = r.conn.WriteMessage(websocket.BinaryMessage, data)
		if err != nil {
			slog.Error("failed to write ws", "err", err.Error())
		}
		return len(data), err
	}
	return 0, nil
}

func (r RelayTcpSocks5e) Close() error {
	if r.conn != nil {
		err := r.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Millisecond*20))
		if err != nil {
			slog.Error("failed to close ws", "err", err.Error())
		}
		return r.conn.Close()
	}
	return nil
}


================================================
FILE: socks5ws/relay_udp_direct.go
================================================
package socks5ws

import (
	"errors"
	"fmt"
	"io"
	"log"
	"log/slog"
	"net"
	"sort"
	"sync"
	"time"
)

type RelayUdpDirect struct {
	s5       net.Conn
	relayUdp *net.UDPConn

	// Reassembly queue for fragmented UDP packets.
	mu            sync.Mutex
	fragments     map[string][]*udpPacket // Map of DstAddr to fragments
	highestFrag   map[string]byte         // Track highest FRAG value for each DstAddr
	timers        map[string]*time.Timer  // Map of DstAddr to reassembly timer
	timerDuration time.Duration           // Timer duration
}

func (ud *RelayUdpDirect) addFragment(clientAddr *net.UDPAddr, frag *udpPacket) {
	ud.mu.Lock()
	defer ud.mu.Unlock()
	clientDstAddr := ud.clientDstAddrAsID(clientAddr, frag.dstAddr())
	// Initialize fragment queue and timer if not already present.
	if _, exists := ud.fragments[clientDstAddr]; !exists {
		ud.fragments[clientDstAddr] = []*udpPacket{}
		ud.highestFrag[clientDstAddr] = socks5UdpFragNotSupported
		ud.startTimer(clientDstAddr)
	}

	// Update highest FRAG value.
	if frag.Frag > ud.highestFrag[clientDstAddr] {
		ud.highestFrag[clientDstAddr] = frag.Frag
	}

	// Add fragment to the queue.
	ud.fragments[clientDstAddr] = append(ud.fragments[clientDstAddr], frag)

	// Check if this is the final fragment (end-of-fragment sequence).
	if frag.Frag == socks5UdpFragEnd || frag.Frag == socks5UdpFragNotSupported { // High-order bit indicates end of sequence.
		ud.assembleThenPipeUdp(clientAddr, frag.dstAddr())
	}
}

func (ud *RelayUdpDirect) startTimer(ClientDstAddr string) {
	if timer, exists := ud.timers[ClientDstAddr]; exists {
		timer.Stop()
	}
	ud.timers[ClientDstAddr] = time.AfterFunc(ud.timerDuration, func() {
		ud.mu.Lock()
		defer ud.mu.Unlock()
		delete(ud.fragments, ClientDstAddr)
		delete(ud.highestFrag, ClientDstAddr)
		delete(ud.timers, ClientDstAddr)
	})
}
func (ud *RelayUdpDirect) clientDstAddrAsID(clientAddr *net.UDPAddr, dstAddr string) string {
	return fmt.Sprintf("%s/%s", clientAddr, dstAddr)
}
func (ud *RelayUdpDirect) assembleThenPipeUdp(clientAddr *net.UDPAddr, dstAddr string) {
	var data []byte
	clientDstAddr := ud.clientDstAddrAsID(clientAddr, dstAddr)
	fragments := ud.fragments[clientDstAddr]
	// Sort fragments by FRAG value.
	sort.Slice(fragments, func(i, j int) bool {
		return fragments[i].Frag < fragments[j].Frag
	})
	for _, frag := range fragments {
		data = append(data, frag.Data...)
	}
	comboPacket := fragments[0]
	comboPacket.Data = data

	// Clean up after successful reassembly.
	delete(ud.fragments, clientDstAddr)
	delete(ud.highestFrag, clientDstAddr)
	if timer, exists := ud.timers[clientDstAddr]; exists {
		timer.Stop()
		delete(ud.timers, clientDstAddr)
	}
	ud.segmentPipe(comboPacket, clientAddr)
}

func (ud *RelayUdpDirect) PipeUdp() {
	buf := make([]byte, bufferSize)
	for {
		n, clientAddr, err := ud.relayUdp.ReadFromUDP(buf)
		if errors.Is(err, io.EOF) {
			return
		}
		//I will not verify the `clientAddr` because this SOCKS5 proxy is intended for local relay to bypass the GFW.
		if err != nil {
			slog.Error("Error reading UDP data", "err", err.Error())
			continue
		}
		packet, err := parseUDPData(buf[:n])
		if err != nil {
			log.Println("Error parsing UDP data", err)
			continue
		}
		ud.addFragment(clientAddr, packet)
	}
}

func (ud *RelayUdpDirect) segmentPipe(comboPacket *udpPacket, clientAddr *net.UDPAddr) {
	resp, err := forwardUDPData(comboPacket)
	if err != nil {
		slog.Error("Error forwarding UDP data", "err", err.Error())
		return
	}
	header := comboPacket.ResponseData(resp)
	_, err = ud.relayUdp.WriteToUDP(header, clientAddr)
	if err != nil {
		slog.Error("Error sending UDP response", "err", err.Error())
	}
}

func NewRelayUdpDirect(s5 net.Conn) (*RelayUdpDirect, error) {
	udpAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0}
	udpConn, err := net.ListenUDP("udp", udpAddr)
	if err != nil {
		return nil, fmt.Errorf("failed to bind UDP socket: %w", err)
	}
	ud := &RelayUdpDirect{
		s5:            s5,
		relayUdp:      udpConn,
		mu:            sync.Mutex{},
		fragments:     make(map[string][]*udpPacket),
		highestFrag:   make(map[string]byte),
		timers:        make(map[string]*time.Timer),
		timerDuration: time.Second * 60,
	}

	boundAddr := udpConn.LocalAddr().(*net.UDPAddr)
	response := []byte{
		socks5Version, socks5ReplyOkay, socks5ReplyReserved, socks5AtypeIPv4,
		boundAddr.IP[0], boundAddr.IP[1], boundAddr.IP[2], boundAddr.IP[3],
		byte(boundAddr.Port >> 8), byte(boundAddr.Port & 0xFF),
	}
	_, err = ud.s5.Write(response)
	if err != nil {
		return nil, fmt.Errorf("failed to send response to client: %w", err)
	}

	return ud, nil
}

func forwardUDPData(udpPacket *udpPacket) ([]byte, error) {
	conn, err := net.DialUDP("udp", nil, udpPacket.addr())
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	_, err = conn.Write(udpPacket.Data)
	if err != nil {
		return nil, err
	}

	buf := make([]byte, bufferSize)
	n, _, err := conn.ReadFromUDP(buf)
	if err != nil {
		return nil, err
	}
	return buf[:n], nil
}

type udpPacket struct {
	RSV   [2]byte // reserved
	Frag  byte    // fragment
	AType byte    // dst address type
	Addr  []byte  // dst address
	Port  []byte  // dst port
	Data  []byte  // payload
}

func (p udpPacket) ResponseData(payload []byte) []byte {
	header := []byte{p.RSV[0], p.RSV[1], 0, p.AType}
	header = append(header, p.Addr...)
	header = append(header, p.Port...)
	return append(header, payload...)
}

func parseUDPData(data []byte) (*udpPacket, error) {
	if len(data) < 4 {
		return nil, fmt.Errorf("invalid UDP packet")
	}
	// parse header
	var packet = udpPacket{
		RSV:   [2]byte{data[0], data[1]},
		Frag:  data[2],
		AType: data[3],
	}
	switch packet.AType {
	case socks5AtypeIPv4:
		if len(data) < 10 {
			return nil, fmt.Errorf("invalid IPv4 UDP packet")
		}
		packet.Addr = data[4 : 4+net.IPv4len]
		packet.Port = data[4+net.IPv4len : 4+net.IPv4len+2]
		packet.Data = data[4+net.IPv4len+2:]
	case socks5AtypeIPv6:
		if len(data) < 22 {
			return nil, fmt.Errorf("invalid IPv6 UDP packet")
		}
		packet.Addr = data[4 : 4+net.IPv6len]
		packet.Port = data[4+net.IPv6len : 4+net.IPv6len+2]
		packet.Data = data[4+net.IPv6len+2:]
	case socks5AtypeDomain:
		if len(data) < 7 {
			return nil, fmt.Errorf("invalid domain UDP packet")
		}
		addrLen := int(data[4])
		packet.Addr = data[5 : 5+addrLen]
		packet.Port = data[5+addrLen : 5+addrLen+2]
		packet.Data = data[5+addrLen+2:]
	default:
		return nil, fmt.Errorf("unsupported address type: %d", packet.AType)
	}
	return &packet, nil
}

func (p udpPacket) ip() net.IP {
	switch p.AType {
	case socks5AtypeIPv4, socks5AtypeIPv6:
		return p.Addr
	case socks5AtypeDomain:
		ips, err := net.LookupIP(string(p.Addr))
		if err != nil {
			slog.Error("failed to resolve domain", "err", err.Error())
			return net.IPv4zero
		}
		if len(ips) == 0 {
			return net.IPv4zero
		}
		return ips[0]
	default:
		return net.IPv4zero
	}
}

func (p udpPacket) port() int {
	return int(p.Port[0])<<8 + int(p.Port[1])
}
func (p udpPacket) addr() *net.UDPAddr {
	return &net.UDPAddr{IP: p.ip(), Port: p.port()}
}
func (p udpPacket) dstAddr() string {
	return fmt.Sprintf("%s:%d", p.ip(), p.port())
}

func (ud *RelayUdpDirect) Close() {
	//s5 has already been closed in outside
	if ud.relayUdp != nil {
		err := ud.relayUdp.Close()
		if err != nil {
			log.Println("close udp conn failed: ", err)
		}
	}

}


================================================
FILE: socks5ws/socks5_bind.go
================================================
package socks5ws

import (
	"io"
	"log/slog"
	"net"
	"sync"
)

func relayBind(s5 net.Conn, _ *Socks5Request) {
	bindListener, err := net.Listen("tcp4", ":0")
	if err != nil {
		slog.Error("bind tcp failed", "err", err)
		socks5Response(s5, net.IPv4zero, 0, socks5ReplyFail)
		return
	}
	defer bindListener.Close()
	//first reply
	localAddr := bindListener.Addr().(*net.TCPAddr)
	socks5Response(s5, localAddr.IP, localAddr.Port, socks5ReplyOkay)

	targetConn, err := bindListener.Accept()
	if err != nil {
		slog.Error("bind tcp failed", "err", err)
		return
	}
	defer targetConn.Close()
	//sec reply
	targetAddr := targetConn.RemoteAddr().(*net.TCPAddr)
	socks5Response(s5, targetAddr.IP, targetAddr.Port, socks5ReplyOkay)

	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		defer wg.Done()
		_, err := io.Copy(targetConn, s5)
		if err != nil {
			slog.Error("bind tcp failed", "err", err)
		}
	}()
	go func() {
		defer wg.Done()
		_, err := io.Copy(s5, targetConn)
		if err != nil {
			slog.Error("bind tcp failed", "err", err)
		}
	}()
	wg.Wait()
}


================================================
FILE: socks5ws/socks5_connect.go
================================================
package socks5ws


================================================
FILE: socks5ws/socks5_req.go
================================================
package socks5ws

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/mojocn/felix/util"
	"log/slog"
	"net"
)

type Socks5Request struct {
	id          string
	socks5Cmd   byte
	socks5Atyp  byte
	dstAddr     []byte
	dstPort     []byte
	CountryCode string //iso country code
}

func parseSocks5Request(data []byte, geo *util.GeoIP) (*Socks5Request, error) {
	id := uuid.NewString()
	info := &Socks5Request{id: id}

	if data[0] != socks5Version {
		return nil, fmt.Errorf("unsupported SOCKS version: %d", data[0])
	}
	if data[1] == socks5CmdConnect {
		info.socks5Cmd = socks5CmdConnect
	} else if data[1] == socks5CmdUdpAssoc {
		info.socks5Cmd = socks5CmdUdpAssoc
	} else {
		//BIND is not supported
		return nil, fmt.Errorf("unsupported command: %d", data[1])
	}
	if data[2] != socks5ReplyReserved {
		return nil, fmt.Errorf("RSV must be 0x00")
	}
	if data[3] == socks5AtypeIPv4 {
		if len(data) < 10 {
			return nil, fmt.Errorf("request too short for atyp IPv4")
		}
		info.socks5Atyp = socks5AtypeIPv4
		info.dstAddr = data[4:8]
		info.dstPort = data[8:10]
	} else if data[3] == socks5AtypeDomain {
		if len(data) < 5 {
			return nil, fmt.Errorf("request too short for atyp Domain")
		}
		addrLen := int(data[4])
		info.socks5Atyp = socks5AtypeDomain
		info.dstAddr = data[5 : 5+addrLen]
		info.dstPort = data[5+addrLen : 5+addrLen+2]
	} else if data[3] == socks5AtypeIPv6 {
		if len(data) < 22 {
			return nil, fmt.Errorf("request too short for atyp IPv6")
		}
		info.socks5Atyp = socks5AtypeIPv6
		info.dstAddr = data[4:20]
		info.dstPort = data[20:22]
	} else {
		return nil, fmt.Errorf("unsupported address type: %d", data[3])
	}
	//only get country code for connect command
	if info.socks5Cmd == socks5CmdConnect {
		code, err := geo.Country(info.host())
		if err != nil {
			info.Logger().Error("failed to get country code", "err", err.Error())
		} else {
			info.CountryCode = code
		}
	}
	return info, nil
}

func (s Socks5Request) host() string {
	addr := ""
	if s.socks5Atyp == socks5AtypeIPv4 || s.socks5Atyp == socks5AtypeIPv6 {
		addr = net.IP(s.dstAddr).String()
	} else if s.socks5Atyp == socks5AtypeDomain {
		addr = string(s.dstAddr)
	} else {
		addr = string(s.dstAddr)
	}
	return addr
}

func (s Socks5Request) addr() string {
	return fmt.Sprintf("%s:%s", s.host(), s.port())
}
func (s Socks5Request) cmd() string {
	cmd := "unknown"
	if s.socks5Cmd == socks5CmdConnect {
		cmd = "connect"
	} else if s.socks5Cmd == socks5CmdUdpAssoc {
		cmd = "udp"
	} else if s.socks5Cmd == socks5CmdBind {
		cmd = "bind"
	}
	return cmd
}

func (s Socks5Request) Network() string {
	cmd := "unknown"
	if s.socks5Cmd == socks5CmdConnect {
		cmd = "tcp"
	} else if s.socks5Cmd == socks5CmdUdpAssoc {
		cmd = "udp"
	} else if s.socks5Cmd == socks5CmdBind {
		cmd = "bind"
	}
	return cmd
}

func (s Socks5Request) aType() string {
	return fmt.Sprintf("%v", s.socks5Atyp)
}

func (s Socks5Request) port() string {
	port := int(s.dstPort[0])<<8 + int(s.dstPort[1])
	return fmt.Sprintf("%v", port)
}

func (s Socks5Request) Logger() *slog.Logger {
	return slog.With("reqId", s.id, "cmd", s.cmd(), "atyp", s.aType(), "ip", s.host(), "port", s.port(), "country", s.CountryCode)
}
func (s Socks5Request) String() string {
	return fmt.Sprintf("socks5Cmd: %v, socks5Atyp: %v, dstAddr: %v, dstPort: %v, country: %s", s.cmd(), s.aType(), s.host(), s.port(), s.CountryCode)
}

func (s Socks5Request) addressBytes() []byte {
	if s.socks5Atyp == socks5AtypeDomain {
		return append([]byte{byte(len(s.dstAddr))}, s.dstAddr...)
	}
	return s.dstAddr
}


================================================
FILE: socks5ws/socks5_udp_associate.go
================================================
package socks5ws


================================================
FILE: socks5ws/websocket.go
================================================
package socks5ws

import (
	"context"
	"crypto/tls"
	"fmt"
	"github.com/gorilla/websocket"
	"github.com/mojocn/felix/model"
	"log/slog"
	"net/http"
)

const (
	browserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
)

func webSocketConn(ctx context.Context, proxy *model.Proxy, req *Socks5Request) (*websocket.Conn, error) {
	wsDialer := websocket.DefaultDialer

	headers := http.Header{}
	headers.Set("Authorization", proxy.UserID)
	headers.Set("User-Agent", browserAgent)
	if proxy.Sni != "" {
		headers.Set("Host", proxy.Sni)
		wsDialer.TLSClientConfig = &tls.Config{
			ServerName: proxy.Sni, // Set the SNI to the hostname of the server
		}
	}
	headers.Set("x-req-id", req.id)
	headers.Set("x-dst-network", "tcp")
	headers.Set("x-dst-addr", req.host())
	headers.Set("x-dst-port", req.port())
	headers.Set("x-dst-version", "socks5") // socks5proxy.Version
	url := proxy.RelayURL()
	slog.Debug("connecting to remote proxy server", "url", url)
	ws, resp, err := websocket.DefaultDialer.DialContext(ctx, url, headers)
	if err != nil {
		return nil, fmt.Errorf("failed to connect to remote proxy server: %s ,error:%v", proxy.RelayURL(), err)
	}
	if resp.StatusCode != http.StatusSwitchingProtocols {
		return nil, fmt.Errorf("failed to connect to remote proxy server: %s ,error:%v", proxy.RelayURL(), err)
	}
	return ws, nil
}


================================================
FILE: util/browse_open.go
================================================
package util

import (
	"os/exec"
	"runtime"
)

func BrowserOpen(url string) error {
	var cmd string
	var args []string

	switch runtime.GOOS {
	case "windows":
		cmd = "cmd"
		args = []string{"/c", "start"}
	case "darwin":
		cmd = "open"
	default: // "linux", "freebsd", "openbsd", "netbsd"
		cmd = "xdg-open"
	}
	args = append(args, url)
	return exec.Command(cmd, args...).Start()
}


================================================
FILE: util/cf_ip.go
================================================
package util

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"time"
)

//https://api.cloudflare.com/client/v4/ips
//https://api.cloudflare.com/client/v4/ips?networks=jdcloud

type CfIP struct {
	Ipv4Cidrs    []string `json:"ipv4_cidrs"`
	Ipv6Cidrs    []string `json:"ipv6_cidrs"`
	ReachableIPs chan string
}

var cfIpNode *CfIP

func singletonCfIP() *CfIP {
	if cfIpNode == nil {
		var err error
		cfIpNode, err = NewCfIP()
		if err != nil {
			log.Printf("Error getting cf ip: %v\n", err)
		}
	}
	return cfIpNode
}

func NewCfIP() (*CfIP, error) {
	resp, err := http.Get("https://api.cloudflare.com/client/v4/ips")
	if err != nil {
		return nil, fmt.Errorf("get cf ip failed %w", err)
	}
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("get cf ip failed %s", resp.Status)
	}
	defer resp.Body.Close()
	all, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("read cf ip failed %w", err)
	}
	result := struct {
		Result struct {
			Ipv4Cidrs []string `json:"ipv4_cidrs"`
			Ipv6Cidrs []string `json:"ipv6_cidrs"`
			Etag      string   `json:"etag"`
		} `json:"result"`
		Success  bool          `json:"success"`
		Errors   []interface{} `json:"errors"`
		Messages []interface{} `json:"messages"`
	}{}
	err = json.Unmarshal(all, &result)
	if err != nil {
		return nil, fmt.Errorf("unmarshal cf ip failed %w", err)
	}

	return &CfIP{
		Ipv4Cidrs:    result.Result.Ipv4Cidrs,
		Ipv6Cidrs:    result.Result.Ipv4Cidrs,
		ReachableIPs: make(chan string),
	}, nil
}

func (ci CfIP) IsCf(ip net.IP) bool {
	for _, cidr := range append(ci.Ipv4Cidrs, ci.Ipv6Cidrs...) {
		_, ipNet, err := net.ParseCIDR(cidr)
		if err != nil {
			log.Printf("Error parsing Cidr: %v\n", err)
			continue
		}
		if ipNet.Contains(ip) {
			return true
		}
	}
	return false
}

func (ci CfIP) AllIps(fn func(ip, cidr string)) {
	for _, cidr := range append(ci.Ipv4Cidrs, ci.Ipv6Cidrs...) {
		ips, err := getIPsFromCIDR(cidr)
		if err != nil {
			fmt.Printf("Error parsing Cidr: %v\n", err)
			continue
		}
		for _, ip := range ips {
			fn(ip, cidr)
		}
	}
}

//func (ci CfIP) CheckReachableIps() {
//	maxWorkers := runtime.GOMAXPROCS(0) * 64
//	ips := ci.ips()
//	jobs := make(chan string, len(ips))
//	resultChan := make(chan string, len(ips))
//	var wg sync.WaitGroup
//	for i := 0; i < maxWorkers; i++ {
//		wg.Add(1)
//		go func() {
//			defer wg.Done()
//			for ip := range jobs {
//				if isReachable(ip, 443) {
//					resultChan <- ip
//				}
//			}
//		}()
//	}
//	for _, ip := range ci.ips() {
//		jobs <- ip
//	}
//	close(jobs)
//	wg.Wait()
//	var reachable []string
//	for ip := range resultChan {
//		reachable = append(reachable, ip)
//	}
//	fd, err := os.Create("cf_reachable_ips.txt")
//	if err != nil {
//		log.Println(err)
//		return
//	}
//	defer fd.Close()
//	fd.Write([]byte(strings.Join(reachable, "\n")))
//}

func getIPsFromCIDR(cidr string) ([]string, error) {
	ip, ipNet, err := net.ParseCIDR(cidr)
	if err != nil {
		return nil, err
	}

	var ips []string
	for ip := ip.Mask(ipNet.Mask); ipNet.Contains(ip); inc(ip) {
		ips = append(ips, ip.String())
	}
	// Remove network address and broadcast address
	return ips[1 : len(ips)-1], nil
}

func inc(ip net.IP) {
	for j := len(ip) - 1; j >= 0; j-- {
		ip[j]++
		if ip[j] > 0 {
			break
		}
	}
}

func isReachable(ip string, port int) bool {
	timeout := time.Millisecond * 70
	conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", ip, port), timeout)
	if err != nil {
		log.Printf("Error connecting to %s:%d: %v\n", ip, port, err)
		return false
	}
	conn.Close()
	return true
}


================================================
FILE: util/cf_ip_test.go
================================================
package util

import "testing"

func TestCfIP_CheckReachableIps(t *testing.T) {

}


================================================
FILE: util/crypt_aes.go
================================================
package util

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
)

//https://tech.mojotv.cn/2019/06/28/golang-crypt#svekr
// key length must be 16/24/32
func AesEncrypt(origData []byte, key string) (string, error) {
	// 转成字节数组
	k := []byte(key)

	// 分组秘钥
	block, err := aes.NewCipher(k)
	if err != nil {
		return "", err
	}
	// 获取秘钥块的长度
	blockSize := block.BlockSize()
	// 补全码
	origData = PKCS7Padding(origData, blockSize)
	// 加密模式
	blockMode := cipher.NewCBCEncrypter(block, k[:blockSize])
	// 创建数组
	cryted := make([]byte, len(origData))
	// 加密
	blockMode.CryptBlocks(cryted, origData)

	return base64.RawURLEncoding.EncodeToString(cryted), nil

}

func AesDecrypt(cryted string, key string) ([]byte, error) {
	// 转成字节数组
	crytedByte, err := base64.RawURLEncoding.DecodeString(cryted)
	if err != nil {
		return nil, err
	}
	k := []byte(key)

	// 分组秘钥
	block, err := aes.NewCipher(k)
	if err != nil {
		return nil, err
	}
	// 获取秘钥块的长度
	blockSize := block.BlockSize()
	// 加密模式
	blockMode := cipher.NewCBCDecrypter(block, k[:blockSize])
	// 创建数组
	orig := make([]byte, len(crytedByte))
	// 解密
	blockMode.CryptBlocks(orig, crytedByte)
	// 去补全码
	orig = PKCS7UnPadding(orig)
	return orig, nil
}

//补码
func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
	padding := blocksize - len(ciphertext)%blocksize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

//去码
func PKCS7UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}


================================================
FILE: util/crypt_aes_test.go
================================================
package util

import "testing"

func TestAesDecryptEn(t *testing.T) {
	key := RandStringWordC(32)

	msg := RandomString(12)

	code, err := AesEncrypt([]byte(msg), key)
	if err != nil {
		t.Error(err)
	}
	tMsg, err := AesDecrypt(code, key)
	if err != nil {
		t.Error(err)
	}
	if string(tMsg) != msg {
		t.Error("aes failed")
	}
}


================================================
FILE: util/crypt_des.go
================================================
package util

import (
	"bytes"
	"crypto/des"
	"encoding/hex"
	"errors"
)

func ZeroPadding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{0}, padding)
	return append(ciphertext, padtext...)
}

func ZeroUnPadding(origData []byte) []byte {
	return bytes.TrimFunc(origData,
		func(r rune) bool {
			return r == rune(0)
		})
}

func DesEncrypt(text string, key []byte) (string, error) {
	src := []byte(text)
	block, err := des.NewCipher(key)
	if err != nil {
		return "", err
	}
	bs := block.BlockSize()
	src = ZeroPadding(src, bs)
	if len(src)%bs != 0 {
		return "", errors.New("Need a multiple of the blocksize")
	}
	out := make([]byte, len(src))
	dst := out
	for len(src) > 0 {
		block.Encrypt(dst, src[:bs])
		src = src[bs:]
		dst = dst[bs:]
	}
	return hex.EncodeToString(out), nil
}
func DesDecrypt(decrypted string, key []byte) (string, error) {
	src, err := hex.DecodeString(decrypted)
	if err != nil {
		return "", err
	}
	block, err := des.NewCipher(key)
	if err != nil {
		return "", err
	}
	out := make([]byte, len(src))
	dst := out
	bs := block.BlockSize()
	if len(src)%bs != 0 {
		return "", errors.New("crypto/cipher: input not full blocks")
	}
	for len(src) > 0 {
		block.Decrypt(dst, src[:bs])
		src = src[bs:]
		dst = dst[bs:]
	}
	out = ZeroUnPadding(out)
	return string(out), nil
}


================================================
FILE: util/enable_socks5_darwin.go
================================================
package util

import (
	"bytes"
	"fmt"
	"os/exec"
	"strings"
)

func proxySettingOn(socks5Addr string) {
	networkService := "Wi-Fi"   // Change this to your active network service name
	proxyAddress := "127.0.0.1" // SOCKS5 proxy address
	proxyPort := "1080"         // SOCKS5 proxy port

	// Disable the SOCKS proxy first (optional cleanup)
	disableCmd := exec.Command("networksetup", "-setsocksfirewallproxystate", networkService, "off")
	if err := disableCmd.Run(); err != nil {
		fmt.Printf("Failed to disable SOCKS proxy: %v\n", err)
	}

	// Set the SOCKS proxy
	cmd := exec.Command("networksetup",
		"-setsocksfirewallproxy",
		networkService,
		proxyAddress,
		proxyPort)
	if err := cmd.Run(); err != nil {
		fmt.Printf("Failed to set SOCKS proxy: %v\n", err)
		return
	}

	// Enable the SOCKS proxy
	enableCmd := exec.Command("networksetup", "-setsocksfirewallproxystate", networkService, "on")
	if err := enableCmd.Run(); err != nil {
		fmt.Printf("Failed to enable SOCKS proxy: %v\n", err)
		return
	}

	fmt.Println("SOCKS5 proxy configured successfully!")
}

func proxySettingOff() (string, error) {
	cmd := exec.Command("networksetup", "-listallnetworkservices")
	var out bytes.Buffer
	cmd.Stdout = &out
	if err := cmd.Run(); err != nil {
		return "", err
	}

	// List all network services
	services := strings.Split(out.String(), "\n")
	for _, service := range services {
		if service != "" {
			// Check if the service is active by getting the status
			statusCmd := exec.Command("networksetup", "-getinfo", service)
			var statusOut bytes.Buffer
			statusCmd.Stdout = &statusOut
			if err := statusCmd.Run(); err != nil {
				return "", err
			}

			// Check if the service has a valid IP address (active network)
			if strings.Contains(statusOut.String(), "IP address") {
				return service, nil
			}
		}
	}
	return "", fmt.Errorf("no active network service found")
}


================================================
FILE: util/enable_socks5_linux.go
================================================
package util

func proxySettingOn(socks5Addr string) {

}
func proxySettingOff(socks5Addr string) {

}


================================================
FILE: util/enable_socks5_windows.go
================================================
package util

import (
	"fmt"
	"golang.org/x/sys/windows/registry"
	"log"
)

func proxySettingOn(socks5Addr string) {
	// Open the registry key for proxy settings
	key, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.SET_VALUE)
	if err != nil {
		log.Fatalf("Error opening registry key: %v", err)
	}
	defer key.Close()

	// Enable proxy and set proxy server to SOCKS5
	err = key.SetDWordValue("ProxyEnable", 1) // 1 to enable proxy
	if err != nil {
		log.Fatalf("Error enabling proxy: %v", err)
	}

	// Set the SOCKS5 proxy address (e.g., "socks=127.0.0.1:1080")
	err = key.SetStringValue("ProxyServer", "socks5://"+socks5Addr)
	if err != nil {
		log.Fatalf("Error setting proxy server: %v", err)
	}

	// Set the proxy override settings : *.cn;*.local
	//
	skipAddrs := "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>;*.cn"
	err = key.SetStringValue("ProxyOverride", skipAddrs)
	if err != nil {
		log.Fatalf("Error setting proxy override: %v", err)
	}
	// Optionally disable automatic proxy detection
	err = key.SetDWordValue("AutoDetect", 0) // 0 to disable
	if err != nil {
		log.Fatalf("Error disabling automatic proxy detection: %v", err)
	}

	fmt.Println("SOCKS5 proxy configuration applied successfully.")

	//cmd := exec.Command("netsh", "winhttp", "reset", "proxy")
	//err = cmd.Run()
	//if err != nil {
	//	slog.Error("Error resetting proxy settings: ", err)
	//}
	//log.Println("Network settings refreshed.")
}
func proxySettingOff() {
	log.Print("Disabling SOCKS5 proxy settings...")
	// Open the registry key for proxy settings
	key, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.SET_VALUE)
	if err != nil {
		log.Fatalf("Error opening registry key: %v", err)
	}
	defer key.Close()

	// Enable proxy and set proxy server to SOCKS5
	err = key.SetDWordValue("ProxyEnable", 0) // 1 to enable proxy
	if err != nil {
		log.Fatalf("Error enabling proxy: %v", err)
	}

	//cmd := exec.Command("netsh", "winhttp", "reset", "proxy")
	//err = cmd.Run()
	//if err != nil {
	//	log.Fatalf("Error resetting proxy settings: %v", err)
	//}
	//log.Println("Network settings refreshed.")
}


================================================
FILE: util/geo_ip.go
================================================
package util

import (
	"fmt"
	"github.com/oschwald/geoip2-golang"
	"net"
)

type GeoIP struct {
	db *geoip2.Reader
}

func NewGeoIP(geoIpFilePath string) (*GeoIP, error) {
	if geoIpFilePath == "" {
		geoIpFilePath = "GeoLite2-Country.mmdb" //https://github.com/P3TERX/GeoLite.mmdb?tab=readme-ov-file
	}
	db, err := geoip2.Open(geoIpFilePath)
	if err != nil {
		return nil, err
	}
	return &GeoIP{db: db}, nil
}

func (g *GeoIP) Close() error {
	if g.db != nil {
		return g.db.Close()
	}
	return nil
}

func (g *GeoIP) Country(host string) (isoCountryCode string, err error) {
	if g == nil {
		return "", fmt.Errorf("geo databse is nil")
	}
	ip := net.ParseIP(host)
	if ip == nil {
		ips, err := net.LookupIP(host)
		if err != nil {
			return "", fmt.Errorf("failed to lookup IP: %w", err)
		}
		if len(ips) == 0 {
			return "", fmt.Errorf("no IP found for %s", host)
		}
		ip = ips[0]
	}
	record, err := g.db.Country(ip)
	if err != nil {
		return "", fmt.Errorf("failed to get Country: %w", err)
	}
	return record.Country.IsoCode, nil
}


================================================
FILE: util/geo_ip_test.go
================================================
package util

import (
	"testing"
)

func TestGeoDns_country(t *testing.T) {

}


================================================
FILE: util/random_string.go
================================================
package util

import (
	"fmt"
	"math/rand"
)

var (
	stringMisc = []byte(".$#@&*_")

	stringDigit    = []byte("1234567890")
	stringDigitLen = len(stringDigit)

	stringLword    = []byte("abcdefghijklmnopqrstuvwxyz")
	stringLwordLen = len(stringLword)

	stringUWord    = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
	stringUWordLen = len(stringUWord)

	stringCWord    = []byte(fmt.Sprintf("%s%s", stringLword, stringUWord))
	stringCWordLen = len(stringCWord)

	letterRunes    = []byte(fmt.Sprintf("%s%s%s%s", stringDigit, stringLword, stringMisc, stringUWord))
	letterRunesLen = len(letterRunes)
)

func RandomString(n int) string {
	b := make([]byte, n)
	for i := range b {
		b[i] = letterRunes[rand.Intn(letterRunesLen)]
	}
	return string(b)
}

func RandStringWordL(n int) string {
	b := make([]byte, n)
	for i := range b {
		b[i] = stringLword[rand.Intn(stringLwordLen)]
	}
	return string(b)
}

func RandStringWordU(n int) string {
	b := make([]byte, n)
	for i := range b {
		b[i] = stringUWord[rand.Intn(stringUWordLen)]
	}
	return string(b)
}
func RandStringWordC(n int) string {
	b := make([]byte, n)
	for i := range b {
		b[i] = stringCWord[rand.Intn(stringCWordLen)]
	}
	return string(b)
}
func RandStringDigit(n int) string {
	b := make([]byte, n)
	for i := range b {
		b[i] = stringDigit[rand.Intn(stringDigitLen)]
	}
	return string(b)
}


================================================
FILE: util/vless_data.go
================================================
package util

import (
	"encoding/binary"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"log/slog"
	"net"
)

type SchemaVLESS struct {
	userID      uuid.UUID
	DstProtocol string //tcp or udp
	dstHost     string
	dstHostType string //ipv6 or ipv4,domain
	dstPort     uint16
	Version     byte
	payload     []byte
}

func (h SchemaVLESS) UUID() string {
	return h.userID.String()
}

func (h SchemaVLESS) DataUdp() []byte {
	allData := make([]byte, 0)
	chunk := h.payload
	for index := 0; index < len(chunk); {
		if index+2 > len(chunk) {
			fmt.Println("Incomplete length buffer")
			return nil
		}
		lengthBuffer := chunk[index : index+2]
		udpPacketLength := binary.BigEndian.Uint16(lengthBuffer)
		if index+2+int(udpPacketLength) > len(chunk) {
			fmt.Println("Incomplete UDP packet")
			return nil
		}
		udpData := chunk[index+2 : index+2+int(udpPacketLength)]
		index = index + 2 + int(udpPacketLength)
		allData = append(allData, udpData...)
	}
	return allData
}
func (h SchemaVLESS) DataTcp() []byte {
	return h.payload
}

func (h SchemaVLESS) AddrUdp() *net.UDPAddr {
	return &net.UDPAddr{IP: h.HostIP(), Port: int(h.dstPort)}
}
func (h SchemaVLESS) HostIP() net.IP {
	ip := net.ParseIP(h.dstHost)
	if ip == nil {
		ips, err := net.LookupIP(h.dstHost)
		if err != nil {
			h.Logger().Error("failed to resolve domain", "err", err.Error())
			return net.IPv4zero
		}
		if len(ips) == 0 {
			return net.IPv4zero
		}
		return ips[0]
	}
	return ip
}

func (h SchemaVLESS) HostPort() string {
	return net.JoinHostPort(h.dstHost, fmt.Sprintf("%d", h.dstPort))
}
func (h SchemaVLESS) Logger() *slog.Logger {
	return slog.With("userID", h.userID.String(), "network", h.DstProtocol, "addr", h.HostPort())
}

// VlessParse https://xtls.github.io/development/protocols/vless.html
func VlessParse(buf []byte) (*SchemaVLESS, error) {
	payload := &SchemaVLESS{
		userID:      uuid.Nil,
		DstProtocol: "",
		dstHost:     "",
		dstPort:     0,
		Version:     0,
		payload:     nil,
	}

	if len(buf) < 24 {
		return payload, errors.New("invalid payload length")
	}

	payload.Version = buf[0]
	payload.userID = uuid.Must(uuid.FromBytes(buf[1:17]))
	extraInfoProtoBufLen := buf[17]

	command := buf[18+extraInfoProtoBufLen]
	switch command {
	case 1:
		payload.DstProtocol = "tcp"
	case 2:
		payload.DstProtocol = "udp"
	default:
		return payload, fmt.Errorf("command %d is not supported, command 01-tcp, 02-udp, 03-mux", command)
	}

	portIndex := 18 + extraInfoProtoBufLen + 1
	payload.dstPort = binary.BigEndian.Uint16(buf[portIndex : portIndex+2])

	addressIndex := portIndex + 2
	addressType := buf[addressIndex]
	addressValueIndex := addressIndex + 1

	switch addressType {
	case 1: // IPv4
		if len(buf) < int(addressValueIndex+net.IPv4len) {
			return nil, fmt.Errorf("invalid IPv4 address length")
		}
		payload.dstHost = net.IP(buf[addressValueIndex : addressValueIndex+net.IPv4len]).String()
		payload.payload = buf[addressValueIndex+net.IPv4len:]
		payload.dstHostType = "ipv4"
	case 2: // domain
		addressLength := buf[addressValueIndex]
		addressValueIndex++
		if len(buf) < int(addressValueIndex)+int(addressLength) {
			return nil, fmt.Errorf("invalid domain address length")
		}
		payload.dstHost = string(buf[addressValueIndex : int(addressValueIndex)+int(addressLength)])
		payload.payload = buf[int(addressValueIndex)+int(addressLength):]
		payload.dstHostType = "domain"

	case 3: // IPv6
		if len(buf) < int(addressValueIndex+net.IPv6len) {
			return nil, fmt.Errorf("invalid IPv6 address length")
		}
		payload.dstHost = net.IP(buf[addressValueIndex : addressValueIndex+net.IPv6len]).String()
		payload.payload = buf[addressValueIndex+net.IPv6len:]
		payload.dstHostType = "ipv6"
	default:
		return nil, fmt.Errorf("addressType %d is not supported", addressType)
	}

	return payload, nil
}
Download .txt
gitextract_4c84voe0/

├── .gitattributes
├── .github/
│   └── workflows/
│       └── codeql-analysis.yml
├── .gitignore
├── .travis.yml
├── GeoLite2-Country.mmdb
├── LICENSE
├── Makefile
├── README.md
├── README_zh.md
├── SECURITY.md
├── api/
│   ├── api_cfip.go
│   ├── api_meta.go
│   ├── api_proxy.go
│   └── app.go
├── go.mod
├── go.sum
├── main.go
├── model/
│   ├── config.go
│   ├── db.go
│   ├── helper.go
│   ├── migrate.go
│   ├── t_cfip.go
│   ├── t_meta.go
│   └── t_proxy.go
├── socks5ws/
│   ├── app.go
│   ├── const.go
│   ├── relay_svr.go
│   ├── relay_tcp_direct.go
│   ├── relay_tcp_socks5e.go
│   ├── relay_udp_direct.go
│   ├── socks5_bind.go
│   ├── socks5_connect.go
│   ├── socks5_req.go
│   ├── socks5_udp_associate.go
│   └── websocket.go
└── util/
    ├── browse_open.go
    ├── cf_ip.go
    ├── cf_ip_test.go
    ├── crypt_aes.go
    ├── crypt_aes_test.go
    ├── crypt_des.go
    ├── enable_socks5_darwin.go
    ├── enable_socks5_linux.go
    ├── enable_socks5_windows.go
    ├── geo_ip.go
    ├── geo_ip_test.go
    ├── random_string.go
    └── vless_data.go
Download .txt
SYMBOL INDEX (142 symbols across 34 files)

FILE: api/api_cfip.go
  function apiCfIpInit (line 11) | func apiCfIpInit(w http.ResponseWriter, req *http.Request) {
  function apiCfIpList (line 31) | func apiCfIpList(w http.ResponseWriter, req *http.Request) {
  function apiCfIpUpdate (line 40) | func apiCfIpUpdate(w http.ResponseWriter, req *http.Request) {
  function apiCfIpCreate (line 53) | func apiCfIpCreate(w http.ResponseWriter, req *http.Request) {
  function apiCfIpDelete (line 67) | func apiCfIpDelete(w http.ResponseWriter, req *http.Request) {

FILE: api/api_meta.go
  function responseJson (line 9) | func responseJson(w http.ResponseWriter, code int, data any) {
  function checkErr (line 17) | func checkErr(w http.ResponseWriter, err error) (shouldReturn bool) {
  function apiMeta (line 25) | func apiMeta(w http.ResponseWriter, req *http.Request) {

FILE: api/api_proxy.go
  function apiProxyList (line 10) | func apiProxyList(w http.ResponseWriter, req *http.Request) {
  function apiProxyUpdate (line 19) | func apiProxyUpdate(w http.ResponseWriter, req *http.Request) {
  function apiProxyCreate (line 32) | func apiProxyCreate(w http.ResponseWriter, req *http.Request) {
  function apiProxyDelete (line 46) | func apiProxyDelete(w http.ResponseWriter, req *http.Request) {

FILE: api/app.go
  type apiHandler (line 8) | type apiHandler struct
    method ServeHTTP (line 10) | func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {}
  function AdminServer (line 12) | func AdminServer(addr string) *http.Server {

FILE: main.go
  function main (line 24) | func main() {

FILE: model/config.go
  type Config (line 5) | type Config struct
  function Cfg (line 22) | func Cfg() *Config {

FILE: model/db.go
  function initDb (line 10) | func initDb() {
  function DB (line 19) | func DB() *gorm.DB {

FILE: model/helper.go
  type PaginationQ (line 9) | type PaginationQ struct
    method SearchAll (line 18) | func (p *PaginationQ) SearchAll(queryTx *gorm.DB) (data *PaginationQ, ...
  function crudAll (line 42) | func crudAll(p *PaginationQ, queryTx *gorm.DB, list interface{}) (int64,...
  function crudOne (line 63) | func crudOne(m interface{}) (err error) {
  function crudDelete (line 70) | func crudDelete(m interface{}) (err error) {

FILE: model/migrate.go
  function migrate (line 5) | func migrate() {

FILE: model/t_cfip.go
  type ModelBase (line 8) | type ModelBase struct
  type CfIp (line 15) | type CfIp struct

FILE: model/t_meta.go
  type Meta (line 3) | type Meta struct

FILE: model/t_proxy.go
  type Proxy (line 8) | type Proxy struct
    method IsActive (line 25) | func (p *Proxy) IsActive() bool {
    method RelayURL (line 28) | func (p *Proxy) RelayURL() string {

FILE: socks5ws/app.go
  type ClientLocalSocks5Server (line 17) | type ClientLocalSocks5Server struct
    method fetchActiveProxy (line 37) | func (ss *ClientLocalSocks5Server) fetchActiveProxy() {
    method Run (line 57) | func (ss *ClientLocalSocks5Server) Run(ctx context.Context) {
    method socks5HandShake (line 90) | func (ss *ClientLocalSocks5Server) socks5HandShake(conn net.Conn) error {
    method socks5Request (line 113) | func (ss *ClientLocalSocks5Server) socks5Request(conn net.Conn) (*Sock...
    method handleConnection (line 126) | func (ss *ClientLocalSocks5Server) handleConnection(outerCtx context.C...
    method shouldGoDirect (line 176) | func (ss *ClientLocalSocks5Server) shouldGoDirect(req *Socks5Request) ...
    method dispatchRelayTcpServer (line 186) | func (ss *ClientLocalSocks5Server) dispatchRelayTcpServer(ctx context....
    method pipeTcp (line 194) | func (ss *ClientLocalSocks5Server) pipeTcp(ctx context.Context, s5 net...
  function NewClientLocalSocks5Server (line 24) | func NewClientLocalSocks5Server(addr, geoIpPath string) (*ClientLocalSoc...

FILE: socks5ws/const.go
  constant socks5Version (line 9) | socks5Version             = 0x05
  constant socks5ReplyOkay (line 10) | socks5ReplyOkay           = 0x00
  constant socks5ReplyFail (line 11) | socks5ReplyFail           = 0x01
  constant socks5ReplyReserved (line 12) | socks5ReplyReserved       = 0x00
  constant socks5CmdConnect (line 13) | socks5CmdConnect          = 0x01
  constant socks5CmdBind (line 14) | socks5CmdBind             = 0x02
  constant socks5CmdUdpAssoc (line 15) | socks5CmdUdpAssoc         = 0x03
  constant socks5AtypeIPv4 (line 16) | socks5AtypeIPv4           = 0x01
  constant socks5AtypeDomain (line 17) | socks5AtypeDomain         = 0x03
  constant socks5AtypeIPv6 (line 18) | socks5AtypeIPv6           = 0x04
  constant socks5UdpFragNotSupported (line 19) | socks5UdpFragNotSupported = 0x00
  constant socks5UdpFragEnd (line 20) | socks5UdpFragEnd          = 0x80
  constant bufferSize (line 22) | bufferSize = 64 << 10
  function socks5Response (line 25) | func socks5Response(conn net.Conn, ipv4 net.IP, port int, socks5OkayOrFa...

FILE: socks5ws/relay_svr.go
  type RelayTcp (line 5) | type RelayTcp interface

FILE: socks5ws/relay_tcp_direct.go
  type RelayTcpDirect (line 7) | type RelayTcpDirect struct
    method Read (line 19) | func (r *RelayTcpDirect) Read(p []byte) (n int, err error) {
    method Write (line 23) | func (r *RelayTcpDirect) Write(p []byte) (n int, err error) {
    method Close (line 27) | func (r *RelayTcpDirect) Close() error {
  function NewRelayTcpDirect (line 11) | func NewRelayTcpDirect(req *Socks5Request) (*RelayTcpDirect, error) {

FILE: socks5ws/relay_tcp_socks5e.go
  type RelayTcpSocks5e (line 13) | type RelayTcpSocks5e struct
    method Read (line 31) | func (r RelayTcpSocks5e) Read(data []byte) (n int, err error) {
    method Write (line 42) | func (r RelayTcpSocks5e) Write(data []byte) (n int, err error) {
    method Close (line 53) | func (r RelayTcpSocks5e) Close() error {
  function NewRelayTcpSocks5e (line 19) | func NewRelayTcpSocks5e(ctx context.Context, cfg *model.Proxy, req *Sock...

FILE: socks5ws/relay_udp_direct.go
  type RelayUdpDirect (line 15) | type RelayUdpDirect struct
    method addFragment (line 27) | func (ud *RelayUdpDirect) addFragment(clientAddr *net.UDPAddr, frag *u...
    method startTimer (line 52) | func (ud *RelayUdpDirect) startTimer(ClientDstAddr string) {
    method clientDstAddrAsID (line 64) | func (ud *RelayUdpDirect) clientDstAddrAsID(clientAddr *net.UDPAddr, d...
    method assembleThenPipeUdp (line 67) | func (ud *RelayUdpDirect) assembleThenPipeUdp(clientAddr *net.UDPAddr,...
    method PipeUdp (line 91) | func (ud *RelayUdpDirect) PipeUdp() {
    method segmentPipe (line 112) | func (ud *RelayUdpDirect) segmentPipe(comboPacket *udpPacket, clientAd...
    method Close (line 259) | func (ud *RelayUdpDirect) Close() {
  function NewRelayUdpDirect (line 125) | func NewRelayUdpDirect(s5 net.Conn) (*RelayUdpDirect, error) {
  function forwardUDPData (line 155) | func forwardUDPData(udpPacket *udpPacket) ([]byte, error) {
  type udpPacket (line 175) | type udpPacket struct
    method ResponseData (line 184) | func (p udpPacket) ResponseData(payload []byte) []byte {
    method ip (line 230) | func (p udpPacket) ip() net.IP {
    method port (line 249) | func (p udpPacket) port() int {
    method addr (line 252) | func (p udpPacket) addr() *net.UDPAddr {
    method dstAddr (line 255) | func (p udpPacket) dstAddr() string {
  function parseUDPData (line 191) | func parseUDPData(data []byte) (*udpPacket, error) {

FILE: socks5ws/socks5_bind.go
  function relayBind (line 10) | func relayBind(s5 net.Conn, _ *Socks5Request) {

FILE: socks5ws/socks5_req.go
  type Socks5Request (line 11) | type Socks5Request struct
    method host (line 75) | func (s Socks5Request) host() string {
    method addr (line 87) | func (s Socks5Request) addr() string {
    method cmd (line 90) | func (s Socks5Request) cmd() string {
    method Network (line 102) | func (s Socks5Request) Network() string {
    method aType (line 114) | func (s Socks5Request) aType() string {
    method port (line 118) | func (s Socks5Request) port() string {
    method Logger (line 123) | func (s Socks5Request) Logger() *slog.Logger {
    method String (line 126) | func (s Socks5Request) String() string {
    method addressBytes (line 130) | func (s Socks5Request) addressBytes() []byte {
  function parseSocks5Request (line 20) | func parseSocks5Request(data []byte, geo *util.GeoIP) (*Socks5Request, e...

FILE: socks5ws/websocket.go
  constant browserAgent (line 14) | browserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/53...
  function webSocketConn (line 17) | func webSocketConn(ctx context.Context, proxy *model.Proxy, req *Socks5R...

FILE: util/browse_open.go
  function BrowserOpen (line 8) | func BrowserOpen(url string) error {

FILE: util/cf_ip.go
  type CfIP (line 16) | type CfIP struct
    method IsCf (line 70) | func (ci CfIP) IsCf(ip net.IP) bool {
    method AllIps (line 84) | func (ci CfIP) AllIps(fn func(ip, cidr string)) {
  function singletonCfIP (line 24) | func singletonCfIP() *CfIP {
  function NewCfIP (line 35) | func NewCfIP() (*CfIP, error) {
  function getIPsFromCIDR (line 132) | func getIPsFromCIDR(cidr string) ([]string, error) {
  function inc (line 146) | func inc(ip net.IP) {
  function isReachable (line 155) | func isReachable(ip string, port int) bool {

FILE: util/cf_ip_test.go
  function TestCfIP_CheckReachableIps (line 5) | func TestCfIP_CheckReachableIps(t *testing.T) {

FILE: util/crypt_aes.go
  function AesEncrypt (line 12) | func AesEncrypt(origData []byte, key string) (string, error) {
  function AesDecrypt (line 36) | func AesDecrypt(cryted string, key string) ([]byte, error) {
  function PKCS7Padding (line 63) | func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
  function PKCS7UnPadding (line 70) | func PKCS7UnPadding(origData []byte) []byte {

FILE: util/crypt_aes_test.go
  function TestAesDecryptEn (line 5) | func TestAesDecryptEn(t *testing.T) {

FILE: util/crypt_des.go
  function ZeroPadding (line 10) | func ZeroPadding(ciphertext []byte, blockSize int) []byte {
  function ZeroUnPadding (line 16) | func ZeroUnPadding(origData []byte) []byte {
  function DesEncrypt (line 23) | func DesEncrypt(text string, key []byte) (string, error) {
  function DesDecrypt (line 43) | func DesDecrypt(decrypted string, key []byte) (string, error) {

FILE: util/enable_socks5_darwin.go
  function proxySettingOn (line 10) | func proxySettingOn(socks5Addr string) {
  function proxySettingOff (line 42) | func proxySettingOff() (string, error) {

FILE: util/enable_socks5_linux.go
  function proxySettingOn (line 3) | func proxySettingOn(socks5Addr string) {
  function proxySettingOff (line 6) | func proxySettingOff(socks5Addr string) {

FILE: util/enable_socks5_windows.go
  function proxySettingOn (line 9) | func proxySettingOn(socks5Addr string) {
  function proxySettingOff (line 51) | func proxySettingOff() {

FILE: util/geo_ip.go
  type GeoIP (line 9) | type GeoIP struct
    method Close (line 24) | func (g *GeoIP) Close() error {
    method Country (line 31) | func (g *GeoIP) Country(host string) (isoCountryCode string, err error) {
  function NewGeoIP (line 13) | func NewGeoIP(geoIpFilePath string) (*GeoIP, error) {

FILE: util/geo_ip_test.go
  function TestGeoDns_country (line 7) | func TestGeoDns_country(t *testing.T) {

FILE: util/random_string.go
  function RandomString (line 27) | func RandomString(n int) string {
  function RandStringWordL (line 35) | func RandStringWordL(n int) string {
  function RandStringWordU (line 43) | func RandStringWordU(n int) string {
  function RandStringWordC (line 50) | func RandStringWordC(n int) string {
  function RandStringDigit (line 57) | func RandStringDigit(n int) string {

FILE: util/vless_data.go
  type SchemaVLESS (line 12) | type SchemaVLESS struct
    method UUID (line 22) | func (h SchemaVLESS) UUID() string {
    method DataUdp (line 26) | func (h SchemaVLESS) DataUdp() []byte {
    method DataTcp (line 46) | func (h SchemaVLESS) DataTcp() []byte {
    method AddrUdp (line 50) | func (h SchemaVLESS) AddrUdp() *net.UDPAddr {
    method HostIP (line 53) | func (h SchemaVLESS) HostIP() net.IP {
    method HostPort (line 69) | func (h SchemaVLESS) HostPort() string {
    method Logger (line 72) | func (h SchemaVLESS) Logger() *slog.Logger {
  function VlessParse (line 77) | func VlessParse(buf []byte) (*SchemaVLESS, error) {
Condensed preview — 48 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (79K chars).
[
  {
    "path": ".gitattributes",
    "chars": 48,
    "preview": "* linguist-vendored\n*.go linguist-vendored=false"
  },
  {
    "path": ".github/workflows/codeql-analysis.yml",
    "chars": 2432,
    "preview": "# For most projects, this workflow file will not need changing; you simply need\n# to commit it to your repository.\n#\n# Y"
  },
  {
    "path": ".gitignore",
    "chars": 103,
    "preview": "felix\n.idea\nbuilds\nbuilds/*\ntest*\n_build*\n*.exe\nrelease\ndist\n_book\n_release\n.vscode\n_nes\ndist/\n*sqlite3"
  },
  {
    "path": ".travis.yml",
    "chars": 296,
    "preview": "language: go\nos:\n  - linux\n  - osx\n\n\nmatrix:\n  fast_finish: true\n  include:\n    - go: 1.12.x\n      env: CGO_ENABLED=0 GO"
  },
  {
    "path": "LICENSE",
    "chars": 11358,
    "preview": "\n                                 Apache License\n                           Version 2.0, January 2004\n                  "
  },
  {
    "path": "Makefile",
    "chars": 1071,
    "preview": "LDFLAGS := \"-s -w -X main.buildTime=$(shell date -u '+%Y-%m-%dT%I:%M:%S%p') -X main.gitHash=$(shell git rev-parse HEAD)\""
  },
  {
    "path": "README.md",
    "chars": 27,
    "preview": "# Felix [中文](README_zh.md)\n"
  },
  {
    "path": "README_zh.md",
    "chars": 120,
    "preview": "# Felix\n[![Build Status](https://travis-ci.org/libragen/felix.svg?branch=master)](https://travis-ci.org/libragen/felix)\n"
  },
  {
    "path": "SECURITY.md",
    "chars": 619,
    "preview": "# Security Policy\n\n## Supported Versions\n\nUse this section to tell people about which versions of your project are\ncurre"
  },
  {
    "path": "api/api_cfip.go",
    "chars": 1672,
    "preview": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/mojocn/felix/model\"\n\t\"github.com/mojocn/felix/util\"\n\t\"net/htt"
  },
  {
    "path": "api/api_meta.go",
    "chars": 706,
    "preview": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"github.com/mojocn/felix/model\"\n\t\"net/http\"\n)\n\nfunc responseJson(w http.Response"
  },
  {
    "path": "api/api_proxy.go",
    "chars": 1238,
    "preview": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/mojocn/felix/model\"\n\t\"net/http\"\n)\n\nfunc apiProxyList(w http.R"
  },
  {
    "path": "api/app.go",
    "chars": 884,
    "preview": "package api\n\nimport (\n\t\"log\"\n\t\"net/http\"\n)\n\ntype apiHandler struct{}\n\nfunc (apiHandler) ServeHTTP(http.ResponseWriter, *"
  },
  {
    "path": "go.mod",
    "chars": 494,
    "preview": "module github.com/mojocn/felix\n\ngo 1.22\n\nrequire (\n\tgithub.com/google/uuid v1.6.0\n\tgithub.com/gorilla/websocket v1.5.3\n\t"
  },
  {
    "path": "go.sum",
    "chars": 2519,
    "preview": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.m"
  },
  {
    "path": "main.go",
    "chars": 1523,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"github.com/mojocn/felix/api\"\n\t\"github.com/mojocn/felix/model\"\n\t\"github.com/mo"
  },
  {
    "path": "model/config.go",
    "chars": 578,
    "preview": "package model\n\nimport \"log/slog\"\n\ntype Config struct {\n\tPortSocks5 int    `json:\"port_socks5\"`\n\tPortHttp   int    `json:"
  },
  {
    "path": "model/db.go",
    "chars": 349,
    "preview": "package model\n\nimport (\n\t\"gorm.io/driver/sqlite\" // Sqlite driver based on CGO\n\t\"gorm.io/gorm\"\n)\n\nvar db *gorm.DB\n\nfunc "
  },
  {
    "path": "model/helper.go",
    "chars": 2004,
    "preview": "package model\n\nimport (\n\t\"errors\"\n\t\"gorm.io/gorm\"\n)\n\n// PaginationQ gin handler query binding struct\ntype PaginationQ st"
  },
  {
    "path": "model/migrate.go",
    "chars": 233,
    "preview": "package model\n\nimport \"log\"\n\nfunc migrate() {\n\tif db == nil {\n\t\tlog.Print(\"db is nil\")\n\t\treturn\n\t}\n\tfor _, m := range []"
  },
  {
    "path": "model/t_cfip.go",
    "chars": 492,
    "preview": "package model\n\nimport (\n\t\"gorm.io/gorm\"\n\t\"time\"\n)\n\ntype ModelBase struct {\n\tID        uint           `gorm:\"primarykey\" "
  },
  {
    "path": "model/t_meta.go",
    "chars": 111,
    "preview": "package model\n\ntype Meta struct {\n\tModelBase\n\tConfig Config `json:\"config\" gorm:\"type:json;serializer:json\"`\n}\n"
  },
  {
    "path": "model/t_proxy.go",
    "chars": 1109,
    "preview": "package model\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Proxy struct {\n\tModelBase\n\tName string `json:\"name\" gorm:\"varchar(255)"
  },
  {
    "path": "socks5ws/app.go",
    "chars": 6511,
    "preview": "package socks5ws\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/mojocn/felix/model\"\n\t\"github.com/mojocn/felix/util\"\n"
  },
  {
    "path": "socks5ws/const.go",
    "chars": 1030,
    "preview": "package socks5ws\n\nimport (\n\t\"log/slog\"\n\t\"net\"\n)\n\nconst (\n\tsocks5Version             = 0x05\n\tsocks5ReplyOkay           = "
  },
  {
    "path": "socks5ws/relay_svr.go",
    "chars": 92,
    "preview": "package socks5ws\n\nimport \"io\"\n\ntype RelayTcp interface {\n\tio.Reader\n\tio.Writer\n\tio.Closer\n}\n"
  },
  {
    "path": "socks5ws/relay_tcp_direct.go",
    "chars": 556,
    "preview": "package socks5ws\n\nimport \"net\"\n\nvar _ RelayTcp = (*RelayTcpDirect)(nil)\n\ntype RelayTcpDirect struct {\n\tconn net.Conn\n}\n\n"
  },
  {
    "path": "socks5ws/relay_tcp_socks5e.go",
    "chars": 1494,
    "preview": "package socks5ws\n\nimport (\n\t\"context\"\n\t\"github.com/gorilla/websocket\"\n\t\"github.com/mojocn/felix/model\"\n\t\"log/slog\"\n\t\"tim"
  },
  {
    "path": "socks5ws/relay_udp_direct.go",
    "chars": 7332,
    "preview": "package socks5ws\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"log/slog\"\n\t\"net\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype RelayUdpDire"
  },
  {
    "path": "socks5ws/socks5_bind.go",
    "chars": 1049,
    "preview": "package socks5ws\n\nimport (\n\t\"io\"\n\t\"log/slog\"\n\t\"net\"\n\t\"sync\"\n)\n\nfunc relayBind(s5 net.Conn, _ *Socks5Request) {\n\tbindList"
  },
  {
    "path": "socks5ws/socks5_connect.go",
    "chars": 17,
    "preview": "package socks5ws\n"
  },
  {
    "path": "socks5ws/socks5_req.go",
    "chars": 3542,
    "preview": "package socks5ws\n\nimport (\n\t\"fmt\"\n\t\"github.com/google/uuid\"\n\t\"github.com/mojocn/felix/util\"\n\t\"log/slog\"\n\t\"net\"\n)\n\ntype S"
  },
  {
    "path": "socks5ws/socks5_udp_associate.go",
    "chars": 17,
    "preview": "package socks5ws\n"
  },
  {
    "path": "socks5ws/websocket.go",
    "chars": 1401,
    "preview": "package socks5ws\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"github.com/gorilla/websocket\"\n\t\"github.com/mojocn/felix/mod"
  },
  {
    "path": "util/browse_open.go",
    "chars": 385,
    "preview": "package util\n\nimport (\n\t\"os/exec\"\n\t\"runtime\"\n)\n\nfunc BrowserOpen(url string) error {\n\tvar cmd string\n\tvar args []string\n"
  },
  {
    "path": "util/cf_ip.go",
    "chars": 3573,
    "preview": "package util\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\n//https://api.cloudflare.com/c"
  },
  {
    "path": "util/cf_ip_test.go",
    "chars": 83,
    "preview": "package util\n\nimport \"testing\"\n\nfunc TestCfIP_CheckReachableIps(t *testing.T) {\n\n}\n"
  },
  {
    "path": "util/crypt_aes.go",
    "chars": 1578,
    "preview": "package util\n\nimport (\n\t\"bytes\"\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"encoding/base64\"\n)\n\n//https://tech.mojotv.cn/2019/06/28"
  },
  {
    "path": "util/crypt_aes_test.go",
    "chars": 329,
    "preview": "package util\n\nimport \"testing\"\n\nfunc TestAesDecryptEn(t *testing.T) {\n\tkey := RandStringWordC(32)\n\n\tmsg := RandomString("
  },
  {
    "path": "util/crypt_des.go",
    "chars": 1375,
    "preview": "package util\n\nimport (\n\t\"bytes\"\n\t\"crypto/des\"\n\t\"encoding/hex\"\n\t\"errors\"\n)\n\nfunc ZeroPadding(ciphertext []byte, blockSize"
  },
  {
    "path": "util/enable_socks5_darwin.go",
    "chars": 1884,
    "preview": "package util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os/exec\"\n\t\"strings\"\n)\n\nfunc proxySettingOn(socks5Addr string) {\n\tnetworkService"
  },
  {
    "path": "util/enable_socks5_linux.go",
    "chars": 103,
    "preview": "package util\n\nfunc proxySettingOn(socks5Addr string) {\n\n}\nfunc proxySettingOff(socks5Addr string) {\n\n}\n"
  },
  {
    "path": "util/enable_socks5_windows.go",
    "chars": 2364,
    "preview": "package util\n\nimport (\n\t\"fmt\"\n\t\"golang.org/x/sys/windows/registry\"\n\t\"log\"\n)\n\nfunc proxySettingOn(socks5Addr string) {\n\t/"
  },
  {
    "path": "util/geo_ip.go",
    "chars": 1037,
    "preview": "package util\n\nimport (\n\t\"fmt\"\n\t\"github.com/oschwald/geoip2-golang\"\n\t\"net\"\n)\n\ntype GeoIP struct {\n\tdb *geoip2.Reader\n}\n\nf"
  },
  {
    "path": "util/geo_ip_test.go",
    "chars": 80,
    "preview": "package util\n\nimport (\n\t\"testing\"\n)\n\nfunc TestGeoDns_country(t *testing.T) {\n\n}\n"
  },
  {
    "path": "util/random_string.go",
    "chars": 1338,
    "preview": "package util\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\nvar (\n\tstringMisc = []byte(\".$#@&*_\")\n\n\tstringDigit    = []byte(\"123456789"
  },
  {
    "path": "util/vless_data.go",
    "chars": 3796,
    "preview": "package util\n\nimport (\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/google/uuid\"\n\t\"log/slog\"\n\t\"net\"\n)\n\ntype SchemaVL"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the dejavuzhou/felix GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 48 files (69.3 KB), approximately 22.2k tokens, and a symbol index with 142 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!