├── .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 /.gitattributes: -------------------------------------------------------------------------------- 1 | * linguist-vendored 2 | *.go linguist-vendored=false -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ master ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ master ] 20 | schedule: 21 | - cron: '29 4 * * 2' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'go' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 37 | # Learn more: 38 | # 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 39 | 40 | steps: 41 | - name: Checkout repository 42 | uses: actions/checkout@v2 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | felix 2 | .idea 3 | builds 4 | builds/* 5 | test* 6 | _build* 7 | *.exe 8 | release 9 | dist 10 | _book 11 | _release 12 | .vscode 13 | _nes 14 | dist/ 15 | *sqlite3 -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | os: 3 | - linux 4 | - osx 5 | 6 | 7 | matrix: 8 | fast_finish: true 9 | include: 10 | - go: 1.12.x 11 | env: CGO_ENABLED=0 GO111MODULE=on 12 | \ 13 | 14 | git: 15 | depth: 1 16 | 17 | 18 | before_install: 19 | - go build 20 | script: 21 | - ./felix sshw 22 | 23 | notifications: 24 | email: 25 | recipients: 26 | - neochau@gmail.com 27 | on_success: never -------------------------------------------------------------------------------- /GeoLite2-Country.mmdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mojocn/felix/9e5c6c4794497fcd799fb7d86989cb8263609175/GeoLite2-Country.mmdb -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | LDFLAGS := "-s -w -X main.buildTime=$(shell date -u '+%Y-%m-%dT%I:%M:%S%p') -X main.gitHash=$(shell git rev-parse HEAD)" 2 | GO ?= go 3 | GOFMT ?= gofmt "-s" 4 | PACKAGES ?= $(shell $(GO) list ./... | grep -v /vendor/) 5 | VETPACKAGES ?= $(shell $(GO) list ./... | grep -v /vendor/ | grep -v /examples/) 6 | GOFILES := $(shell find . -name "*.go" -type f -not -path "./vendor/*") 7 | 8 | 9 | run: install 10 | ./build/felix -V 11 | install: 12 | go install -ldflags $(LDFLAGS) 13 | vuejs: 14 | felix ginbin -s dist -p felixbin 15 | 16 | build:vuejs 17 | go build -race -ldflags $(LDFLAGS) -o build/felix *.go 18 | 19 | release:vuejs 20 | 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 21 | CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -ldflags $(LDFLAGS) -o _release/felix-amd64-linux *.go 22 | CGO_ENABLED=1 GOOS=linux GOARCH=arm go build -ldflags $(LDFLAGS) -o _release/felix-amd64-linux-arm *.go 23 | CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 go build -ldflags $(LDFLAGS) -o _release/felix-amd64-darwin *.go 24 | 25 | 26 | .PHONY: release 27 | 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Felix [中文](README_zh.md) 2 | -------------------------------------------------------------------------------- /README_zh.md: -------------------------------------------------------------------------------- 1 | # Felix 2 | [![Build Status](https://travis-ci.org/libragen/felix.svg?branch=master)](https://travis-ci.org/libragen/felix) 3 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Use this section to tell people about which versions of your project are 6 | currently being supported with security updates. 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | 5.1.x | :white_check_mark: | 11 | | 5.0.x | :x: | 12 | | 4.0.x | :white_check_mark: | 13 | | < 4.0 | :x: | 14 | 15 | ## Reporting a Vulnerability 16 | 17 | Use this section to tell people how to report a vulnerability. 18 | 19 | Tell them where to go, how often they can expect to get an update on a 20 | reported vulnerability, what to expect if the vulnerability is accepted or 21 | declined, etc. 22 | -------------------------------------------------------------------------------- /api/api_cfip.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/mojocn/felix/model" 7 | "github.com/mojocn/felix/util" 8 | "net/http" 9 | ) 10 | 11 | func apiCfIpInit(w http.ResponseWriter, req *http.Request) { 12 | client, err := util.NewCfIP() 13 | if checkErr(w, err) { 14 | return 15 | } 16 | var rows []model.CfIp 17 | client.AllIps(func(ip, cidr string) { 18 | ins := model.CfIp{ 19 | IP: ip, 20 | Cidr: cidr, 21 | } 22 | rows = append(rows, ins) 23 | }) 24 | err = model.DB().CreateInBatches(rows, 200).Error 25 | if checkErr(w, err) { 26 | return 27 | } 28 | responseJson(w, http.StatusOK, "ok") 29 | } 30 | 31 | func apiCfIpList(w http.ResponseWriter, req *http.Request) { 32 | var rows []model.CfIp 33 | err := model.DB().Limit(100).Find(&rows).Error 34 | if checkErr(w, err) { 35 | return 36 | } 37 | responseJson(w, http.StatusOK, rows) 38 | } 39 | 40 | func apiCfIpUpdate(w http.ResponseWriter, req *http.Request) { 41 | ins := new(model.CfIp) 42 | err := json.NewDecoder(req.Body).Decode(ins) 43 | if checkErr(w, err) { 44 | return 45 | } 46 | err = model.DB().Save(ins).Error 47 | if checkErr(w, err) { 48 | return 49 | } 50 | responseJson(w, http.StatusOK, ins) 51 | } 52 | 53 | func apiCfIpCreate(w http.ResponseWriter, req *http.Request) { 54 | ins := new(model.CfIp) 55 | err := json.NewDecoder(req.Body).Decode(ins) 56 | if checkErr(w, err) { 57 | return 58 | } 59 | ins.ID = 0 60 | err = model.DB().Save(ins).Error 61 | if checkErr(w, err) { 62 | return 63 | } 64 | responseJson(w, http.StatusOK, ins) 65 | } 66 | 67 | func apiCfIpDelete(w http.ResponseWriter, req *http.Request) { 68 | ins := new(model.CfIp) 69 | err := json.NewDecoder(req.Body).Decode(ins) 70 | if checkErr(w, err) { 71 | return 72 | } 73 | if ins.ID == 0 { 74 | err = fmt.Errorf("id can not be 0") 75 | } 76 | if checkErr(w, err) { 77 | return 78 | } 79 | err = model.DB().Delete(ins).Error 80 | if checkErr(w, err) { 81 | return 82 | } 83 | responseJson(w, http.StatusOK, ins) 84 | } 85 | -------------------------------------------------------------------------------- /api/api_meta.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/mojocn/felix/model" 6 | "net/http" 7 | ) 8 | 9 | func responseJson(w http.ResponseWriter, code int, data any) { 10 | w.Header().Set("Content-Type", "application/json") 11 | w.WriteHeader(code) 12 | err := json.NewEncoder(w).Encode(data) 13 | if err != nil { 14 | http.Error(w, err.Error(), http.StatusInternalServerError) 15 | } 16 | } 17 | func checkErr(w http.ResponseWriter, err error) (shouldReturn bool) { 18 | if err != nil { 19 | http.Error(w, err.Error(), http.StatusTeapot) 20 | return true 21 | } 22 | return false 23 | } 24 | 25 | func apiMeta(w http.ResponseWriter, req *http.Request) { 26 | row := new(model.Meta) 27 | err := model.DB().First(row).Error 28 | if checkErr(w, err) { 29 | return 30 | } 31 | responseJson(w, http.StatusOK, row) 32 | } 33 | -------------------------------------------------------------------------------- /api/api_proxy.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/mojocn/felix/model" 7 | "net/http" 8 | ) 9 | 10 | func apiProxyList(w http.ResponseWriter, req *http.Request) { 11 | rows := []model.Proxy{} 12 | err := model.DB().Find(&rows).Error 13 | if checkErr(w, err) { 14 | return 15 | } 16 | responseJson(w, http.StatusOK, rows) 17 | } 18 | 19 | func apiProxyUpdate(w http.ResponseWriter, req *http.Request) { 20 | ins := new(model.Proxy) 21 | err := json.NewDecoder(req.Body).Decode(ins) 22 | if checkErr(w, err) { 23 | return 24 | } 25 | err = model.DB().Save(ins).Error 26 | if checkErr(w, err) { 27 | return 28 | } 29 | responseJson(w, http.StatusOK, ins) 30 | } 31 | 32 | func apiProxyCreate(w http.ResponseWriter, req *http.Request) { 33 | ins := new(model.Proxy) 34 | err := json.NewDecoder(req.Body).Decode(ins) 35 | if checkErr(w, err) { 36 | return 37 | } 38 | ins.ID = 0 39 | err = model.DB().Save(ins).Error 40 | if checkErr(w, err) { 41 | return 42 | } 43 | responseJson(w, http.StatusOK, ins) 44 | } 45 | 46 | func apiProxyDelete(w http.ResponseWriter, req *http.Request) { 47 | ins := new(model.Proxy) 48 | err := json.NewDecoder(req.Body).Decode(ins) 49 | if checkErr(w, err) { 50 | return 51 | } 52 | if ins.ID == 0 { 53 | err = fmt.Errorf("id can not be 0") 54 | } 55 | if checkErr(w, err) { 56 | return 57 | } 58 | err = model.DB().Delete(ins).Error 59 | if checkErr(w, err) { 60 | return 61 | } 62 | responseJson(w, http.StatusOK, ins) 63 | } 64 | -------------------------------------------------------------------------------- /api/app.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | ) 7 | 8 | type apiHandler struct{} 9 | 10 | func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {} 11 | 12 | func AdminServer(addr string) *http.Server { 13 | log.Println("http api server starting on", addr) 14 | mux := http.NewServeMux() 15 | mux.Handle("/api/foo", apiHandler{}) 16 | mux.HandleFunc("GET /api/meta", apiMeta) 17 | 18 | mux.HandleFunc("GET /api/proxies", apiProxyList) 19 | mux.HandleFunc("PATCH /api/proxies", apiProxyUpdate) 20 | mux.HandleFunc("POST /api/proxies", apiProxyCreate) 21 | mux.HandleFunc("DELETE /api/proxies", apiProxyDelete) 22 | 23 | mux.HandleFunc("GET /api/cfip-init", apiCfIpInit) 24 | mux.HandleFunc("GET /api/cfips", apiCfIpList) 25 | mux.HandleFunc("PATCH /api/cfips", apiCfIpUpdate) 26 | mux.HandleFunc("POST /api/cfips", apiCfIpCreate) 27 | mux.HandleFunc("DELETE /api/cfips", apiCfIpDelete) 28 | 29 | server := &http.Server{ 30 | Addr: addr, 31 | Handler: mux, 32 | } 33 | return server 34 | } 35 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/mojocn/felix 2 | 3 | go 1.22 4 | 5 | require ( 6 | github.com/google/uuid v1.6.0 7 | github.com/gorilla/websocket v1.5.3 8 | github.com/oschwald/geoip2-golang v1.11.0 9 | golang.org/x/sys v0.27.0 10 | gorm.io/driver/sqlite v1.5.6 11 | gorm.io/gorm v1.25.12 12 | ) 13 | 14 | require ( 15 | github.com/jinzhu/inflection v1.0.0 // indirect 16 | github.com/jinzhu/now v1.1.5 // indirect 17 | github.com/mattn/go-sqlite3 v1.14.22 // indirect 18 | github.com/oschwald/maxminddb-golang v1.13.0 // indirect 19 | golang.org/x/text v0.20.0 // indirect 20 | ) 21 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 4 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 5 | github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= 6 | github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 7 | github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= 8 | github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= 9 | github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= 10 | github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= 11 | github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= 12 | github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= 13 | github.com/oschwald/geoip2-golang v1.11.0 h1:hNENhCn1Uyzhf9PTmquXENiWS6AlxAEnBII6r8krA3w= 14 | github.com/oschwald/geoip2-golang v1.11.0/go.mod h1:P9zG+54KPEFOliZ29i7SeYZ/GM6tfEL+rgSn03hYuUo= 15 | github.com/oschwald/maxminddb-golang v1.13.0 h1:R8xBorY71s84yO06NgTmQvqvTvlS/bnYZrrWX1MElnU= 16 | github.com/oschwald/maxminddb-golang v1.13.0/go.mod h1:BU0z8BfFVhi1LQaonTwwGQlsHUEu9pWNdMfmq4ztm0o= 17 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 18 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 19 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 20 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 21 | golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s= 22 | golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 23 | golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug= 24 | golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4= 25 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 26 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 27 | gorm.io/driver/sqlite v1.5.6 h1:fO/X46qn5NUEEOZtnjJRWRzZMe8nqJiQ9E+0hi+hKQE= 28 | gorm.io/driver/sqlite v1.5.6/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4= 29 | gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8= 30 | gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ= 31 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "github.com/mojocn/felix/api" 7 | "github.com/mojocn/felix/model" 8 | "github.com/mojocn/felix/socks5ws" 9 | "log" 10 | "log/slog" 11 | "os" 12 | "os/signal" 13 | "syscall" 14 | "time" 15 | ) 16 | 17 | var ( 18 | buildTime, gitHash string 19 | userUUID = "53881505-c10c-464a-8949-e57184a576a9" 20 | url = "ws://demo.libragen.cn/5sdfasdf" 21 | protocol = "socks5e" // or vless 22 | ) 23 | 24 | func main() { 25 | log.SetFlags(log.Lmicroseconds | log.Lshortfile) 26 | slog.SetLogLoggerLevel(slog.LevelDebug) 27 | 28 | model.DB() 29 | appCfg := model.Cfg() 30 | 31 | app, err := socks5ws.NewClientLocalSocks5Server(fmt.Sprintf("127.0.0.1:%d", appCfg.PortSocks5), "GeoLite2-Country.mmdb") 32 | if err != nil { 33 | log.Fatal(err) 34 | } 35 | 36 | slog.With("socks5", app.AddrSocks5).Info("socks5 server listening on") 37 | 38 | ctx, cancel := context.WithCancel(context.Background()) 39 | signalChan := make(chan os.Signal, 1) 40 | signal.Notify(signalChan, syscall.SIGINT, syscall.SIGABRT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGKILL) 41 | 42 | httpS := api.AdminServer(fmt.Sprintf("127.0.0.1:%d", appCfg.PortHttp)) 43 | go func() { 44 | if err := httpS.ListenAndServe(); err != nil { 45 | log.Fatal(err) 46 | } 47 | }() 48 | 49 | go func() { 50 | sig := <-signalChan 51 | fmt.Printf("\nReceived signal: %s\n", sig) 52 | cancel() // Cancel the context 53 | 54 | // Shutdown the server with a timeout 55 | shutdownCtx, shutdownCancel := context.WithTimeout(ctx, 2*time.Second) 56 | defer shutdownCancel() 57 | if err := httpS.Shutdown(shutdownCtx); err != nil { 58 | log.Fatalf("Server Shutdown Failed:%+v", err) 59 | } 60 | }() 61 | 62 | app.Run(ctx) 63 | } 64 | -------------------------------------------------------------------------------- /model/config.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import "log/slog" 4 | 5 | type Config struct { 6 | PortSocks5 int `json:"port_socks5"` 7 | PortHttp int `json:"port_http"` 8 | AuthUser string `json:"auth_user"` 9 | AuthPass string `json:"auth_pass"` 10 | } 11 | 12 | var ( 13 | cfg *Config 14 | defCfg = Config{ 15 | PortSocks5: 1080, 16 | PortHttp: 1080 + 5, 17 | AuthUser: "admin", 18 | AuthPass: "admin", 19 | } 20 | ) 21 | 22 | func Cfg() *Config { 23 | if cfg == nil { 24 | row := new(Meta) 25 | row.Config = defCfg 26 | err := db.FirstOrCreate(&row).Error 27 | if err != nil { 28 | slog.Error("get config error", "err", err) 29 | } else { 30 | cfg = &defCfg 31 | } 32 | } 33 | return cfg 34 | } 35 | -------------------------------------------------------------------------------- /model/db.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "gorm.io/driver/sqlite" // Sqlite driver based on CGO 5 | "gorm.io/gorm" 6 | ) 7 | 8 | var db *gorm.DB 9 | 10 | func initDb() { 11 | var err error 12 | db, err = gorm.Open(sqlite.Open("felix.sqlite3"), &gorm.Config{}) 13 | if err != nil { 14 | panic("failed to connect database") 15 | } 16 | migrate() 17 | } 18 | 19 | func DB() *gorm.DB { 20 | if db == nil { 21 | initDb() 22 | } 23 | return db 24 | } 25 | -------------------------------------------------------------------------------- /model/helper.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "errors" 5 | "gorm.io/gorm" 6 | ) 7 | 8 | // PaginationQ gin handler query binding struct 9 | type PaginationQ struct { 10 | Ok bool `json:"ok"` 11 | Size int `form:"size" json:"size"` 12 | Page int `form:"page" json:"page"` 13 | Data interface{} `json:"data" comment:"muster be a pointer of slice gorm.Model"` // save pagination list 14 | Total int64 `json:"total"` 15 | } 16 | 17 | // SearchAll optimized pagination method for gorm 18 | func (p *PaginationQ) SearchAll(queryTx *gorm.DB) (data *PaginationQ, err error) { 19 | //99999 magic number for get all list without pagination 20 | if p.Size == 9999 || p.Size == 99999 { 21 | err = queryTx.Find(p.Data).Error 22 | p.Ok = err == nil 23 | return p, err 24 | } 25 | 26 | if p.Size < 1 { 27 | p.Size = 10 28 | } 29 | if p.Page < 1 { 30 | p.Page = 1 31 | } 32 | offset := p.Size * (p.Page - 1) 33 | err = queryTx.Count(&p.Total).Error 34 | if err != nil { 35 | return p, err 36 | } 37 | err = queryTx.Limit(p.Size).Offset(offset).Find(p.Data).Error 38 | p.Ok = err == nil 39 | return p, err 40 | } 41 | 42 | func crudAll(p *PaginationQ, queryTx *gorm.DB, list interface{}) (int64, error) { 43 | if p.Size < 1 { 44 | p.Size = 10 45 | } 46 | if p.Page < 1 { 47 | p.Page = 1 48 | } 49 | 50 | var total int64 51 | err := queryTx.Count(&total).Error 52 | if err != nil { 53 | return 0, err 54 | } 55 | offset := p.Size * (p.Page - 1) 56 | err = queryTx.Limit(p.Size).Offset(offset).Find(list).Error 57 | if err != nil { 58 | return 0, err 59 | } 60 | return total, err 61 | } 62 | 63 | func crudOne(m interface{}) (err error) { 64 | if err := db.First(m).Error; errors.Is(err, gorm.ErrRecordNotFound) { 65 | return errors.New("resource is not found") 66 | } 67 | return nil 68 | } 69 | 70 | func crudDelete(m interface{}) (err error) { 71 | //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 72 | //primary key must be not zero value 73 | db := db.Unscoped().Delete(m) 74 | if err = db.Error; err != nil { 75 | return 76 | } 77 | if db.RowsAffected != 1 { 78 | return errors.New("resource is not found to destroy") 79 | } 80 | return nil 81 | } 82 | -------------------------------------------------------------------------------- /model/migrate.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import "log" 4 | 5 | func migrate() { 6 | if db == nil { 7 | log.Print("db is nil") 8 | return 9 | } 10 | for _, m := range []interface{}{&CfIp{}, &Meta{}, &Proxy{}} { 11 | if err := db.AutoMigrate(m); err != nil { 12 | log.Print(err) 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /model/t_cfip.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "gorm.io/gorm" 5 | "time" 6 | ) 7 | 8 | type ModelBase struct { 9 | ID uint `gorm:"primarykey" json:"id"` 10 | CreatedAt time.Time `json:"created_at"` 11 | UpdatedAt time.Time `json:"updated_at"` 12 | DeletedAt gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index"` 13 | } 14 | 15 | type CfIp struct { 16 | ModelBase 17 | IP string `json:"ip" gorm:"type:varchar(15)"` 18 | Cidr string `json:"cidr" gorm:"type:varchar(18)"` 19 | Ports []int `json:"ports" gorm:"type:json;serializer:json"` 20 | } 21 | -------------------------------------------------------------------------------- /model/t_meta.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | type Meta struct { 4 | ModelBase 5 | Config Config `json:"config" gorm:"type:json;serializer:json"` 6 | } 7 | -------------------------------------------------------------------------------- /model/t_proxy.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | type Proxy struct { 9 | ModelBase 10 | Name string `json:"name" gorm:"varchar(255)"` 11 | 12 | Protocol string `json:"protocol" gorm:"varchar(16)"` //ws,wss,http2,tls,http3 13 | Host string `json:"host" gorm:"varchar(255)"` 14 | Uri string `json:"uri" gorm:"varchar(255)"` 15 | Sni string `json:"sni" gorm:"varchar(255)"` 16 | Version string `json:"version" gorm:"varchar(16)"` // one socks5 17 | 18 | UserID string `json:"user_id"` 19 | Password string `json:"password"` 20 | TrafficKb int64 `json:"traffic_kb" gorm:"default:0"` 21 | SpeedMs int64 `json:"speed_ms" gorm:"default:0"` 22 | Status string `json:"status" gorm:"varchar(16);default:''"` //active, inactive 23 | } 24 | 25 | func (p *Proxy) IsActive() bool { 26 | return p.Status == "active" 27 | } 28 | func (p *Proxy) RelayURL() string { 29 | switch p.Protocol { 30 | case "ws": 31 | return fmt.Sprintf("ws://%s/%s", p.Host, strings.TrimPrefix(p.Uri, "/")) 32 | case "wss": 33 | return fmt.Sprintf("wss://%s/%s", p.Host, strings.TrimPrefix(p.Uri, "/")) 34 | case "tcp+tls": 35 | return fmt.Sprintf("tcp-tls://%s/%s", p.Host, strings.TrimPrefix(p.Uri, "/")) 36 | default: 37 | return "" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /socks5ws/app.go: -------------------------------------------------------------------------------- 1 | package socks5ws 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "fmt" 7 | "github.com/mojocn/felix/model" 8 | "github.com/mojocn/felix/util" 9 | "io" 10 | "log" 11 | "log/slog" 12 | "net" 13 | "sync" 14 | "time" 15 | ) 16 | 17 | type ClientLocalSocks5Server struct { 18 | AddrSocks5 string 19 | geo *util.GeoIP 20 | Timeout time.Duration 21 | proxy *model.Proxy 22 | } 23 | 24 | func NewClientLocalSocks5Server(addr, geoIpPath string) (*ClientLocalSocks5Server, error) { 25 | geo, err := util.NewGeoIP(geoIpPath) 26 | if err != nil { 27 | return nil, err 28 | } 29 | return &ClientLocalSocks5Server{ 30 | AddrSocks5: addr, 31 | geo: geo, 32 | Timeout: 5 * time.Minute, 33 | }, nil 34 | 35 | } 36 | 37 | func (ss *ClientLocalSocks5Server) fetchActiveProxy() { 38 | var proxies []model.Proxy 39 | err := model.DB().Find(&proxies).Error 40 | if err != nil { 41 | slog.Error("failed to get proxy setting", "err", err.Error()) 42 | return 43 | } 44 | if len(proxies) == 0 { 45 | slog.Error("no proxy setting found") 46 | return 47 | } 48 | ss.proxy = &proxies[0] 49 | for _, proxy := range proxies { 50 | if proxy.IsActive() { 51 | ss.proxy = &proxy 52 | break 53 | } 54 | } 55 | } 56 | 57 | func (ss *ClientLocalSocks5Server) Run(ctx context.Context) { 58 | ss.fetchActiveProxy() 59 | 60 | listener, err := net.Listen("tcp", ss.AddrSocks5) 61 | if err != nil { 62 | listener, err = net.Listen("tcp4", "127.0.0.1:0") 63 | } 64 | if err != nil { 65 | log.Fatalf("Failed to listen on %s: %v", ss.AddrSocks5, err) 66 | } 67 | ss.AddrSocks5 = listener.Addr().String() 68 | slog.Info("socks5 server listening on", "addr", ss.AddrSocks5) 69 | 70 | defer listener.Close() 71 | log.Println("SOCKS5 server listening on: " + ss.AddrSocks5) 72 | //proxySettingOn(ss.AddrSocks5) 73 | //defer proxySettingOff() 74 | for { 75 | select { 76 | case <-ctx.Done(): 77 | log.Println("socks5 server exit") 78 | return 79 | default: 80 | conn, err := listener.Accept() 81 | if err != nil { 82 | log.Printf("Failed to accept connection: %v", err) 83 | continue 84 | } 85 | go ss.handleConnection(ctx, conn) 86 | } 87 | } 88 | } 89 | 90 | func (ss *ClientLocalSocks5Server) socks5HandShake(conn net.Conn) error { 91 | buf := make([]byte, 2) 92 | if _, err := io.ReadFull(conn, buf); err != nil { 93 | return fmt.Errorf("failed to read version and nmethods: %w", err) 94 | } 95 | if buf[0] != socks5Version { 96 | return fmt.Errorf("socks5 only. unsupported SOCKS version: %d", buf[0]) 97 | } 98 | 99 | // Read the supported authentication methods 100 | nMethods := int(buf[1]) 101 | nMethodsData := make([]byte, nMethods) 102 | if _, err := io.ReadFull(conn, nMethodsData); err != nil { 103 | return fmt.Errorf("failed to read methods: %w", err) 104 | } 105 | 106 | // Select no authentication (0x00) 107 | if _, err := conn.Write([]byte{socks5Version, 0x00}); err != nil { 108 | return fmt.Errorf("failed to write method selection: %w", err) 109 | } 110 | return nil 111 | } 112 | 113 | func (ss *ClientLocalSocks5Server) socks5Request(conn net.Conn) (*Socks5Request, error) { 114 | buf := make([]byte, 8<<10) 115 | n, err := conn.Read(buf) 116 | if err != nil { 117 | return nil, fmt.Errorf("failed to read request: %w", err) 118 | } 119 | data := buf[:n] 120 | if len(data) < 4 { 121 | return nil, fmt.Errorf("request too short") 122 | } 123 | return parseSocks5Request(data, ss.geo) 124 | } 125 | 126 | func (ss *ClientLocalSocks5Server) handleConnection(outerCtx context.Context, conn net.Conn) { 127 | defer conn.Close() // the outer for loop is not suitable for defer, so defer close here 128 | ctx, cf := context.WithTimeout(outerCtx, ss.Timeout) 129 | defer cf() 130 | 131 | err := ss.socks5HandShake(conn) 132 | if err != nil { 133 | slog.Error("failed to handshake", "err", err.Error()) 134 | socks5Response(conn, net.IPv4zero, 0, socks5ReplyFail) 135 | return 136 | } 137 | req, err := ss.socks5Request(conn) 138 | if err != nil { 139 | slog.Error("failed to parse socks5 request", "err", err.Error()) 140 | socks5Response(conn, net.IPv4zero, 0, socks5ReplyFail) 141 | return 142 | } 143 | req.Logger().Info("remote target") 144 | if req.socks5Cmd == socks5CmdConnect { //tcp 145 | relayTcpSvr, err := ss.dispatchRelayTcpServer(ctx, req) 146 | if err != nil { 147 | slog.Error("failed to dispatch relay tcp server", "err", err.Error()) 148 | socks5Response(conn, net.IPv4zero, 0, socks5ReplyFail) 149 | return 150 | } 151 | socks5Response(conn, net.IPv4zero, 0, socks5ReplyOkay) 152 | defer relayTcpSvr.Close() 153 | ss.pipeTcp(ctx, conn, relayTcpSvr) 154 | return 155 | } else if req.socks5Cmd == socks5CmdUdpAssoc { 156 | udpH, err := NewRelayUdpDirect(conn) 157 | if err != nil { 158 | slog.Error("failed to create udp handler", "err", err.Error()) 159 | socks5Response(conn, net.IPv4zero, 0, socks5ReplyFail) 160 | return 161 | } 162 | 163 | defer udpH.Close() 164 | udpH.PipeUdp() 165 | return 166 | } else if req.socks5Cmd == socks5CmdBind { 167 | relayBind(conn, req) 168 | return 169 | } else { 170 | err = fmt.Errorf("unknown command: %d", req.socks5Cmd) 171 | slog.Error("unknown command", "err", err.Error()) 172 | socks5Response(conn, net.IPv4zero, 0, socks5ReplyFail) 173 | } 174 | } 175 | 176 | func (ss *ClientLocalSocks5Server) shouldGoDirect(req *Socks5Request) (goDirect bool) { 177 | 178 | if req.CountryCode == "CN" || req.CountryCode == "" { 179 | //empty means geo ip failed or local address 180 | return true 181 | } 182 | 183 | return false 184 | } 185 | 186 | func (ss *ClientLocalSocks5Server) dispatchRelayTcpServer(ctx context.Context, req *Socks5Request) (io.ReadWriteCloser, error) { 187 | if ss.shouldGoDirect(req) { 188 | req.Logger().Info("go direct") 189 | return NewRelayTcpDirect(req) 190 | } 191 | return NewRelayTcpSocks5e(ctx, ss.proxy, req) 192 | } 193 | 194 | func (ss *ClientLocalSocks5Server) pipeTcp(ctx context.Context, s5 net.Conn, relayRw io.ReadWriter) { 195 | wg := sync.WaitGroup{} 196 | wg.Add(2) 197 | go func() { 198 | span := slog.With("fn", "ws -> s5") 199 | defer func() { 200 | span.Debug("wg1 done") 201 | wg.Done() 202 | }() 203 | for { 204 | select { 205 | case <-ctx.Done(): 206 | span.Info("ctx.Done exit") 207 | return 208 | default: 209 | //ws.SetReadDeadline(time.Now().Add(1 * time.Second)) 210 | buf := make([]byte, 8<<10) 211 | n, err := relayRw.Read(buf) 212 | if err != nil { 213 | span.Error("relay read", "err", err.Error()) 214 | return 215 | } 216 | _, err = s5.Write(buf[:n]) 217 | if err != nil { 218 | span.Error("s5 write", "err", err.Error()) 219 | return 220 | } 221 | } 222 | } 223 | }() 224 | go func() { // s5 -> ws 225 | span := slog.With("fn", "s5 -> ws") 226 | defer func() { 227 | span.Debug("wg2 done") 228 | wg.Done() 229 | }() 230 | for { 231 | select { 232 | case <-ctx.Done(): 233 | span.Debug("ctx.Done exit") 234 | return 235 | default: 236 | buf := make([]byte, 8<<10) 237 | //s5.SetReadDeadline(time.Now().Add(20 * time.Millisecond)) 238 | n, err := s5.Read(buf) 239 | if errors.Is(err, io.EOF) { 240 | slog.Info("s5 read EOF") 241 | return 242 | } 243 | if err != nil { 244 | et := fmt.Sprintf("%T", err) 245 | span.With("errType", et).Error("s5 read", "err", err.Error()) 246 | return 247 | } 248 | //ws.SetWriteDeadline(time.Now().Add(1 * time.Second)) 249 | n, err = relayRw.Write(buf[:n]) 250 | if err != nil { 251 | span.Error("relay write", "err", err.Error()) 252 | return 253 | } 254 | } 255 | } 256 | }() 257 | wg.Wait() 258 | slog.Debug("2 goroutines is Done") 259 | } 260 | -------------------------------------------------------------------------------- /socks5ws/const.go: -------------------------------------------------------------------------------- 1 | package socks5ws 2 | 3 | import ( 4 | "log/slog" 5 | "net" 6 | ) 7 | 8 | const ( 9 | socks5Version = 0x05 10 | socks5ReplyOkay = 0x00 11 | socks5ReplyFail = 0x01 12 | socks5ReplyReserved = 0x00 13 | socks5CmdConnect = 0x01 14 | socks5CmdBind = 0x02 15 | socks5CmdUdpAssoc = 0x03 16 | socks5AtypeIPv4 = 0x01 17 | socks5AtypeDomain = 0x03 18 | socks5AtypeIPv6 = 0x04 19 | socks5UdpFragNotSupported = 0x00 20 | socks5UdpFragEnd = 0x80 21 | 22 | bufferSize = 64 << 10 23 | ) 24 | 25 | func socks5Response(conn net.Conn, ipv4 net.IP, port int, socks5OkayOrFail byte) { 26 | if socks5OkayOrFail != socks5ReplyOkay { 27 | ipv4 = net.IPv4zero 28 | port = 0 29 | } 30 | if ipv4 == nil { 31 | ipv4 = net.IPv4zero 32 | } 33 | if port < 0 || port > 65535 { 34 | port = 0 35 | } 36 | response := []byte{socks5Version, socks5OkayOrFail, socks5ReplyReserved, socks5AtypeIPv4, ipv4[0], ipv4[1], ipv4[2], ipv4[3], byte(port >> 8), byte(port & 0xff)} 37 | _, err := conn.Write(response) 38 | if err != nil { 39 | slog.Error("socks5 request rely failed to write", "err", err.Error()) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /socks5ws/relay_svr.go: -------------------------------------------------------------------------------- 1 | package socks5ws 2 | 3 | import "io" 4 | 5 | type RelayTcp interface { 6 | io.Reader 7 | io.Writer 8 | io.Closer 9 | } 10 | -------------------------------------------------------------------------------- /socks5ws/relay_tcp_direct.go: -------------------------------------------------------------------------------- 1 | package socks5ws 2 | 3 | import "net" 4 | 5 | var _ RelayTcp = (*RelayTcpDirect)(nil) 6 | 7 | type RelayTcpDirect struct { 8 | conn net.Conn 9 | } 10 | 11 | func NewRelayTcpDirect(req *Socks5Request) (*RelayTcpDirect, error) { 12 | conn, err := net.Dial("tcp", req.addr()) 13 | if err != nil { 14 | return nil, err 15 | } 16 | return &RelayTcpDirect{conn: conn}, nil 17 | } 18 | 19 | func (r *RelayTcpDirect) Read(p []byte) (n int, err error) { 20 | return r.conn.Read(p) 21 | } 22 | 23 | func (r *RelayTcpDirect) Write(p []byte) (n int, err error) { 24 | return r.conn.Write(p) 25 | } 26 | 27 | func (r *RelayTcpDirect) Close() error { 28 | return r.conn.Close() 29 | } 30 | -------------------------------------------------------------------------------- /socks5ws/relay_tcp_socks5e.go: -------------------------------------------------------------------------------- 1 | package socks5ws 2 | 3 | import ( 4 | "context" 5 | "github.com/gorilla/websocket" 6 | "github.com/mojocn/felix/model" 7 | "log/slog" 8 | "time" 9 | ) 10 | 11 | var _ RelayTcp = (*RelayTcpSocks5e)(nil) 12 | 13 | type RelayTcpSocks5e struct { 14 | cfg *model.Proxy 15 | req *Socks5Request 16 | conn *websocket.Conn 17 | } 18 | 19 | func NewRelayTcpSocks5e(ctx context.Context, cfg *model.Proxy, req *Socks5Request) (*RelayTcpSocks5e, error) { 20 | ws, err := webSocketConn(ctx, cfg, req) 21 | if err != nil { 22 | return nil, err 23 | } 24 | ws.SetCloseHandler(func(code int, text string) error { 25 | slog.Debug("ws has closed", "code", code, "text", text) 26 | return nil 27 | }) 28 | return &RelayTcpSocks5e{cfg: cfg, req: req, conn: ws}, nil 29 | } 30 | 31 | func (r RelayTcpSocks5e) Read(data []byte) (n int, err error) { 32 | if r.conn != nil { 33 | _, p, err := r.conn.ReadMessage() 34 | if err != nil { 35 | slog.Error("failed to read ws", "err", err.Error()) 36 | } 37 | return copy(data, p), err 38 | } 39 | return 0, nil 40 | } 41 | 42 | func (r RelayTcpSocks5e) Write(data []byte) (n int, err error) { 43 | if r.conn != nil { 44 | err = r.conn.WriteMessage(websocket.BinaryMessage, data) 45 | if err != nil { 46 | slog.Error("failed to write ws", "err", err.Error()) 47 | } 48 | return len(data), err 49 | } 50 | return 0, nil 51 | } 52 | 53 | func (r RelayTcpSocks5e) Close() error { 54 | if r.conn != nil { 55 | err := r.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Millisecond*20)) 56 | if err != nil { 57 | slog.Error("failed to close ws", "err", err.Error()) 58 | } 59 | return r.conn.Close() 60 | } 61 | return nil 62 | } 63 | -------------------------------------------------------------------------------- /socks5ws/relay_udp_direct.go: -------------------------------------------------------------------------------- 1 | package socks5ws 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "io" 7 | "log" 8 | "log/slog" 9 | "net" 10 | "sort" 11 | "sync" 12 | "time" 13 | ) 14 | 15 | type RelayUdpDirect struct { 16 | s5 net.Conn 17 | relayUdp *net.UDPConn 18 | 19 | // Reassembly queue for fragmented UDP packets. 20 | mu sync.Mutex 21 | fragments map[string][]*udpPacket // Map of DstAddr to fragments 22 | highestFrag map[string]byte // Track highest FRAG value for each DstAddr 23 | timers map[string]*time.Timer // Map of DstAddr to reassembly timer 24 | timerDuration time.Duration // Timer duration 25 | } 26 | 27 | func (ud *RelayUdpDirect) addFragment(clientAddr *net.UDPAddr, frag *udpPacket) { 28 | ud.mu.Lock() 29 | defer ud.mu.Unlock() 30 | clientDstAddr := ud.clientDstAddrAsID(clientAddr, frag.dstAddr()) 31 | // Initialize fragment queue and timer if not already present. 32 | if _, exists := ud.fragments[clientDstAddr]; !exists { 33 | ud.fragments[clientDstAddr] = []*udpPacket{} 34 | ud.highestFrag[clientDstAddr] = socks5UdpFragNotSupported 35 | ud.startTimer(clientDstAddr) 36 | } 37 | 38 | // Update highest FRAG value. 39 | if frag.Frag > ud.highestFrag[clientDstAddr] { 40 | ud.highestFrag[clientDstAddr] = frag.Frag 41 | } 42 | 43 | // Add fragment to the queue. 44 | ud.fragments[clientDstAddr] = append(ud.fragments[clientDstAddr], frag) 45 | 46 | // Check if this is the final fragment (end-of-fragment sequence). 47 | if frag.Frag == socks5UdpFragEnd || frag.Frag == socks5UdpFragNotSupported { // High-order bit indicates end of sequence. 48 | ud.assembleThenPipeUdp(clientAddr, frag.dstAddr()) 49 | } 50 | } 51 | 52 | func (ud *RelayUdpDirect) startTimer(ClientDstAddr string) { 53 | if timer, exists := ud.timers[ClientDstAddr]; exists { 54 | timer.Stop() 55 | } 56 | ud.timers[ClientDstAddr] = time.AfterFunc(ud.timerDuration, func() { 57 | ud.mu.Lock() 58 | defer ud.mu.Unlock() 59 | delete(ud.fragments, ClientDstAddr) 60 | delete(ud.highestFrag, ClientDstAddr) 61 | delete(ud.timers, ClientDstAddr) 62 | }) 63 | } 64 | func (ud *RelayUdpDirect) clientDstAddrAsID(clientAddr *net.UDPAddr, dstAddr string) string { 65 | return fmt.Sprintf("%s/%s", clientAddr, dstAddr) 66 | } 67 | func (ud *RelayUdpDirect) assembleThenPipeUdp(clientAddr *net.UDPAddr, dstAddr string) { 68 | var data []byte 69 | clientDstAddr := ud.clientDstAddrAsID(clientAddr, dstAddr) 70 | fragments := ud.fragments[clientDstAddr] 71 | // Sort fragments by FRAG value. 72 | sort.Slice(fragments, func(i, j int) bool { 73 | return fragments[i].Frag < fragments[j].Frag 74 | }) 75 | for _, frag := range fragments { 76 | data = append(data, frag.Data...) 77 | } 78 | comboPacket := fragments[0] 79 | comboPacket.Data = data 80 | 81 | // Clean up after successful reassembly. 82 | delete(ud.fragments, clientDstAddr) 83 | delete(ud.highestFrag, clientDstAddr) 84 | if timer, exists := ud.timers[clientDstAddr]; exists { 85 | timer.Stop() 86 | delete(ud.timers, clientDstAddr) 87 | } 88 | ud.segmentPipe(comboPacket, clientAddr) 89 | } 90 | 91 | func (ud *RelayUdpDirect) PipeUdp() { 92 | buf := make([]byte, bufferSize) 93 | for { 94 | n, clientAddr, err := ud.relayUdp.ReadFromUDP(buf) 95 | if errors.Is(err, io.EOF) { 96 | return 97 | } 98 | //I will not verify the `clientAddr` because this SOCKS5 proxy is intended for local relay to bypass the GFW. 99 | if err != nil { 100 | slog.Error("Error reading UDP data", "err", err.Error()) 101 | continue 102 | } 103 | packet, err := parseUDPData(buf[:n]) 104 | if err != nil { 105 | log.Println("Error parsing UDP data", err) 106 | continue 107 | } 108 | ud.addFragment(clientAddr, packet) 109 | } 110 | } 111 | 112 | func (ud *RelayUdpDirect) segmentPipe(comboPacket *udpPacket, clientAddr *net.UDPAddr) { 113 | resp, err := forwardUDPData(comboPacket) 114 | if err != nil { 115 | slog.Error("Error forwarding UDP data", "err", err.Error()) 116 | return 117 | } 118 | header := comboPacket.ResponseData(resp) 119 | _, err = ud.relayUdp.WriteToUDP(header, clientAddr) 120 | if err != nil { 121 | slog.Error("Error sending UDP response", "err", err.Error()) 122 | } 123 | } 124 | 125 | func NewRelayUdpDirect(s5 net.Conn) (*RelayUdpDirect, error) { 126 | udpAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0} 127 | udpConn, err := net.ListenUDP("udp", udpAddr) 128 | if err != nil { 129 | return nil, fmt.Errorf("failed to bind UDP socket: %w", err) 130 | } 131 | ud := &RelayUdpDirect{ 132 | s5: s5, 133 | relayUdp: udpConn, 134 | mu: sync.Mutex{}, 135 | fragments: make(map[string][]*udpPacket), 136 | highestFrag: make(map[string]byte), 137 | timers: make(map[string]*time.Timer), 138 | timerDuration: time.Second * 60, 139 | } 140 | 141 | boundAddr := udpConn.LocalAddr().(*net.UDPAddr) 142 | response := []byte{ 143 | socks5Version, socks5ReplyOkay, socks5ReplyReserved, socks5AtypeIPv4, 144 | boundAddr.IP[0], boundAddr.IP[1], boundAddr.IP[2], boundAddr.IP[3], 145 | byte(boundAddr.Port >> 8), byte(boundAddr.Port & 0xFF), 146 | } 147 | _, err = ud.s5.Write(response) 148 | if err != nil { 149 | return nil, fmt.Errorf("failed to send response to client: %w", err) 150 | } 151 | 152 | return ud, nil 153 | } 154 | 155 | func forwardUDPData(udpPacket *udpPacket) ([]byte, error) { 156 | conn, err := net.DialUDP("udp", nil, udpPacket.addr()) 157 | if err != nil { 158 | return nil, err 159 | } 160 | defer conn.Close() 161 | 162 | _, err = conn.Write(udpPacket.Data) 163 | if err != nil { 164 | return nil, err 165 | } 166 | 167 | buf := make([]byte, bufferSize) 168 | n, _, err := conn.ReadFromUDP(buf) 169 | if err != nil { 170 | return nil, err 171 | } 172 | return buf[:n], nil 173 | } 174 | 175 | type udpPacket struct { 176 | RSV [2]byte // reserved 177 | Frag byte // fragment 178 | AType byte // dst address type 179 | Addr []byte // dst address 180 | Port []byte // dst port 181 | Data []byte // payload 182 | } 183 | 184 | func (p udpPacket) ResponseData(payload []byte) []byte { 185 | header := []byte{p.RSV[0], p.RSV[1], 0, p.AType} 186 | header = append(header, p.Addr...) 187 | header = append(header, p.Port...) 188 | return append(header, payload...) 189 | } 190 | 191 | func parseUDPData(data []byte) (*udpPacket, error) { 192 | if len(data) < 4 { 193 | return nil, fmt.Errorf("invalid UDP packet") 194 | } 195 | // parse header 196 | var packet = udpPacket{ 197 | RSV: [2]byte{data[0], data[1]}, 198 | Frag: data[2], 199 | AType: data[3], 200 | } 201 | switch packet.AType { 202 | case socks5AtypeIPv4: 203 | if len(data) < 10 { 204 | return nil, fmt.Errorf("invalid IPv4 UDP packet") 205 | } 206 | packet.Addr = data[4 : 4+net.IPv4len] 207 | packet.Port = data[4+net.IPv4len : 4+net.IPv4len+2] 208 | packet.Data = data[4+net.IPv4len+2:] 209 | case socks5AtypeIPv6: 210 | if len(data) < 22 { 211 | return nil, fmt.Errorf("invalid IPv6 UDP packet") 212 | } 213 | packet.Addr = data[4 : 4+net.IPv6len] 214 | packet.Port = data[4+net.IPv6len : 4+net.IPv6len+2] 215 | packet.Data = data[4+net.IPv6len+2:] 216 | case socks5AtypeDomain: 217 | if len(data) < 7 { 218 | return nil, fmt.Errorf("invalid domain UDP packet") 219 | } 220 | addrLen := int(data[4]) 221 | packet.Addr = data[5 : 5+addrLen] 222 | packet.Port = data[5+addrLen : 5+addrLen+2] 223 | packet.Data = data[5+addrLen+2:] 224 | default: 225 | return nil, fmt.Errorf("unsupported address type: %d", packet.AType) 226 | } 227 | return &packet, nil 228 | } 229 | 230 | func (p udpPacket) ip() net.IP { 231 | switch p.AType { 232 | case socks5AtypeIPv4, socks5AtypeIPv6: 233 | return p.Addr 234 | case socks5AtypeDomain: 235 | ips, err := net.LookupIP(string(p.Addr)) 236 | if err != nil { 237 | slog.Error("failed to resolve domain", "err", err.Error()) 238 | return net.IPv4zero 239 | } 240 | if len(ips) == 0 { 241 | return net.IPv4zero 242 | } 243 | return ips[0] 244 | default: 245 | return net.IPv4zero 246 | } 247 | } 248 | 249 | func (p udpPacket) port() int { 250 | return int(p.Port[0])<<8 + int(p.Port[1]) 251 | } 252 | func (p udpPacket) addr() *net.UDPAddr { 253 | return &net.UDPAddr{IP: p.ip(), Port: p.port()} 254 | } 255 | func (p udpPacket) dstAddr() string { 256 | return fmt.Sprintf("%s:%d", p.ip(), p.port()) 257 | } 258 | 259 | func (ud *RelayUdpDirect) Close() { 260 | //s5 has already been closed in outside 261 | if ud.relayUdp != nil { 262 | err := ud.relayUdp.Close() 263 | if err != nil { 264 | log.Println("close udp conn failed: ", err) 265 | } 266 | } 267 | 268 | } 269 | -------------------------------------------------------------------------------- /socks5ws/socks5_bind.go: -------------------------------------------------------------------------------- 1 | package socks5ws 2 | 3 | import ( 4 | "io" 5 | "log/slog" 6 | "net" 7 | "sync" 8 | ) 9 | 10 | func relayBind(s5 net.Conn, _ *Socks5Request) { 11 | bindListener, err := net.Listen("tcp4", ":0") 12 | if err != nil { 13 | slog.Error("bind tcp failed", "err", err) 14 | socks5Response(s5, net.IPv4zero, 0, socks5ReplyFail) 15 | return 16 | } 17 | defer bindListener.Close() 18 | //first reply 19 | localAddr := bindListener.Addr().(*net.TCPAddr) 20 | socks5Response(s5, localAddr.IP, localAddr.Port, socks5ReplyOkay) 21 | 22 | targetConn, err := bindListener.Accept() 23 | if err != nil { 24 | slog.Error("bind tcp failed", "err", err) 25 | return 26 | } 27 | defer targetConn.Close() 28 | //sec reply 29 | targetAddr := targetConn.RemoteAddr().(*net.TCPAddr) 30 | socks5Response(s5, targetAddr.IP, targetAddr.Port, socks5ReplyOkay) 31 | 32 | var wg sync.WaitGroup 33 | wg.Add(2) 34 | go func() { 35 | defer wg.Done() 36 | _, err := io.Copy(targetConn, s5) 37 | if err != nil { 38 | slog.Error("bind tcp failed", "err", err) 39 | } 40 | }() 41 | go func() { 42 | defer wg.Done() 43 | _, err := io.Copy(s5, targetConn) 44 | if err != nil { 45 | slog.Error("bind tcp failed", "err", err) 46 | } 47 | }() 48 | wg.Wait() 49 | } 50 | -------------------------------------------------------------------------------- /socks5ws/socks5_connect.go: -------------------------------------------------------------------------------- 1 | package socks5ws 2 | -------------------------------------------------------------------------------- /socks5ws/socks5_req.go: -------------------------------------------------------------------------------- 1 | package socks5ws 2 | 3 | import ( 4 | "fmt" 5 | "github.com/google/uuid" 6 | "github.com/mojocn/felix/util" 7 | "log/slog" 8 | "net" 9 | ) 10 | 11 | type Socks5Request struct { 12 | id string 13 | socks5Cmd byte 14 | socks5Atyp byte 15 | dstAddr []byte 16 | dstPort []byte 17 | CountryCode string //iso country code 18 | } 19 | 20 | func parseSocks5Request(data []byte, geo *util.GeoIP) (*Socks5Request, error) { 21 | id := uuid.NewString() 22 | info := &Socks5Request{id: id} 23 | 24 | if data[0] != socks5Version { 25 | return nil, fmt.Errorf("unsupported SOCKS version: %d", data[0]) 26 | } 27 | if data[1] == socks5CmdConnect { 28 | info.socks5Cmd = socks5CmdConnect 29 | } else if data[1] == socks5CmdUdpAssoc { 30 | info.socks5Cmd = socks5CmdUdpAssoc 31 | } else { 32 | //BIND is not supported 33 | return nil, fmt.Errorf("unsupported command: %d", data[1]) 34 | } 35 | if data[2] != socks5ReplyReserved { 36 | return nil, fmt.Errorf("RSV must be 0x00") 37 | } 38 | if data[3] == socks5AtypeIPv4 { 39 | if len(data) < 10 { 40 | return nil, fmt.Errorf("request too short for atyp IPv4") 41 | } 42 | info.socks5Atyp = socks5AtypeIPv4 43 | info.dstAddr = data[4:8] 44 | info.dstPort = data[8:10] 45 | } else if data[3] == socks5AtypeDomain { 46 | if len(data) < 5 { 47 | return nil, fmt.Errorf("request too short for atyp Domain") 48 | } 49 | addrLen := int(data[4]) 50 | info.socks5Atyp = socks5AtypeDomain 51 | info.dstAddr = data[5 : 5+addrLen] 52 | info.dstPort = data[5+addrLen : 5+addrLen+2] 53 | } else if data[3] == socks5AtypeIPv6 { 54 | if len(data) < 22 { 55 | return nil, fmt.Errorf("request too short for atyp IPv6") 56 | } 57 | info.socks5Atyp = socks5AtypeIPv6 58 | info.dstAddr = data[4:20] 59 | info.dstPort = data[20:22] 60 | } else { 61 | return nil, fmt.Errorf("unsupported address type: %d", data[3]) 62 | } 63 | //only get country code for connect command 64 | if info.socks5Cmd == socks5CmdConnect { 65 | code, err := geo.Country(info.host()) 66 | if err != nil { 67 | info.Logger().Error("failed to get country code", "err", err.Error()) 68 | } else { 69 | info.CountryCode = code 70 | } 71 | } 72 | return info, nil 73 | } 74 | 75 | func (s Socks5Request) host() string { 76 | addr := "" 77 | if s.socks5Atyp == socks5AtypeIPv4 || s.socks5Atyp == socks5AtypeIPv6 { 78 | addr = net.IP(s.dstAddr).String() 79 | } else if s.socks5Atyp == socks5AtypeDomain { 80 | addr = string(s.dstAddr) 81 | } else { 82 | addr = string(s.dstAddr) 83 | } 84 | return addr 85 | } 86 | 87 | func (s Socks5Request) addr() string { 88 | return fmt.Sprintf("%s:%s", s.host(), s.port()) 89 | } 90 | func (s Socks5Request) cmd() string { 91 | cmd := "unknown" 92 | if s.socks5Cmd == socks5CmdConnect { 93 | cmd = "connect" 94 | } else if s.socks5Cmd == socks5CmdUdpAssoc { 95 | cmd = "udp" 96 | } else if s.socks5Cmd == socks5CmdBind { 97 | cmd = "bind" 98 | } 99 | return cmd 100 | } 101 | 102 | func (s Socks5Request) Network() string { 103 | cmd := "unknown" 104 | if s.socks5Cmd == socks5CmdConnect { 105 | cmd = "tcp" 106 | } else if s.socks5Cmd == socks5CmdUdpAssoc { 107 | cmd = "udp" 108 | } else if s.socks5Cmd == socks5CmdBind { 109 | cmd = "bind" 110 | } 111 | return cmd 112 | } 113 | 114 | func (s Socks5Request) aType() string { 115 | return fmt.Sprintf("%v", s.socks5Atyp) 116 | } 117 | 118 | func (s Socks5Request) port() string { 119 | port := int(s.dstPort[0])<<8 + int(s.dstPort[1]) 120 | return fmt.Sprintf("%v", port) 121 | } 122 | 123 | func (s Socks5Request) Logger() *slog.Logger { 124 | return slog.With("reqId", s.id, "cmd", s.cmd(), "atyp", s.aType(), "ip", s.host(), "port", s.port(), "country", s.CountryCode) 125 | } 126 | func (s Socks5Request) String() string { 127 | return fmt.Sprintf("socks5Cmd: %v, socks5Atyp: %v, dstAddr: %v, dstPort: %v, country: %s", s.cmd(), s.aType(), s.host(), s.port(), s.CountryCode) 128 | } 129 | 130 | func (s Socks5Request) addressBytes() []byte { 131 | if s.socks5Atyp == socks5AtypeDomain { 132 | return append([]byte{byte(len(s.dstAddr))}, s.dstAddr...) 133 | } 134 | return s.dstAddr 135 | } 136 | -------------------------------------------------------------------------------- /socks5ws/socks5_udp_associate.go: -------------------------------------------------------------------------------- 1 | package socks5ws 2 | -------------------------------------------------------------------------------- /socks5ws/websocket.go: -------------------------------------------------------------------------------- 1 | package socks5ws 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "fmt" 7 | "github.com/gorilla/websocket" 8 | "github.com/mojocn/felix/model" 9 | "log/slog" 10 | "net/http" 11 | ) 12 | 13 | const ( 14 | browserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" 15 | ) 16 | 17 | func webSocketConn(ctx context.Context, proxy *model.Proxy, req *Socks5Request) (*websocket.Conn, error) { 18 | wsDialer := websocket.DefaultDialer 19 | 20 | headers := http.Header{} 21 | headers.Set("Authorization", proxy.UserID) 22 | headers.Set("User-Agent", browserAgent) 23 | if proxy.Sni != "" { 24 | headers.Set("Host", proxy.Sni) 25 | wsDialer.TLSClientConfig = &tls.Config{ 26 | ServerName: proxy.Sni, // Set the SNI to the hostname of the server 27 | } 28 | } 29 | headers.Set("x-req-id", req.id) 30 | headers.Set("x-dst-network", "tcp") 31 | headers.Set("x-dst-addr", req.host()) 32 | headers.Set("x-dst-port", req.port()) 33 | headers.Set("x-dst-version", "socks5") // socks5proxy.Version 34 | url := proxy.RelayURL() 35 | slog.Debug("connecting to remote proxy server", "url", url) 36 | ws, resp, err := websocket.DefaultDialer.DialContext(ctx, url, headers) 37 | if err != nil { 38 | return nil, fmt.Errorf("failed to connect to remote proxy server: %s ,error:%v", proxy.RelayURL(), err) 39 | } 40 | if resp.StatusCode != http.StatusSwitchingProtocols { 41 | return nil, fmt.Errorf("failed to connect to remote proxy server: %s ,error:%v", proxy.RelayURL(), err) 42 | } 43 | return ws, nil 44 | } 45 | -------------------------------------------------------------------------------- /util/browse_open.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "os/exec" 5 | "runtime" 6 | ) 7 | 8 | func BrowserOpen(url string) error { 9 | var cmd string 10 | var args []string 11 | 12 | switch runtime.GOOS { 13 | case "windows": 14 | cmd = "cmd" 15 | args = []string{"/c", "start"} 16 | case "darwin": 17 | cmd = "open" 18 | default: // "linux", "freebsd", "openbsd", "netbsd" 19 | cmd = "xdg-open" 20 | } 21 | args = append(args, url) 22 | return exec.Command(cmd, args...).Start() 23 | } 24 | -------------------------------------------------------------------------------- /util/cf_ip.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io" 7 | "log" 8 | "net" 9 | "net/http" 10 | "time" 11 | ) 12 | 13 | //https://api.cloudflare.com/client/v4/ips 14 | //https://api.cloudflare.com/client/v4/ips?networks=jdcloud 15 | 16 | type CfIP struct { 17 | Ipv4Cidrs []string `json:"ipv4_cidrs"` 18 | Ipv6Cidrs []string `json:"ipv6_cidrs"` 19 | ReachableIPs chan string 20 | } 21 | 22 | var cfIpNode *CfIP 23 | 24 | func singletonCfIP() *CfIP { 25 | if cfIpNode == nil { 26 | var err error 27 | cfIpNode, err = NewCfIP() 28 | if err != nil { 29 | log.Printf("Error getting cf ip: %v\n", err) 30 | } 31 | } 32 | return cfIpNode 33 | } 34 | 35 | func NewCfIP() (*CfIP, error) { 36 | resp, err := http.Get("https://api.cloudflare.com/client/v4/ips") 37 | if err != nil { 38 | return nil, fmt.Errorf("get cf ip failed %w", err) 39 | } 40 | if resp.StatusCode != http.StatusOK { 41 | return nil, fmt.Errorf("get cf ip failed %s", resp.Status) 42 | } 43 | defer resp.Body.Close() 44 | all, err := io.ReadAll(resp.Body) 45 | if err != nil { 46 | return nil, fmt.Errorf("read cf ip failed %w", err) 47 | } 48 | result := struct { 49 | Result struct { 50 | Ipv4Cidrs []string `json:"ipv4_cidrs"` 51 | Ipv6Cidrs []string `json:"ipv6_cidrs"` 52 | Etag string `json:"etag"` 53 | } `json:"result"` 54 | Success bool `json:"success"` 55 | Errors []interface{} `json:"errors"` 56 | Messages []interface{} `json:"messages"` 57 | }{} 58 | err = json.Unmarshal(all, &result) 59 | if err != nil { 60 | return nil, fmt.Errorf("unmarshal cf ip failed %w", err) 61 | } 62 | 63 | return &CfIP{ 64 | Ipv4Cidrs: result.Result.Ipv4Cidrs, 65 | Ipv6Cidrs: result.Result.Ipv4Cidrs, 66 | ReachableIPs: make(chan string), 67 | }, nil 68 | } 69 | 70 | func (ci CfIP) IsCf(ip net.IP) bool { 71 | for _, cidr := range append(ci.Ipv4Cidrs, ci.Ipv6Cidrs...) { 72 | _, ipNet, err := net.ParseCIDR(cidr) 73 | if err != nil { 74 | log.Printf("Error parsing Cidr: %v\n", err) 75 | continue 76 | } 77 | if ipNet.Contains(ip) { 78 | return true 79 | } 80 | } 81 | return false 82 | } 83 | 84 | func (ci CfIP) AllIps(fn func(ip, cidr string)) { 85 | for _, cidr := range append(ci.Ipv4Cidrs, ci.Ipv6Cidrs...) { 86 | ips, err := getIPsFromCIDR(cidr) 87 | if err != nil { 88 | fmt.Printf("Error parsing Cidr: %v\n", err) 89 | continue 90 | } 91 | for _, ip := range ips { 92 | fn(ip, cidr) 93 | } 94 | } 95 | } 96 | 97 | //func (ci CfIP) CheckReachableIps() { 98 | // maxWorkers := runtime.GOMAXPROCS(0) * 64 99 | // ips := ci.ips() 100 | // jobs := make(chan string, len(ips)) 101 | // resultChan := make(chan string, len(ips)) 102 | // var wg sync.WaitGroup 103 | // for i := 0; i < maxWorkers; i++ { 104 | // wg.Add(1) 105 | // go func() { 106 | // defer wg.Done() 107 | // for ip := range jobs { 108 | // if isReachable(ip, 443) { 109 | // resultChan <- ip 110 | // } 111 | // } 112 | // }() 113 | // } 114 | // for _, ip := range ci.ips() { 115 | // jobs <- ip 116 | // } 117 | // close(jobs) 118 | // wg.Wait() 119 | // var reachable []string 120 | // for ip := range resultChan { 121 | // reachable = append(reachable, ip) 122 | // } 123 | // fd, err := os.Create("cf_reachable_ips.txt") 124 | // if err != nil { 125 | // log.Println(err) 126 | // return 127 | // } 128 | // defer fd.Close() 129 | // fd.Write([]byte(strings.Join(reachable, "\n"))) 130 | //} 131 | 132 | func getIPsFromCIDR(cidr string) ([]string, error) { 133 | ip, ipNet, err := net.ParseCIDR(cidr) 134 | if err != nil { 135 | return nil, err 136 | } 137 | 138 | var ips []string 139 | for ip := ip.Mask(ipNet.Mask); ipNet.Contains(ip); inc(ip) { 140 | ips = append(ips, ip.String()) 141 | } 142 | // Remove network address and broadcast address 143 | return ips[1 : len(ips)-1], nil 144 | } 145 | 146 | func inc(ip net.IP) { 147 | for j := len(ip) - 1; j >= 0; j-- { 148 | ip[j]++ 149 | if ip[j] > 0 { 150 | break 151 | } 152 | } 153 | } 154 | 155 | func isReachable(ip string, port int) bool { 156 | timeout := time.Millisecond * 70 157 | conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", ip, port), timeout) 158 | if err != nil { 159 | log.Printf("Error connecting to %s:%d: %v\n", ip, port, err) 160 | return false 161 | } 162 | conn.Close() 163 | return true 164 | } 165 | -------------------------------------------------------------------------------- /util/cf_ip_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import "testing" 4 | 5 | func TestCfIP_CheckReachableIps(t *testing.T) { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /util/crypt_aes.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "bytes" 5 | "crypto/aes" 6 | "crypto/cipher" 7 | "encoding/base64" 8 | ) 9 | 10 | //https://tech.mojotv.cn/2019/06/28/golang-crypt#svekr 11 | // key length must be 16/24/32 12 | func AesEncrypt(origData []byte, key string) (string, error) { 13 | // 转成字节数组 14 | k := []byte(key) 15 | 16 | // 分组秘钥 17 | block, err := aes.NewCipher(k) 18 | if err != nil { 19 | return "", err 20 | } 21 | // 获取秘钥块的长度 22 | blockSize := block.BlockSize() 23 | // 补全码 24 | origData = PKCS7Padding(origData, blockSize) 25 | // 加密模式 26 | blockMode := cipher.NewCBCEncrypter(block, k[:blockSize]) 27 | // 创建数组 28 | cryted := make([]byte, len(origData)) 29 | // 加密 30 | blockMode.CryptBlocks(cryted, origData) 31 | 32 | return base64.RawURLEncoding.EncodeToString(cryted), nil 33 | 34 | } 35 | 36 | func AesDecrypt(cryted string, key string) ([]byte, error) { 37 | // 转成字节数组 38 | crytedByte, err := base64.RawURLEncoding.DecodeString(cryted) 39 | if err != nil { 40 | return nil, err 41 | } 42 | k := []byte(key) 43 | 44 | // 分组秘钥 45 | block, err := aes.NewCipher(k) 46 | if err != nil { 47 | return nil, err 48 | } 49 | // 获取秘钥块的长度 50 | blockSize := block.BlockSize() 51 | // 加密模式 52 | blockMode := cipher.NewCBCDecrypter(block, k[:blockSize]) 53 | // 创建数组 54 | orig := make([]byte, len(crytedByte)) 55 | // 解密 56 | blockMode.CryptBlocks(orig, crytedByte) 57 | // 去补全码 58 | orig = PKCS7UnPadding(orig) 59 | return orig, nil 60 | } 61 | 62 | //补码 63 | func PKCS7Padding(ciphertext []byte, blocksize int) []byte { 64 | padding := blocksize - len(ciphertext)%blocksize 65 | padtext := bytes.Repeat([]byte{byte(padding)}, padding) 66 | return append(ciphertext, padtext...) 67 | } 68 | 69 | //去码 70 | func PKCS7UnPadding(origData []byte) []byte { 71 | length := len(origData) 72 | unpadding := int(origData[length-1]) 73 | return origData[:(length - unpadding)] 74 | } 75 | -------------------------------------------------------------------------------- /util/crypt_aes_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import "testing" 4 | 5 | func TestAesDecryptEn(t *testing.T) { 6 | key := RandStringWordC(32) 7 | 8 | msg := RandomString(12) 9 | 10 | code, err := AesEncrypt([]byte(msg), key) 11 | if err != nil { 12 | t.Error(err) 13 | } 14 | tMsg, err := AesDecrypt(code, key) 15 | if err != nil { 16 | t.Error(err) 17 | } 18 | if string(tMsg) != msg { 19 | t.Error("aes failed") 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /util/crypt_des.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "bytes" 5 | "crypto/des" 6 | "encoding/hex" 7 | "errors" 8 | ) 9 | 10 | func ZeroPadding(ciphertext []byte, blockSize int) []byte { 11 | padding := blockSize - len(ciphertext)%blockSize 12 | padtext := bytes.Repeat([]byte{0}, padding) 13 | return append(ciphertext, padtext...) 14 | } 15 | 16 | func ZeroUnPadding(origData []byte) []byte { 17 | return bytes.TrimFunc(origData, 18 | func(r rune) bool { 19 | return r == rune(0) 20 | }) 21 | } 22 | 23 | func DesEncrypt(text string, key []byte) (string, error) { 24 | src := []byte(text) 25 | block, err := des.NewCipher(key) 26 | if err != nil { 27 | return "", err 28 | } 29 | bs := block.BlockSize() 30 | src = ZeroPadding(src, bs) 31 | if len(src)%bs != 0 { 32 | return "", errors.New("Need a multiple of the blocksize") 33 | } 34 | out := make([]byte, len(src)) 35 | dst := out 36 | for len(src) > 0 { 37 | block.Encrypt(dst, src[:bs]) 38 | src = src[bs:] 39 | dst = dst[bs:] 40 | } 41 | return hex.EncodeToString(out), nil 42 | } 43 | func DesDecrypt(decrypted string, key []byte) (string, error) { 44 | src, err := hex.DecodeString(decrypted) 45 | if err != nil { 46 | return "", err 47 | } 48 | block, err := des.NewCipher(key) 49 | if err != nil { 50 | return "", err 51 | } 52 | out := make([]byte, len(src)) 53 | dst := out 54 | bs := block.BlockSize() 55 | if len(src)%bs != 0 { 56 | return "", errors.New("crypto/cipher: input not full blocks") 57 | } 58 | for len(src) > 0 { 59 | block.Decrypt(dst, src[:bs]) 60 | src = src[bs:] 61 | dst = dst[bs:] 62 | } 63 | out = ZeroUnPadding(out) 64 | return string(out), nil 65 | } 66 | -------------------------------------------------------------------------------- /util/enable_socks5_darwin.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "os/exec" 7 | "strings" 8 | ) 9 | 10 | func proxySettingOn(socks5Addr string) { 11 | networkService := "Wi-Fi" // Change this to your active network service name 12 | proxyAddress := "127.0.0.1" // SOCKS5 proxy address 13 | proxyPort := "1080" // SOCKS5 proxy port 14 | 15 | // Disable the SOCKS proxy first (optional cleanup) 16 | disableCmd := exec.Command("networksetup", "-setsocksfirewallproxystate", networkService, "off") 17 | if err := disableCmd.Run(); err != nil { 18 | fmt.Printf("Failed to disable SOCKS proxy: %v\n", err) 19 | } 20 | 21 | // Set the SOCKS proxy 22 | cmd := exec.Command("networksetup", 23 | "-setsocksfirewallproxy", 24 | networkService, 25 | proxyAddress, 26 | proxyPort) 27 | if err := cmd.Run(); err != nil { 28 | fmt.Printf("Failed to set SOCKS proxy: %v\n", err) 29 | return 30 | } 31 | 32 | // Enable the SOCKS proxy 33 | enableCmd := exec.Command("networksetup", "-setsocksfirewallproxystate", networkService, "on") 34 | if err := enableCmd.Run(); err != nil { 35 | fmt.Printf("Failed to enable SOCKS proxy: %v\n", err) 36 | return 37 | } 38 | 39 | fmt.Println("SOCKS5 proxy configured successfully!") 40 | } 41 | 42 | func proxySettingOff() (string, error) { 43 | cmd := exec.Command("networksetup", "-listallnetworkservices") 44 | var out bytes.Buffer 45 | cmd.Stdout = &out 46 | if err := cmd.Run(); err != nil { 47 | return "", err 48 | } 49 | 50 | // List all network services 51 | services := strings.Split(out.String(), "\n") 52 | for _, service := range services { 53 | if service != "" { 54 | // Check if the service is active by getting the status 55 | statusCmd := exec.Command("networksetup", "-getinfo", service) 56 | var statusOut bytes.Buffer 57 | statusCmd.Stdout = &statusOut 58 | if err := statusCmd.Run(); err != nil { 59 | return "", err 60 | } 61 | 62 | // Check if the service has a valid IP address (active network) 63 | if strings.Contains(statusOut.String(), "IP address") { 64 | return service, nil 65 | } 66 | } 67 | } 68 | return "", fmt.Errorf("no active network service found") 69 | } 70 | -------------------------------------------------------------------------------- /util/enable_socks5_linux.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | func proxySettingOn(socks5Addr string) { 4 | 5 | } 6 | func proxySettingOff(socks5Addr string) { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /util/enable_socks5_windows.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "fmt" 5 | "golang.org/x/sys/windows/registry" 6 | "log" 7 | ) 8 | 9 | func proxySettingOn(socks5Addr string) { 10 | // Open the registry key for proxy settings 11 | key, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.SET_VALUE) 12 | if err != nil { 13 | log.Fatalf("Error opening registry key: %v", err) 14 | } 15 | defer key.Close() 16 | 17 | // Enable proxy and set proxy server to SOCKS5 18 | err = key.SetDWordValue("ProxyEnable", 1) // 1 to enable proxy 19 | if err != nil { 20 | log.Fatalf("Error enabling proxy: %v", err) 21 | } 22 | 23 | // Set the SOCKS5 proxy address (e.g., "socks=127.0.0.1:1080") 24 | err = key.SetStringValue("ProxyServer", "socks5://"+socks5Addr) 25 | if err != nil { 26 | log.Fatalf("Error setting proxy server: %v", err) 27 | } 28 | 29 | // Set the proxy override settings : *.cn;*.local 30 | // 31 | 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.*;;*.cn" 32 | err = key.SetStringValue("ProxyOverride", skipAddrs) 33 | if err != nil { 34 | log.Fatalf("Error setting proxy override: %v", err) 35 | } 36 | // Optionally disable automatic proxy detection 37 | err = key.SetDWordValue("AutoDetect", 0) // 0 to disable 38 | if err != nil { 39 | log.Fatalf("Error disabling automatic proxy detection: %v", err) 40 | } 41 | 42 | fmt.Println("SOCKS5 proxy configuration applied successfully.") 43 | 44 | //cmd := exec.Command("netsh", "winhttp", "reset", "proxy") 45 | //err = cmd.Run() 46 | //if err != nil { 47 | // slog.Error("Error resetting proxy settings: ", err) 48 | //} 49 | //log.Println("Network settings refreshed.") 50 | } 51 | func proxySettingOff() { 52 | log.Print("Disabling SOCKS5 proxy settings...") 53 | // Open the registry key for proxy settings 54 | key, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.SET_VALUE) 55 | if err != nil { 56 | log.Fatalf("Error opening registry key: %v", err) 57 | } 58 | defer key.Close() 59 | 60 | // Enable proxy and set proxy server to SOCKS5 61 | err = key.SetDWordValue("ProxyEnable", 0) // 1 to enable proxy 62 | if err != nil { 63 | log.Fatalf("Error enabling proxy: %v", err) 64 | } 65 | 66 | //cmd := exec.Command("netsh", "winhttp", "reset", "proxy") 67 | //err = cmd.Run() 68 | //if err != nil { 69 | // log.Fatalf("Error resetting proxy settings: %v", err) 70 | //} 71 | //log.Println("Network settings refreshed.") 72 | } 73 | -------------------------------------------------------------------------------- /util/geo_ip.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "fmt" 5 | "github.com/oschwald/geoip2-golang" 6 | "net" 7 | ) 8 | 9 | type GeoIP struct { 10 | db *geoip2.Reader 11 | } 12 | 13 | func NewGeoIP(geoIpFilePath string) (*GeoIP, error) { 14 | if geoIpFilePath == "" { 15 | geoIpFilePath = "GeoLite2-Country.mmdb" //https://github.com/P3TERX/GeoLite.mmdb?tab=readme-ov-file 16 | } 17 | db, err := geoip2.Open(geoIpFilePath) 18 | if err != nil { 19 | return nil, err 20 | } 21 | return &GeoIP{db: db}, nil 22 | } 23 | 24 | func (g *GeoIP) Close() error { 25 | if g.db != nil { 26 | return g.db.Close() 27 | } 28 | return nil 29 | } 30 | 31 | func (g *GeoIP) Country(host string) (isoCountryCode string, err error) { 32 | if g == nil { 33 | return "", fmt.Errorf("geo databse is nil") 34 | } 35 | ip := net.ParseIP(host) 36 | if ip == nil { 37 | ips, err := net.LookupIP(host) 38 | if err != nil { 39 | return "", fmt.Errorf("failed to lookup IP: %w", err) 40 | } 41 | if len(ips) == 0 { 42 | return "", fmt.Errorf("no IP found for %s", host) 43 | } 44 | ip = ips[0] 45 | } 46 | record, err := g.db.Country(ip) 47 | if err != nil { 48 | return "", fmt.Errorf("failed to get Country: %w", err) 49 | } 50 | return record.Country.IsoCode, nil 51 | } 52 | -------------------------------------------------------------------------------- /util/geo_ip_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestGeoDns_country(t *testing.T) { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /util/random_string.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | ) 7 | 8 | var ( 9 | stringMisc = []byte(".$#@&*_") 10 | 11 | stringDigit = []byte("1234567890") 12 | stringDigitLen = len(stringDigit) 13 | 14 | stringLword = []byte("abcdefghijklmnopqrstuvwxyz") 15 | stringLwordLen = len(stringLword) 16 | 17 | stringUWord = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ") 18 | stringUWordLen = len(stringUWord) 19 | 20 | stringCWord = []byte(fmt.Sprintf("%s%s", stringLword, stringUWord)) 21 | stringCWordLen = len(stringCWord) 22 | 23 | letterRunes = []byte(fmt.Sprintf("%s%s%s%s", stringDigit, stringLword, stringMisc, stringUWord)) 24 | letterRunesLen = len(letterRunes) 25 | ) 26 | 27 | func RandomString(n int) string { 28 | b := make([]byte, n) 29 | for i := range b { 30 | b[i] = letterRunes[rand.Intn(letterRunesLen)] 31 | } 32 | return string(b) 33 | } 34 | 35 | func RandStringWordL(n int) string { 36 | b := make([]byte, n) 37 | for i := range b { 38 | b[i] = stringLword[rand.Intn(stringLwordLen)] 39 | } 40 | return string(b) 41 | } 42 | 43 | func RandStringWordU(n int) string { 44 | b := make([]byte, n) 45 | for i := range b { 46 | b[i] = stringUWord[rand.Intn(stringUWordLen)] 47 | } 48 | return string(b) 49 | } 50 | func RandStringWordC(n int) string { 51 | b := make([]byte, n) 52 | for i := range b { 53 | b[i] = stringCWord[rand.Intn(stringCWordLen)] 54 | } 55 | return string(b) 56 | } 57 | func RandStringDigit(n int) string { 58 | b := make([]byte, n) 59 | for i := range b { 60 | b[i] = stringDigit[rand.Intn(stringDigitLen)] 61 | } 62 | return string(b) 63 | } 64 | -------------------------------------------------------------------------------- /util/vless_data.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "encoding/binary" 5 | "errors" 6 | "fmt" 7 | "github.com/google/uuid" 8 | "log/slog" 9 | "net" 10 | ) 11 | 12 | type SchemaVLESS struct { 13 | userID uuid.UUID 14 | DstProtocol string //tcp or udp 15 | dstHost string 16 | dstHostType string //ipv6 or ipv4,domain 17 | dstPort uint16 18 | Version byte 19 | payload []byte 20 | } 21 | 22 | func (h SchemaVLESS) UUID() string { 23 | return h.userID.String() 24 | } 25 | 26 | func (h SchemaVLESS) DataUdp() []byte { 27 | allData := make([]byte, 0) 28 | chunk := h.payload 29 | for index := 0; index < len(chunk); { 30 | if index+2 > len(chunk) { 31 | fmt.Println("Incomplete length buffer") 32 | return nil 33 | } 34 | lengthBuffer := chunk[index : index+2] 35 | udpPacketLength := binary.BigEndian.Uint16(lengthBuffer) 36 | if index+2+int(udpPacketLength) > len(chunk) { 37 | fmt.Println("Incomplete UDP packet") 38 | return nil 39 | } 40 | udpData := chunk[index+2 : index+2+int(udpPacketLength)] 41 | index = index + 2 + int(udpPacketLength) 42 | allData = append(allData, udpData...) 43 | } 44 | return allData 45 | } 46 | func (h SchemaVLESS) DataTcp() []byte { 47 | return h.payload 48 | } 49 | 50 | func (h SchemaVLESS) AddrUdp() *net.UDPAddr { 51 | return &net.UDPAddr{IP: h.HostIP(), Port: int(h.dstPort)} 52 | } 53 | func (h SchemaVLESS) HostIP() net.IP { 54 | ip := net.ParseIP(h.dstHost) 55 | if ip == nil { 56 | ips, err := net.LookupIP(h.dstHost) 57 | if err != nil { 58 | h.Logger().Error("failed to resolve domain", "err", err.Error()) 59 | return net.IPv4zero 60 | } 61 | if len(ips) == 0 { 62 | return net.IPv4zero 63 | } 64 | return ips[0] 65 | } 66 | return ip 67 | } 68 | 69 | func (h SchemaVLESS) HostPort() string { 70 | return net.JoinHostPort(h.dstHost, fmt.Sprintf("%d", h.dstPort)) 71 | } 72 | func (h SchemaVLESS) Logger() *slog.Logger { 73 | return slog.With("userID", h.userID.String(), "network", h.DstProtocol, "addr", h.HostPort()) 74 | } 75 | 76 | // VlessParse https://xtls.github.io/development/protocols/vless.html 77 | func VlessParse(buf []byte) (*SchemaVLESS, error) { 78 | payload := &SchemaVLESS{ 79 | userID: uuid.Nil, 80 | DstProtocol: "", 81 | dstHost: "", 82 | dstPort: 0, 83 | Version: 0, 84 | payload: nil, 85 | } 86 | 87 | if len(buf) < 24 { 88 | return payload, errors.New("invalid payload length") 89 | } 90 | 91 | payload.Version = buf[0] 92 | payload.userID = uuid.Must(uuid.FromBytes(buf[1:17])) 93 | extraInfoProtoBufLen := buf[17] 94 | 95 | command := buf[18+extraInfoProtoBufLen] 96 | switch command { 97 | case 1: 98 | payload.DstProtocol = "tcp" 99 | case 2: 100 | payload.DstProtocol = "udp" 101 | default: 102 | return payload, fmt.Errorf("command %d is not supported, command 01-tcp, 02-udp, 03-mux", command) 103 | } 104 | 105 | portIndex := 18 + extraInfoProtoBufLen + 1 106 | payload.dstPort = binary.BigEndian.Uint16(buf[portIndex : portIndex+2]) 107 | 108 | addressIndex := portIndex + 2 109 | addressType := buf[addressIndex] 110 | addressValueIndex := addressIndex + 1 111 | 112 | switch addressType { 113 | case 1: // IPv4 114 | if len(buf) < int(addressValueIndex+net.IPv4len) { 115 | return nil, fmt.Errorf("invalid IPv4 address length") 116 | } 117 | payload.dstHost = net.IP(buf[addressValueIndex : addressValueIndex+net.IPv4len]).String() 118 | payload.payload = buf[addressValueIndex+net.IPv4len:] 119 | payload.dstHostType = "ipv4" 120 | case 2: // domain 121 | addressLength := buf[addressValueIndex] 122 | addressValueIndex++ 123 | if len(buf) < int(addressValueIndex)+int(addressLength) { 124 | return nil, fmt.Errorf("invalid domain address length") 125 | } 126 | payload.dstHost = string(buf[addressValueIndex : int(addressValueIndex)+int(addressLength)]) 127 | payload.payload = buf[int(addressValueIndex)+int(addressLength):] 128 | payload.dstHostType = "domain" 129 | 130 | case 3: // IPv6 131 | if len(buf) < int(addressValueIndex+net.IPv6len) { 132 | return nil, fmt.Errorf("invalid IPv6 address length") 133 | } 134 | payload.dstHost = net.IP(buf[addressValueIndex : addressValueIndex+net.IPv6len]).String() 135 | payload.payload = buf[addressValueIndex+net.IPv6len:] 136 | payload.dstHostType = "ipv6" 137 | default: 138 | return nil, fmt.Errorf("addressType %d is not supported", addressType) 139 | } 140 | 141 | return payload, nil 142 | } 143 | --------------------------------------------------------------------------------