├── php-proxy.syso ├── openwrt ├── php-proxy_2.1.4-220416.46774_x86_64.ipk ├── README.md └── Makefile ├── php-proxy.json ├── php-proxy.go ├── compression.go ├── server ├── README.md ├── index_v3_2_6.php ├── index.php └── index.js ├── go.mod ├── encryption.go ├── php-proxy.crt ├── php-proxy.key ├── response.go ├── request.go ├── casigner.go ├── README.md ├── client.go ├── config.go ├── proxy.go └── LICENSE /php-proxy.syso: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/koalabearguo/php-proxy/HEAD/php-proxy.syso -------------------------------------------------------------------------------- /openwrt/php-proxy_2.1.4-220416.46774_x86_64.ipk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/koalabearguo/php-proxy/HEAD/openwrt/php-proxy_2.1.4-220416.46774_x86_64.ipk -------------------------------------------------------------------------------- /openwrt/README.md: -------------------------------------------------------------------------------- 1 | Makefile for openwrt package build 2 | So far config json file in /etc/php-proxy/php-proxy.json is not used,feature will be fixed 3 | -------------------------------------------------------------------------------- /php-proxy.json: -------------------------------------------------------------------------------- 1 | { 2 | "fetchserver": "https://a.bc.com/go/index.php", 3 | "password": "123456", 4 | "sni": "a.bc.com", 5 | "listen": "127.0.0.1:8081", 6 | "debug": false, 7 | "http3": false, 8 | "insecure": false, 9 | "autoproxy": true, 10 | "user-agent": "", 11 | "proxy":"", 12 | "ca": "", 13 | "key": "" 14 | } 15 | -------------------------------------------------------------------------------- /php-proxy.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | ) 7 | 8 | func main() { 9 | // 10 | log.SetOutput(os.Stdout) 11 | log.SetFlags(log.LstdFlags | log.Lshortfile) 12 | // 13 | config := &config{} 14 | config.init_config() 15 | // 16 | prx := &proxy{cfg: config} 17 | prx.init_proxy() 18 | // 19 | select {} 20 | } 21 | -------------------------------------------------------------------------------- /compression.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "compress/flate" 6 | "io" 7 | "log" 8 | ) 9 | 10 | type compress struct { 11 | cfg *config 12 | level int 13 | } 14 | 15 | func (c *compress) deflate_compress(dst_buf *bytes.Buffer, src_buf io.Reader) { 16 | 17 | flateWrite, _ := flate.NewWriter(dst_buf, c.level) 18 | if _, err := io.Copy(flateWrite, src_buf); err != nil { 19 | if err != io.ErrUnexpectedEOF { 20 | log.Print(err) 21 | } 22 | } 23 | // 24 | flateWrite.Flush() 25 | flateWrite.Close() 26 | // 27 | } 28 | 29 | func (c *compress) deflate_uncompress(dst_buf *bytes.Buffer, src_buf io.Reader) { 30 | 31 | flateReader := flate.NewReader(src_buf) 32 | 33 | io.Copy(dst_buf, flateReader) 34 | flateReader.Close() 35 | } 36 | -------------------------------------------------------------------------------- /server/README.md: -------------------------------------------------------------------------------- 1 | # index_v3_2_6.php 2 | - 该文件兼容goagent php模式; 3 | - goagent php客户端均可使用,不限于这里以golang重构的版本 4 | 5 | # index.php 6 | - 该文件v3.3.0(包括)之后已经不兼容goagent php模式; 7 | - 为了优化服务端的传输延时和服务端性能,最新的index.php支持chunked内容编码 8 | - 使用该版本服务端文件时,建议使用php-proxy v2.1.4(包括)以上版本 9 | 10 | # index.js 11 | - 该文件是部署在Cloudflare Wokers上使用的,目前基本功能已经完成,属于测试阶段。 12 | - 使用该版本服务端文件时,建议使用php-proxy v2.1.4(包括)以上版本 13 | - 由于workers上没有广告,所以基本的XOR加密去掉了。 14 | - 脚本实现参考项目[GotoX](https://github.com/SeaHOH/GotoX),非常感谢作者,如有侵权,删 15 | - 为什么实现了js版本?因为Workers快啊,太快了,体验太好了! 16 | - 下面是配置参考,fetchserver填入Workers地址就可以了 17 | ``` 18 | { 19 | "fetchserver": "https://inner-free-9539.domain.workers.dev/", 20 | "password": "123456", 21 | "sni": "", 22 | "listen": "127.0.0.1:8080", 23 | "debug": false, 24 | "insecure": false, 25 | "autoproxy": false, 26 | "user-agent": "", 27 | "proxy": "" 28 | } 29 | ``` 30 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/koalabearguo/php-proxy 2 | 3 | go 1.18 4 | 5 | require github.com/quic-go/quic-go v0.32.0 6 | 7 | require ( 8 | github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 // indirect 9 | github.com/golang/mock v1.6.0 // indirect 10 | github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 // indirect 11 | github.com/onsi/ginkgo/v2 v2.2.0 // indirect 12 | github.com/quic-go/qpack v0.4.0 // indirect 13 | github.com/quic-go/qtls-go1-18 v0.2.0 // indirect 14 | github.com/quic-go/qtls-go1-19 v0.2.0 // indirect 15 | github.com/quic-go/qtls-go1-20 v0.1.0 // indirect 16 | golang.org/x/crypto v0.4.0 // indirect 17 | golang.org/x/exp v0.0.0-20221205204356-47842c84f3db // indirect 18 | golang.org/x/mod v0.6.0 // indirect 19 | golang.org/x/net v0.4.0 // indirect 20 | golang.org/x/sys v0.3.0 // indirect 21 | golang.org/x/text v0.5.0 // indirect 22 | golang.org/x/tools v0.2.0 // indirect 23 | ) 24 | -------------------------------------------------------------------------------- /encryption.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "io/ioutil" 7 | ) 8 | 9 | type encrypt struct { 10 | cfg *config 11 | rc io.ReadCloser 12 | } 13 | 14 | func (e *encrypt) content_decrypt(dst_buf *bytes.Buffer, src_buf io.Reader) { 15 | 16 | var key []byte 17 | b, _ := ioutil.ReadAll(src_buf) 18 | if e.cfg.Password != "" { 19 | key = []byte(e.cfg.Password) 20 | } else { 21 | key = []byte{0} 22 | } 23 | for i := 0; i < len(b); i++ { 24 | b[i] = b[i] ^ key[0] 25 | } 26 | dst_buf.Write(b) 27 | 28 | } 29 | func (e *encrypt) decrypt_reader(src_buf io.ReadCloser) io.ReadCloser { 30 | e.rc = src_buf 31 | return e 32 | } 33 | 34 | func (e *encrypt) Close() error { 35 | return e.rc.Close() 36 | } 37 | 38 | func (e *encrypt) Read(p []byte) (n int, err error) { 39 | var key []byte 40 | n, err = e.rc.Read(p) 41 | if e.cfg.Password != "" { 42 | key = []byte(e.cfg.Password) 43 | } else { 44 | key = []byte{0} 45 | } 46 | for i := 0; i < n; i++ { 47 | p[i] ^= key[0] 48 | } 49 | 50 | return n, err 51 | } 52 | -------------------------------------------------------------------------------- /php-proxy.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDvTCCAqWgAwIBAgIJAJ6lzaYHcaNcMA0GCSqGSIb3DQEBCwUAMHUxCzAJBgNV 3 | BAYTAkNOMREwDwYDVQQIDAhJbnRlcm5ldDEPMA0GA1UEBwwGQ2VybmV0MRIwEAYD 4 | VQQKDAlQaHAtUHJveHkxFzAVBgNVBAsMDlBocC1Qcm94eSBSb290MRUwEwYDVQQD 5 | DAxQaHAtUHJveHkgQ0EwHhcNMjEwNzE2MDEyNDU2WhcNMzEwNzE0MDEyNDU2WjB1 6 | MQswCQYDVQQGEwJDTjERMA8GA1UECAwISW50ZXJuZXQxDzANBgNVBAcMBkNlcm5l 7 | dDESMBAGA1UECgwJUGhwLVByb3h5MRcwFQYDVQQLDA5QaHAtUHJveHkgUm9vdDEV 8 | MBMGA1UEAwwMUGhwLVByb3h5IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB 9 | CgKCAQEAyoA89JBn6tpag1JFNO3kGWaq1wUPIB0Kil00SOW/IXB1riLMo/l3Utc6 10 | k6BDHRugeyq34NQDEF4AVt3Gb7gxCh/zbFnPaDT9T5i9QGtIs4hp+L+/LofC11WQ 11 | V9xf5G9v2c75JYbjMhp41wfQH2j/zHvjA7LWNE/DXHrU3TOBVhqE8WYXEe1uORag 12 | 13sVWUiTGGu3UCzEZs5H7tZ2mPgSddXrreJ7YtYy8DheA4FsYhD1AK/xj2MrpErL 13 | iy/F86LgimBuAQ01AHccPBrtyY928JBBaPCp++FCmoqf+hpAvN1YiAgny0aPIjsa 14 | VPXs+eEpiqI4RTMuYSfek/l8JTcxNwIDAQABo1AwTjAdBgNVHQ4EFgQUctnJSBh5 15 | IW+81UYIirzu6o/AOl0wHwYDVR0jBBgwFoAUctnJSBh5IW+81UYIirzu6o/AOl0w 16 | DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEACHU/rXn2ERHRSXq8V64l 17 | /97ozE1Sbv54ehWnMAY2prSdXnMQXftFPd7FXz8NwkfqjwsdEjV2o5lpZ/J9seDn 18 | SbTHqiBlo5M7HmN2K+WCMfRhv9hNI2+6IeUfwxhkHrsRTsq7og/UnSODF68Jy2g7 19 | HZmAQFc6dy//GQR4zM8afDhlDSGH23Pgl2lwagQTNtzl2PrCiRh8J9F7cOfMqL0A 20 | Ee2VElNdCS8MR9OGPw/MSo6lWX7g4aWxYa7oajmvT6bgfU9+2rQ/tjldfWyyoCMw 21 | ap/s6xLfzLWwZ+NVShcWiC4l9Dwfkig1z/CWISuvROAMAI58j3BNG8xqcf4iJiuo 22 | gA== 23 | -----END CERTIFICATE----- 24 | -------------------------------------------------------------------------------- /php-proxy.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDKgDz0kGfq2lqD 3 | UkU07eQZZqrXBQ8gHQqKXTRI5b8hcHWuIsyj+XdS1zqToEMdG6B7Krfg1AMQXgBW 4 | 3cZvuDEKH/NsWc9oNP1PmL1Aa0iziGn4v78uh8LXVZBX3F/kb2/ZzvklhuMyGnjX 5 | B9AfaP/Me+MDstY0T8NcetTdM4FWGoTxZhcR7W45FqDXexVZSJMYa7dQLMRmzkfu 6 | 1naY+BJ11eut4nti1jLwOF4DgWxiEPUAr/GPYyukSsuLL8XzouCKYG4BDTUAdxw8 7 | Gu3Jj3bwkEFo8Kn74UKaip/6GkC83ViICCfLRo8iOxpU9ez54SmKojhFMy5hJ96T 8 | +XwlNzE3AgMBAAECggEAfTX7+tDLoJjxPKADMO4ji11DJ372UkoCuXlWGfkNTJTn 9 | /wt/c6iOEogIrT18IiRx/5Zzai5N0rH9DblFuNCwae1Fq+qAZ5PUSYJNCucLZg9k 10 | Ty3o/dFuNY2vmdQm6u3IwGnM/lpAYzuhGny3QKTA/mRgA2pyLphfWPCObFQrldvo 11 | D8/HkPIrWP7eeRhDFBuYH2Y8evBW+JJ0xKWWyxnwpYnOvfQP/bb38M9weSmB6oC+ 12 | XHnWruCldNLrGwVZsgiuvoh/zIXOQlXRz7U9dT/VJZQGGPdiC49rSN8Q5/qKkPST 13 | 1sc2ujmbJpHRtjKtCdBLD/yHNVjbF1cVk2AmPkyGqQKBgQDu+r+7sCruZ+q0ixEm 14 | v7YoMIPouZuuv9wePQL5kwmLqmhZq0vyObcSCRfg5P9oONDB53WNmDjvPEEImQbU 15 | EPmvGofbGVaaTYnbAXmZA50IZElrsPfwZdvRBgMB6gVuPPuHmfStWo+bOEsTml0u 16 | wsa7obEb5giDzjzP22tt2mil/QKBgQDY7GKTP5WUqdgp+1gig5IMu4EpoidrmdWr 17 | U7hKB/R6p+ihrCX1xu/TdZAb7bGFya1O60LsnnQ3iF/heNTWOBUYgDGia6eaEpc1 18 | /K5zis055WoEu5hAebqgr+0VJUEiqGuBUnpqyHLXr8LHf3g7cSU5/4KbCu+1paXu 19 | 2/9MMY7AQwKBgFlIu3t+3PtHPcwILPdCJucrAQ1g0wZdzfpKJyNhSO6yUtw1gGFW 20 | KMyHMzGlvLqOh4f6VtP47ESNSWrR6Vgvo2lFSz6TX+S0VW3KRkjhrbil5zxh2LAr 21 | Dg4w5czARxkhlYPbBCwEKqT+SiZfxLKkuKT/SvE2ZzX/Rn8N5jwbnn9tAoGAcVeZ 22 | 7fxEKOhRxSXKGEaM0lBKnblXRZacmSdmXHAposkG+Sqcrv3iI6gCw0UAA7qr7ldo 23 | oX/tk3KTPplHBCNLioC47ne3m/5oudGsSTzWHJEtQwnN9KpmBD3H78uGbBh6C5lP 24 | 02mm7+GrMVf+N3jYDaTe1inxtAS4XcTfcS1XvEcCgYEAiohDWwiDO/GQloKPuZWc 25 | gVEJoAty/LbU/TyW+i3bM94rcJLKY8ySPBmTQb+ifeqvSRo4W2zv3tQ5lBag77y3 26 | pRYFQzk5UG6yo4V0/oo2UUSDY0UoxX9lVNcJvYVwPcNwKHnX9a9fRrlf3o+c5rrE 27 | jIxm1tgZheqRxqpv1LwQ4hQ= 28 | -----END PRIVATE KEY----- 29 | -------------------------------------------------------------------------------- /openwrt/Makefile: -------------------------------------------------------------------------------- 1 | 2 | include $(TOPDIR)/rules.mk 3 | 4 | PKG_NAME:=php-proxy 5 | PKG_VERSION:=2.1.4 6 | PKG_RELEASE:=$(AUTORELEASE) 7 | 8 | PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz 9 | PKG_SOURCE_URL:=https://codeload.github.com/koalabearguo/php-proxy/tar.gz/v$(PKG_VERSION)? 10 | PKG_HASH:=203d74a8c4b2dec28ab07e247f14737dd1edf110a0c6f3805d5e3634fc7545f6 11 | 12 | PKG_LICENSE:=GPL 13 | PKG_LICENSE_FILE:=LICENSE 14 | PKG_MAINTAINER:=koala 15 | 16 | PKG_BUILD_DEPENDS:=golang/host 17 | PKG_BUILD_PARALLEL:=1 18 | PKG_USE_MIPS16:=0 19 | 20 | GO_PKG:=github.com/koalabearguo/php-proxy 21 | 22 | include $(INCLUDE_DIR)/package.mk 23 | include $(TOPDIR)/feeds/packages/lang/golang/golang-package.mk 24 | 25 | define Package/php-proxy/Default 26 | SECTION:=net 27 | CATEGORY:=Network 28 | #SUBMENU:=File Transfer 29 | TITLE:=php-proxy for agent web content via php/js 30 | URL:=https://github.com/koalabearguo/php-proxy 31 | endef 32 | 33 | define Package/php-proxy 34 | $(call Package/php-proxy/Default) 35 | DEPENDS:=$(GO_ARCH_DEPENDS) 36 | endef 37 | 38 | define Package/php-proxy/description 39 | php-proxy for agent web content via php/js 40 | endef 41 | 42 | define Package/php-proxy/conffiles 43 | /etc/php-proxy/php-proxy.json 44 | endef 45 | 46 | define Build/Prepare 47 | $(call Build/Prepare/Default) 48 | (cd $(PKG_BUILD_DIR); \ 49 | $(RM) -fr php-proxy.syso; \ 50 | echo "module github.com/koalabearguo/php-proxy" > go.mod; \ 51 | echo "" >> go.mod; \ 52 | echo "go 1.15" >> go.mod \ 53 | ) 54 | endef 55 | 56 | define Package/php-proxy/install 57 | $(call GoPackage/Package/Install/Bin,$(PKG_INSTALL_DIR)) 58 | $(INSTALL_DIR) $(1)/usr/bin/ 59 | $(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/php-proxy $(1)/usr/bin/ 60 | $(INSTALL_DIR) $(1)/etc/php-proxy 61 | cat $(PKG_BUILD_DIR)/php-proxy.json > $(1)/etc/php-proxy/php-proxy.json 62 | endef 63 | 64 | $(eval $(call GoBinPackage,php-proxy)) 65 | $(eval $(call BuildPackage,php-proxy)) 66 | -------------------------------------------------------------------------------- /response.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "io" 7 | "log" 8 | "net/http" 9 | "strconv" 10 | //"strings" 11 | "time" 12 | ) 13 | 14 | type response struct { 15 | res *http.Response 16 | cfg *config 17 | } 18 | 19 | var ResDeleteHeader = []string{"Upgrade", "Alt-Svc", "Alternate-Protocol", "Expect-CT", "Report-To", "Nel"} 20 | 21 | func (res *response) patch_response(r *bufio.Reader, req *http.Request) (resp *http.Response, error error) { 22 | // 23 | prefix := make([]byte, 7) 24 | n, err := io.ReadFull(r, prefix) 25 | if err != nil { 26 | return nil, err 27 | } 28 | // 29 | if string(prefix[:n]) == "HTTP/2 " { 30 | // fix HTTP/2 proto 31 | resp, error = http.ReadResponse(bufio.NewReader(io.MultiReader(bytes.NewBufferString("HTTP/2.0 "), r)), req) 32 | } else if string(prefix[:n]) == "HTTP/3 " { 33 | // fix HTTP/3 proto(feature may has this issue) 34 | resp, error = http.ReadResponse(bufio.NewReader(io.MultiReader(bytes.NewBufferString("HTTP/3.0 "), r)), req) 35 | } else { 36 | // other proto 37 | resp, error = http.ReadResponse(bufio.NewReader(io.MultiReader(bytes.NewBuffer(prefix[:n]), r)), req) 38 | } 39 | // 40 | return resp, error 41 | } 42 | 43 | func (res *response) parse_response() *http.Response { 44 | // 45 | if res.cfg.Debug { 46 | for k, v := range res.res.Header { 47 | for _, value := range v { 48 | log.Print(k + ":" + value) 49 | } 50 | } 51 | for _, chunkstr := range res.res.TransferEncoding { 52 | log.Print("Transfer-Encoding" + ":" + chunkstr) 53 | } 54 | if res.res.Uncompressed { 55 | log.Print("Content-Encoding" + ":" + "compressed") 56 | } 57 | } 58 | encrypt := &encrypt{cfg: res.cfg} 59 | // 60 | if res.res.StatusCode != http.StatusOK { 61 | return res.res 62 | } 63 | start := time.Now() 64 | if res.res.Header.Get("Content-Type") == "image/gif" && res.res.Body != nil { 65 | res.res.Body = encrypt.decrypt_reader(res.res.Body) 66 | } 67 | if res.cfg.Debug { 68 | elapsed := time.Since(start) 69 | log.Println("First Data Decrypt Time:", elapsed) 70 | } 71 | // 72 | //return res.res //for test 73 | //resp, err := http.ReadResponse(bufio.NewReader(res.res.Body), res.res.Request) 74 | resp, err := res.patch_response(bufio.NewReader(res.res.Body), res.res.Request) 75 | if err != nil { 76 | log.Println(err) 77 | return res.res 78 | } 79 | // 80 | if resp.Header.Get("Content-Length") == "" && resp.ContentLength >= 0 { 81 | resp.Header.Set("Content-Length", strconv.FormatInt(resp.ContentLength, 10)) 82 | } 83 | // 84 | for _, h := range ResDeleteHeader { 85 | resp.Header.Del(h) 86 | } 87 | // 88 | return resp 89 | } 90 | -------------------------------------------------------------------------------- /request.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "compress/flate" 6 | "io" 7 | "log" 8 | "net/http" 9 | //"strconv" 10 | ) 11 | 12 | type request struct { 13 | //http request header 14 | http_req *http.Request 15 | //Client request 16 | cli_req *http.Request 17 | //cfg 18 | cfg *config 19 | //client.Body io.ReadCloser interface impl 20 | readers []io.Reader 21 | multiReader io.Reader 22 | } 23 | 24 | var ( 25 | ReqDeleteHeader = map[string]bool{ 26 | //disable websocket upgrade 27 | "Upgrade": true, 28 | "Sec-Websocket-Key": true, 29 | "Sec-Websocket-Version": true, 30 | "Sec-Websocket-Extensions": true, 31 | "Sec-WebSocket-Protocol": true, 32 | "Vary": true, 33 | "Via": true, 34 | "X-Forwarded-For": true, 35 | "Proxy-Authorization": true, 36 | "Proxy-Connection": true, 37 | "X-Chrome-Variations": true, 38 | //"Connection": true, 39 | "Cache-Control": true, 40 | } 41 | ) 42 | 43 | func (req *request) MultiReader(readers ...io.Reader) io.ReadCloser { 44 | req.readers = readers 45 | req.multiReader = io.MultiReader(readers...) 46 | return req 47 | } 48 | 49 | func (req *request) Read(p []byte) (n int, err error) { 50 | return req.multiReader.Read(p) 51 | } 52 | 53 | func (req *request) Close() (err error) { 54 | for _, r := range req.readers { 55 | if c, ok := r.(io.Closer); ok { 56 | if e := c.Close(); e != nil { 57 | err = e 58 | } 59 | } 60 | } 61 | return err 62 | } 63 | 64 | func (req *request) parse_request() { 65 | // 66 | com := &compress{cfg: req.cfg} 67 | //com.level = flate.NoCompression 68 | //com.level = flate.BestSpeed 69 | com.level = flate.BestCompression 70 | // 71 | //process header 72 | header_buf := bytes.NewBuffer(nil) 73 | deflare_header_buf := bytes.NewBuffer(nil) 74 | var req_line string 75 | req_line = req.http_req.Method + " " + req.http_req.URL.String() + " " + req.http_req.Proto 76 | log.Print("PHP " + req_line) 77 | _, err := header_buf.WriteString(req_line + "\r\n") 78 | if err != nil { 79 | log.Printf("%s", err) 80 | } 81 | // 82 | req.http_req.Header.Add("X-URLFETCH-password", req.cfg.Password) 83 | // 84 | //for feature use(index.php need upgrade) 85 | if req.cfg.Insecure { 86 | req.http_req.Header.Add("X-URLFETCH-insecure", "1") 87 | } 88 | // 89 | req.http_req.Header.WriteSubset(header_buf, ReqDeleteHeader) 90 | // 91 | if req.cfg.Debug { 92 | for k, v := range req.http_req.Header { 93 | for _, value := range v { 94 | log.Print(k + ":" + value) 95 | } 96 | } 97 | } 98 | // 99 | com.deflate_compress(deflare_header_buf, header_buf) 100 | // 101 | //pack (header length may biger than 65536 bytes) 102 | var length [2]byte 103 | if deflare_header_buf.Len() < 65536 { 104 | length[0] = byte(deflare_header_buf.Len() / 256) 105 | length[1] = byte(deflare_header_buf.Len() % 256) 106 | } else { 107 | log.Fatal("request header too big") 108 | } 109 | // 110 | req.cli_req = &http.Request{ 111 | Method: http.MethodPost, 112 | Header: http.Header{}, 113 | } 114 | //default use brower UA 115 | req.cli_req.Header.Set("User-Agent", req.http_req.Header.Get("User-Agent")) 116 | // 117 | if req.http_req.ContentLength > 0 { 118 | req.cli_req.ContentLength = int64(len(length)+deflare_header_buf.Len()) + req.http_req.ContentLength 119 | req.cli_req.Body = req.MultiReader(bytes.NewReader(length[:]), deflare_header_buf, req.http_req.Body) 120 | } else if req.http_req.ContentLength == -1 { 121 | req.cli_req.ContentLength = -1 122 | req.cli_req.Body = req.MultiReader(bytes.NewReader(length[:]), deflare_header_buf, req.http_req.Body) 123 | log.Print("!!!POST data chunked!!!,you may report this to author about how to happen? this feature not support so far.") 124 | } else { 125 | req.cli_req.ContentLength = int64(len(length) + deflare_header_buf.Len()) 126 | req.cli_req.Body = req.MultiReader(bytes.NewReader(length[:]), deflare_header_buf) 127 | } 128 | // 129 | 130 | } 131 | -------------------------------------------------------------------------------- /casigner.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rsa" 5 | "crypto/sha1" 6 | "crypto/tls" 7 | "crypto/x509" 8 | "math/big" 9 | mrand "math/rand" 10 | "net" 11 | "sort" 12 | "strings" 13 | "sync" 14 | "time" 15 | ) 16 | 17 | // CaSigner is a certificate signer by CA certificate. It supports caching. 18 | type CaSigner struct { 19 | // Ca specifies CA certificate. You must set before using. 20 | Ca *tls.Certificate 21 | 22 | mu sync.RWMutex 23 | certMap map[string]*tls.Certificate 24 | certList []string 25 | certIndex int 26 | certMax int 27 | } 28 | 29 | // NewCaSigner returns a new CaSigner without caching. 30 | func NewCaSigner() *CaSigner { 31 | return NewCaSignerCache(0) 32 | } 33 | 34 | // NewCaSignerCache returns a new CaSigner with caching given max. 35 | func NewCaSignerCache(max int) *CaSigner { 36 | if max < 0 { 37 | max = 0 38 | } 39 | return &CaSigner{ 40 | certMap: make(map[string]*tls.Certificate), 41 | certList: make([]string, max), 42 | certIndex: 0, 43 | certMax: max, 44 | } 45 | } 46 | 47 | // SignHost generates TLS certificate given single host, signed by CA certificate. 48 | func (c *CaSigner) SignHost(host string) (cert *tls.Certificate) { 49 | if host == "" { 50 | return 51 | } 52 | host = WildcardHost(host) 53 | if c.certMax <= 0 { 54 | crt, err := SignHosts(*c.Ca, []string{host}) 55 | if err != nil { 56 | return nil 57 | } 58 | cert = crt 59 | return 60 | } 61 | func() { 62 | c.mu.RLock() 63 | defer c.mu.RUnlock() 64 | cert = c.certMap[host] 65 | }() 66 | if cert != nil { 67 | return 68 | } 69 | c.mu.Lock() 70 | defer c.mu.Unlock() 71 | cert = c.certMap[host] 72 | if cert != nil { 73 | return 74 | } 75 | crt, err := SignHosts(*c.Ca, []string{host}) 76 | if err != nil { 77 | return nil 78 | } 79 | cert = crt 80 | if len(c.certMap) >= c.certMax { 81 | delete(c.certMap, c.certList[c.certIndex]) 82 | } 83 | c.certMap[host] = cert 84 | c.certList[c.certIndex] = host 85 | c.certIndex++ 86 | if c.certIndex >= c.certMax { 87 | c.certIndex = 0 88 | } 89 | return 90 | } 91 | 92 | // SignHosts generates TLS certificate given hosts, signed by CA certificate. 93 | func SignHosts(ca tls.Certificate, hosts []string) (*tls.Certificate, error) { 94 | x509ca, err := x509.ParseCertificate(ca.Certificate[0]) 95 | if err != nil { 96 | return nil, err 97 | } 98 | //start := time.Unix(0, 0) 99 | start := time.Now() 100 | //end, _ := time.Parse("2006-01-02", "2031-01-19") 101 | serial := hashSortedBigInt(append(hosts, "1")) 102 | template := x509.Certificate{ 103 | SerialNumber: serial, 104 | Issuer: x509ca.Subject, 105 | Subject: x509ca.Subject, 106 | NotBefore: start, 107 | //NotAfter: end, 108 | NotAfter: x509ca.NotAfter, 109 | KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, 110 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, 111 | BasicConstraintsValid: true, 112 | } 113 | template.Subject.CommonName = hosts[0] 114 | for _, h := range hosts { 115 | h = stripPort(h) 116 | if ip := net.ParseIP(h); ip != nil { 117 | template.IPAddresses = append(template.IPAddresses, ip) 118 | } else { 119 | template.DNSNames = append(template.DNSNames, h) 120 | } 121 | } 122 | rnd := mrand.New(mrand.NewSource(serial.Int64())) 123 | certPriv, err := rsa.GenerateKey(rnd, 1024) 124 | if err != nil { 125 | return nil, err 126 | } 127 | derBytes, err := x509.CreateCertificate(rnd, &template, x509ca, &certPriv.PublicKey, ca.PrivateKey) 128 | if err != nil { 129 | return nil, err 130 | } 131 | return &tls.Certificate{ 132 | Certificate: [][]byte{derBytes, ca.Certificate[0]}, 133 | PrivateKey: certPriv, 134 | }, nil 135 | } 136 | 137 | func hashSorted(lst []string) []byte { 138 | c := make([]string, len(lst)) 139 | copy(c, lst) 140 | sort.Strings(c) 141 | h := sha1.New() 142 | for _, s := range c { 143 | h.Write([]byte(s + ",")) 144 | } 145 | return h.Sum(nil) 146 | } 147 | 148 | func hashSortedBigInt(lst []string) *big.Int { 149 | rv := new(big.Int) 150 | rv.SetBytes(hashSorted(lst)) 151 | return rv 152 | } 153 | 154 | func stripPort(s string) string { 155 | ix := strings.IndexRune(s, ':') 156 | if ix == -1 { 157 | return s 158 | } 159 | return s[:ix] 160 | } 161 | 162 | func WildcardHost(host string) string { 163 | if ip := net.ParseIP(host); ip != nil { 164 | return host 165 | } else { 166 | domain := strings.Split(host, ".") 167 | if len(domain[len(domain)-1]) >= 3 && len(domain) >= 3 { 168 | h := strings.Replace(host, domain[0], "*", 1) 169 | return h 170 | } else { 171 | return host 172 | } 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # php-proxy 2 | 最近在学习golang,闲来无聊就找个项目把它用golang写了一遍,嗯,golang真香; 3 | 本项目主要实现的是GoAgent的php代理模式,协议兼容GoAgent php模式; 4 | 目前本项目已经支持Cloudflare Wokers(服务端文件server/index.js); 5 | 本项目主要用于个人学习,研究免费php/Cloudflare Wokers空间的用途,严禁用于非法用途,后果自负 6 | 7 | ### 特别提示 8 | - server目录下最新的index.php,已经不在兼容goagent php模式 9 | 10 | ### 特性以及改进 11 | - 在连接php server时,https模式支持TLS sni的发送,可以用来穿过CDN,尤其是cloudflare 12 | - 支持自定义TLS SNI的发送,可以用来欺骗xxx 13 | - 代理模式添加支持HTTP OPTIONS请求,chrome浏览器会用OPTIONS方法 14 | - 修复了curl请求出错时,返回的数据还是加密(简单XOR运算)的小问题 15 | - 修复了hostsdeny匹配时,返回的数据还是加密(简单XOR运算)的小问题 16 | - 屏蔽websocket协议,这种双向的通信协议,支持不好 17 | - 支持HTTP2,server与client保持一个连接,端口复用性能提升 18 | - 由于php-proxy.crt/key根证书公钥私钥公开了,这里在检测到以公开根证书作为根的中间人(php server),就会断开与服务器的通信 19 | - 为了安全性以及使用的灵活性,添加支持自定义CA 20 | - 支持`HTTP3`,测试可以跟cloudflare CDN通信 21 | - 支持智能代理模式 22 | - 支持自定义User-Agent(UA) 23 | - 支持前置代理功能(目前支持的协议有http,https,socks5) 24 | - php服务端支持chunked编码代理内容 25 | - 服务端支持CloudFlare Workers(index.js在server目录下) 26 | - 支持安装到openwrt 27 | 28 | ### 协议分析 29 | - 简单的来讲就是把客户端请求的数据(头+Body),打包POST到php server,格式如下: 30 | |2 byte(header length)| + |header(deflate压缩)| + |body| = POST Body,其中header中的第一行的url路径是绝对路径; 31 | 返回的响应Body就是代理到的所有数据(头+Body),经过解密后发送到浏览器客户端 32 | - GoAgent由于python ssl版本的问题,在向https server发送请求时,并不会发送tls中的sni扩展,当然Host头还是会发的,不过这样好像不能穿过CDN,试过cloudflare,请求不成功 33 | - 这种模式的代理相当于经过了三级的代理,本机算一级,php server算一级,curl算一级,所以延时有点高,小流量使用还行吧 34 | - 这种代理只能代理http/https连接,当然curl应该是支持ftp的,不过CONNECT请求信息中,我们并不能知道接下来要走什么协议,默认是处理成https了 35 | - 这个简单的XOR加密是真的不错,虽然不能保证数据安全,但是放到有广告的php免费空间中,乱码中主机商不知道怎么插入广告了。。。具有广告过滤的功能了,哈哈哈 36 | 37 | ### 使用 38 | 1. 把php-proxy.crt CA证书导入到系统中 39 | 2. 把index.php上传到一个(免费的)php空间中,位置名称随意,记下php文件的网络地址(这里最好用一个CDN加速,例如cloudflare,因为免费空间基本速度不快) 40 | 3. 在右侧release下载对应平台的可执行文件(这里也可以自己根据go文件生成,cmd命令窗口/linux终端下,切换到当前目录,直接go build \*.go([参考](https://github.com/koalabearguo/php-proxy/wiki))就可以了,如果构建失败,请升级go版本) 41 | 4. cmd命令窗口/linux终端执行php-proxy -s php文件的网络地址,这时本地127.0.0.1:8081就是一个http proxy 42 | ``` 43 | #windows监听127.0.0.1:8080 44 | php-proxy.exe -s https://xxx.xx/free/index.php -l 127.0.0.1:8080 45 | 46 | #linux默认监听127.0.0.1:8081 47 | #php 地址https://xxx.xx/free/index.php 48 | php-proxy -s https://xxxx.xx/proxy/index.php 49 | ``` 50 | 5. 设置浏览器的http proxy地址127.0.0.1:8081 51 | 6. 在浏览器中输入你想浏览的网页... 52 | 7. 更多使用详情可以执行php-proxy -h获取 53 | ``` 54 | -d enable debug mode for debug 55 | -k insecure connect to php server(ignore certs verify/middle attack) 56 | -l string 57 | Local listen address(HTTP Proxy address) (default "127.0.0.1:8081") 58 | -p string 59 | php server password (default "123456") 60 | -s string 61 | php fetchserver path(http/https) (default "https://a.bc.com/php-proxy/index.php") 62 | -sni string 63 | HTTPS sni extension ServerName(default fetchserver hostname) 64 | ``` 65 | 8. v1.0(不包括)之后的版本支持json格式的配置文件(php-proxy.json),当命令行有参数时,不使用配置文件,并会把命令行的数据写入json配置文件; 66 | 如果命令行没有参数,则从配置文件中读取配置信息,如果读取失败,则使用内部的默认参数 67 | ``` 68 | { 69 | "fetchserver": "https://a.bc.com/go/index.php", 70 | "password": "123456", 71 | "sni": "a.bc.com", 72 | "listen": "127.0.0.1:8081", 73 | "debug": false, 74 | "insecure": false 75 | } 76 | 77 | ``` 78 | 9. v1.1.2(包括)之后的版本支持自定义CA,只要把crt文件名字命名为php-proxy.crt,key文件命名为php-proxy.key,放到同一个目录下,程序会自动识别; 79 | 我这里自己生成的CA文件,为了安全,不建议大家使用,推荐大家使用自定义的CA,同时要注意自己的CA私钥不要随意泄露给别人;如果可执行文件目录下没有php-proxy.crt和 80 | php-proxy.key文件,则使用内部预留的CA(也就是我自己生成的CA),不推荐这样使用 81 | 10. v1.1.3(包括)之后的版本,可以对抗DNS污染(不能对抗IP封锁哈,IP封锁了就要套CDN了),或者指定DNS解析,比如你的域名helloworld.com被污染了,原先的配置 82 | (php-proxy.json)可以修改成这样,一定要指定sni,否则大部分情况下是不工作的(除了独立服务器,没有使用virtual host类似功能的) 83 | ``` 84 | #当然修改系统的hosts文件,也可以完成相似的功能,不过在不是管理员时可能没有权限 85 | "fetchserver": "https://域名解析正确的IP/go/index.php", 86 | "sni": "helloworld.com", 87 | ``` 88 | 另外隐藏的功能就是,假如你用了cloudflare的cdn,那么它给你域名分配的IP,一般有两个,这两个IP一般不是最优的,可以借助其他工具([better-cloudflare-ip](https://github.com/badafans/better-cloudflare-ip))查找其他的CDN ip,找到性能好的, 89 | 通过这种指定IP的模式,可以更好的使用CDN加速 90 | 另外提一下,如果IP没被封锁,但TLS SNI被盯上了,这个好办,换个域名就好了(好多地方可以免费申请域名) 91 | 92 | 11. v2.0.0版本,重写了数据处理过程,修复了下载问题,性能大幅提升,感谢[10362227](https://github.com/10362227)所做的对比与测试 93 | 12. v2.1.0版本,支持智能代理功能(采用内置的域名列表匹配模式),该功能默认未启用 94 | ``` 95 | { 96 | "fetchserver": "https://a.bc.com/go/index.php", 97 | "password": "123456", 98 | "sni": "a.bc.com", 99 | "listen": "127.0.0.1:8081", 100 | "debug": false, 101 | "insecure": false, 102 | "autoproxy": true 103 | } 104 | ``` 105 | 13. v2.1.2版本,支持自定义user-agent,当user-agent配置为空时,使用请求端的UA,否则使用自定义的UA 106 | ``` 107 | { 108 | "fetchserver": "https://a.bc.com/go/index.php", 109 | "password": "123456", 110 | "sni": "a.bc.com", 111 | "listen": "127.0.0.1:8081", 112 | "debug": false, 113 | "insecure": false, 114 | "autoproxy": true, 115 | "user-agent": "" 116 | } 117 | ``` 118 | 14. v2.1.3版本,支持前置代理,当proxy配置为空时,不使用前置代理;这种代理只在连接到php server时使用,在智能代理模式中,直接连接是不经过前置代理的 119 | 目前只支持http,https,socks5协议,配置格式参考如下: 120 | ``` 121 | //http 122 | http://127.0.0.1:80 123 | http://koala:123456@127.0.0.1:80 124 | //socks5 125 | socks5://user:password@127.0.0.1:1080 126 | socks5://127.0.0.1:1080 127 | //https 128 | https://127.0.0.1:80 129 | https://koala:123456@127.0.0.1:80 130 | ``` 131 | ``` 132 | { 133 | "fetchserver": "https://a.bc.com/go/index.php", 134 | "password": "123456", 135 | "sni": "a.bc.com", 136 | "listen": "127.0.0.1:8081", 137 | "debug": false, 138 | "insecure": false, 139 | "autoproxy": true, 140 | "user-agent": "", 141 | "proxy": "http://koala:free@127.0.0.1:80" 142 | } 143 | ``` 144 | ### 注意事项 145 | - 由于我自己生成的php-proxy.key/crt私钥和公钥的公开,如果导入到系统中,可能会导致一些钓鱼网站的恶意使用;在访问一些以Php-Proxy CA签发的https网站,本机浏览器 146 | 会直接信任这种网站,可能会造成隐私泄露;如果你用的chrome浏览器,建议php-proxy.crt证书不要导到入到系统中,在chrome快捷方式目标后面加上--ignore-certificate-errors 147 | 这样chrome也是可以用的,只是地址栏中会显示红色,这不影响使用;如果确实你需要导入CA到系统中,则在不使用时,建议从根证书系统中删除; 148 | 所以为了安全起见,建议自己动手生成CA;当然你觉得也没啥隐私可泄露的,这也无所谓了 149 | 150 | ### php免费空间推荐 151 | - [000webhost](https://www.000webhost.com/)(我最早用的这个,还不错) 152 | - [heroku](https://www.heroku.com/)(这个平台,是我目前在用的最多的) 153 | - [euroserver](https://euroserver.es/)(联通欧洲直连,CTZZG推荐,注册太麻烦,我没有测试) 154 | - [qoddi](https://app.qoddi.com/)(选择美西,CTZZG推荐,速度还行) 155 | 156 | ### TODO 157 | - 增加请求头添加的配置,也许可以用来放到国内外(免费)的php空间,做免流代理 158 | 159 | ### 感谢 160 | - GoAgent项目,让我学习了Python,php 161 | - [go-httpproxy/httpproxy](https://github.com/go-httpproxy/httpproxy)项目,SSL中间人拦截模式以及Ca签发是从这里学的 162 | -------------------------------------------------------------------------------- /client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "crypto/tls" 7 | "crypto/x509" 8 | "encoding/base64" 9 | "errors" 10 | "github.com/quic-go/quic-go" 11 | "github.com/quic-go/quic-go/http3" 12 | "io" 13 | "log" 14 | "net" 15 | "net/http" 16 | "net/url" 17 | "reflect" 18 | "time" 19 | ) 20 | 21 | type client struct { 22 | //global config 23 | cfg *config 24 | //http.Transport when connect server 25 | tr *http.Transport 26 | tr3 *http3.RoundTripper 27 | //http3 quic config 28 | qconf *quic.Config 29 | //tls.Config when connect https server 30 | tlsconfig *tls.Config 31 | //http.Client used to connect server 32 | client *http.Client 33 | //ca root cert info for middle attack check 34 | cert *x509.Certificate 35 | //server 36 | server *url.URL 37 | //proxy 38 | urlproxy *url.URL 39 | } 40 | 41 | func (cli *client) Post(url, contentType string, body io.Reader) (resp *http.Response, err error) { 42 | req, err := http.NewRequest(http.MethodPost, url, body) 43 | if err != nil { 44 | return nil, err 45 | } 46 | req.Header.Set("Content-Type", contentType) 47 | if cli.cfg.Sni != "" { 48 | if req.URL.Port() == "" { 49 | req.Host = cli.cfg.Sni 50 | } else { 51 | req.Host = cli.cfg.Sni + ":" + req.URL.Port() 52 | } 53 | } 54 | if cli.cfg.Debug == true { 55 | for k, v := range req.Header { 56 | log.Print(k + ": " + v[0]) 57 | } 58 | } 59 | return cli.client.Do(req) 60 | //return cli.client.Post(url, contentType, body) 61 | } 62 | 63 | func (cli *client) Dummy_Get(url string) (resp *http.Response, err error) { 64 | return cli.client.Get(url) 65 | } 66 | 67 | func (cli *client) Do(req *http.Request) (resp *http.Response, err error) { 68 | if req == nil { 69 | log.Printf("POST Request == nil") 70 | } else { 71 | req.URL = cli.server 72 | } 73 | req.Header.Set("Content-Type", "application/octet-stream") 74 | if cli.cfg.User_agent != "" { 75 | req.Header.Set("User-Agent", cli.cfg.User_agent) 76 | } 77 | if cli.cfg.Sni != "" { 78 | if req.URL.Port() == "" { 79 | req.Host = cli.cfg.Sni 80 | } else { 81 | req.Host = cli.cfg.Sni + ":" + req.URL.Port() 82 | } 83 | } 84 | if cli.cfg.Debug == true { 85 | for k, v := range req.Header { 86 | for _, value := range v { 87 | log.Print(k + ": " + value) 88 | } 89 | } 90 | } 91 | return cli.client.Do(req) 92 | } 93 | 94 | func (cli *client) init_client() { 95 | // 96 | server, err := url.Parse(cli.cfg.Fetchserver) 97 | if err != nil { 98 | log.Fatal(err) 99 | } 100 | cli.server = server 101 | // 102 | //tls config 103 | cli.tlsconfig = &tls.Config{ 104 | InsecureSkipVerify: cli.cfg.Insecure, 105 | VerifyConnection: cli.VerifyConnection, 106 | } 107 | if cli.cfg.Insecure == true { 108 | cli.tlsconfig.VerifyConnection = nil 109 | } 110 | if cli.cfg.Sni != "" { 111 | cli.tlsconfig.ServerName = cli.cfg.Sni 112 | } 113 | //parent proxy 114 | if cli.cfg.Proxy != "" { 115 | cli.urlproxy, err = url.Parse(cli.cfg.Proxy) 116 | if err != nil { 117 | log.Println(err) 118 | } 119 | } 120 | if cli.cfg.Http3 == false { 121 | //tr http.client default tr + tlsconfig 122 | cli.tr = &http.Transport{ 123 | //Dial: cli.Dial, 124 | DialContext: (&net.Dialer{ 125 | Timeout: 30 * time.Second, 126 | KeepAlive: 30 * time.Second, 127 | }).DialContext, 128 | ForceAttemptHTTP2: true, 129 | MaxIdleConns: 100, 130 | IdleConnTimeout: 90 * time.Second, 131 | TLSHandshakeTimeout: 10 * time.Second, 132 | ExpectContinueTimeout: 1 * time.Second, 133 | TLSClientConfig: cli.tlsconfig, 134 | WriteBufferSize: 4096 * 32, 135 | ReadBufferSize: 4096 * 32, 136 | } 137 | if cli.urlproxy != nil { 138 | if cli.urlproxy.Scheme == "https" { 139 | //for connect https proxy server 140 | cli.tr.DialTLS = cli.DialTLS 141 | } 142 | cli.tr.Proxy = http.ProxyURL(cli.urlproxy) 143 | } else { 144 | cli.tr.Proxy = http.ProxyFromEnvironment 145 | } 146 | } else { 147 | cli.qconf = &quic.Config{ 148 | MaxIdleTimeout: 90 * time.Second, 149 | HandshakeIdleTimeout: 10 * time.Second, 150 | KeepAlivePeriod: 30 * time.Second, 151 | InitialStreamReceiveWindow: 512 * 1024 * 10, 152 | InitialConnectionReceiveWindow: 512 * 1024 * 10, 153 | } 154 | cli.tr3 = &http3.RoundTripper{TLSClientConfig: cli.tlsconfig, QuicConfig: cli.qconf} 155 | } 156 | // 157 | 158 | cli.client = &http.Client{} 159 | if cli.cfg.Http3 == true { 160 | cli.client.Transport = cli.tr3 161 | } else { 162 | cli.client.Transport = cli.tr 163 | } 164 | //for cache tcp & dns(not must) 165 | //res, _ := cli.Dummy_Get(cli.cfg.Fetchserver) 166 | //if res != nil { 167 | // if res.Body != nil { 168 | // res.Body.Close() 169 | // } 170 | //} 171 | } 172 | 173 | func (cli *client) VerifyConnection(cs tls.ConnectionState) error { 174 | // 175 | cert := cs.PeerCertificates[0] 176 | if reflect.DeepEqual(cert, cli.cert) { 177 | return errors.New("This is a middle attack server using Php-Proxy CA") 178 | } else { 179 | cli.tlsconfig.VerifyConnection = nil 180 | return nil 181 | } 182 | } 183 | 184 | func (cli *client) DialTLS(network, addr string) (net.Conn, error) { 185 | tlsconfig := &tls.Config{ 186 | InsecureSkipVerify: cli.cfg.Insecure, 187 | } 188 | conn, err := tls.Dial(network, addr, tlsconfig) 189 | return conn, err 190 | } 191 | 192 | //for HTTPS Forward PROXY dialer for feature use(need test) 193 | func (cli *client) Dial(network, addr string) (c net.Conn, err error) { 194 | tlsconfig := &tls.Config{ 195 | InsecureSkipVerify: cli.cfg.Insecure, 196 | } 197 | var port string 198 | if cli.urlproxy.Port() == "" { 199 | if cli.urlproxy.Scheme == "http" { 200 | port = "80" 201 | } else if cli.urlproxy.Scheme == "https" { 202 | port = "443" 203 | } else { 204 | port = "80" 205 | } 206 | } 207 | conn, err := tls.Dial("tcp", cli.urlproxy.Hostname()+":"+port, tlsconfig) 208 | if err != nil { 209 | return conn, errors.New("HTTPS Proxy:" + err.Error()) 210 | } 211 | req := &http.Request{ 212 | Method: http.MethodConnect, 213 | Header: http.Header{}, 214 | Host: addr, 215 | URL: &url.URL{Path: addr}, 216 | ContentLength: 0, 217 | Body: nil, 218 | } 219 | req.Header.Set("Host", addr) 220 | req.Header.Set("Proxy-Connection", "keep-alive") 221 | if cli.urlproxy.User != nil { 222 | p := base64.StdEncoding.EncodeToString([]byte(cli.urlproxy.User.String())) 223 | log.Print(p) 224 | req.Header.Set("Proxy-Authorization", "Basic "+p) 225 | } 226 | // 227 | err_wr := req.Write(conn) 228 | if err_wr != nil { 229 | conn.Close() 230 | return conn, errors.New("HTTPS Proxy:" + err_wr.Error()) 231 | } 232 | var b [1024]byte 233 | n, err := conn.Read(b[:]) 234 | if err != nil { 235 | conn.Close() 236 | return conn, errors.New("HTTPS Proxy:" + err.Error()) 237 | } 238 | Res, err_rd := http.ReadResponse(bufio.NewReader(bytes.NewReader(b[:n])), req) 239 | if err_rd != nil { 240 | conn.Close() 241 | return conn, errors.New("HTTPS Proxy:" + err_rd.Error()) 242 | } 243 | if Res.StatusCode != http.StatusOK { 244 | conn.Close() 245 | return conn, errors.New("HTTPS Proxy:" + "Connect status error") 246 | } 247 | return conn, nil 248 | 249 | } 250 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "flag" 6 | "io/ioutil" 7 | "log" 8 | "os" 9 | "runtime" 10 | ) 11 | 12 | //CaCert/CA.crt should be trusted by local OS 13 | //Php-Proxy CA 14 | var CaCert = []byte(`-----BEGIN CERTIFICATE----- 15 | MIIDvTCCAqWgAwIBAgIJAJ6lzaYHcaNcMA0GCSqGSIb3DQEBCwUAMHUxCzAJBgNV 16 | BAYTAkNOMREwDwYDVQQIDAhJbnRlcm5ldDEPMA0GA1UEBwwGQ2VybmV0MRIwEAYD 17 | VQQKDAlQaHAtUHJveHkxFzAVBgNVBAsMDlBocC1Qcm94eSBSb290MRUwEwYDVQQD 18 | DAxQaHAtUHJveHkgQ0EwHhcNMjEwNzE2MDEyNDU2WhcNMzEwNzE0MDEyNDU2WjB1 19 | MQswCQYDVQQGEwJDTjERMA8GA1UECAwISW50ZXJuZXQxDzANBgNVBAcMBkNlcm5l 20 | dDESMBAGA1UECgwJUGhwLVByb3h5MRcwFQYDVQQLDA5QaHAtUHJveHkgUm9vdDEV 21 | MBMGA1UEAwwMUGhwLVByb3h5IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB 22 | CgKCAQEAyoA89JBn6tpag1JFNO3kGWaq1wUPIB0Kil00SOW/IXB1riLMo/l3Utc6 23 | k6BDHRugeyq34NQDEF4AVt3Gb7gxCh/zbFnPaDT9T5i9QGtIs4hp+L+/LofC11WQ 24 | V9xf5G9v2c75JYbjMhp41wfQH2j/zHvjA7LWNE/DXHrU3TOBVhqE8WYXEe1uORag 25 | 13sVWUiTGGu3UCzEZs5H7tZ2mPgSddXrreJ7YtYy8DheA4FsYhD1AK/xj2MrpErL 26 | iy/F86LgimBuAQ01AHccPBrtyY928JBBaPCp++FCmoqf+hpAvN1YiAgny0aPIjsa 27 | VPXs+eEpiqI4RTMuYSfek/l8JTcxNwIDAQABo1AwTjAdBgNVHQ4EFgQUctnJSBh5 28 | IW+81UYIirzu6o/AOl0wHwYDVR0jBBgwFoAUctnJSBh5IW+81UYIirzu6o/AOl0w 29 | DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEACHU/rXn2ERHRSXq8V64l 30 | /97ozE1Sbv54ehWnMAY2prSdXnMQXftFPd7FXz8NwkfqjwsdEjV2o5lpZ/J9seDn 31 | SbTHqiBlo5M7HmN2K+WCMfRhv9hNI2+6IeUfwxhkHrsRTsq7og/UnSODF68Jy2g7 32 | HZmAQFc6dy//GQR4zM8afDhlDSGH23Pgl2lwagQTNtzl2PrCiRh8J9F7cOfMqL0A 33 | Ee2VElNdCS8MR9OGPw/MSo6lWX7g4aWxYa7oajmvT6bgfU9+2rQ/tjldfWyyoCMw 34 | ap/s6xLfzLWwZ+NVShcWiC4l9Dwfkig1z/CWISuvROAMAI58j3BNG8xqcf4iJiuo 35 | gA== 36 | -----END CERTIFICATE-----`) 37 | 38 | var CaKey = []byte(`-----BEGIN PRIVATE KEY----- 39 | MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDKgDz0kGfq2lqD 40 | UkU07eQZZqrXBQ8gHQqKXTRI5b8hcHWuIsyj+XdS1zqToEMdG6B7Krfg1AMQXgBW 41 | 3cZvuDEKH/NsWc9oNP1PmL1Aa0iziGn4v78uh8LXVZBX3F/kb2/ZzvklhuMyGnjX 42 | B9AfaP/Me+MDstY0T8NcetTdM4FWGoTxZhcR7W45FqDXexVZSJMYa7dQLMRmzkfu 43 | 1naY+BJ11eut4nti1jLwOF4DgWxiEPUAr/GPYyukSsuLL8XzouCKYG4BDTUAdxw8 44 | Gu3Jj3bwkEFo8Kn74UKaip/6GkC83ViICCfLRo8iOxpU9ez54SmKojhFMy5hJ96T 45 | +XwlNzE3AgMBAAECggEAfTX7+tDLoJjxPKADMO4ji11DJ372UkoCuXlWGfkNTJTn 46 | /wt/c6iOEogIrT18IiRx/5Zzai5N0rH9DblFuNCwae1Fq+qAZ5PUSYJNCucLZg9k 47 | Ty3o/dFuNY2vmdQm6u3IwGnM/lpAYzuhGny3QKTA/mRgA2pyLphfWPCObFQrldvo 48 | D8/HkPIrWP7eeRhDFBuYH2Y8evBW+JJ0xKWWyxnwpYnOvfQP/bb38M9weSmB6oC+ 49 | XHnWruCldNLrGwVZsgiuvoh/zIXOQlXRz7U9dT/VJZQGGPdiC49rSN8Q5/qKkPST 50 | 1sc2ujmbJpHRtjKtCdBLD/yHNVjbF1cVk2AmPkyGqQKBgQDu+r+7sCruZ+q0ixEm 51 | v7YoMIPouZuuv9wePQL5kwmLqmhZq0vyObcSCRfg5P9oONDB53WNmDjvPEEImQbU 52 | EPmvGofbGVaaTYnbAXmZA50IZElrsPfwZdvRBgMB6gVuPPuHmfStWo+bOEsTml0u 53 | wsa7obEb5giDzjzP22tt2mil/QKBgQDY7GKTP5WUqdgp+1gig5IMu4EpoidrmdWr 54 | U7hKB/R6p+ihrCX1xu/TdZAb7bGFya1O60LsnnQ3iF/heNTWOBUYgDGia6eaEpc1 55 | /K5zis055WoEu5hAebqgr+0VJUEiqGuBUnpqyHLXr8LHf3g7cSU5/4KbCu+1paXu 56 | 2/9MMY7AQwKBgFlIu3t+3PtHPcwILPdCJucrAQ1g0wZdzfpKJyNhSO6yUtw1gGFW 57 | KMyHMzGlvLqOh4f6VtP47ESNSWrR6Vgvo2lFSz6TX+S0VW3KRkjhrbil5zxh2LAr 58 | Dg4w5czARxkhlYPbBCwEKqT+SiZfxLKkuKT/SvE2ZzX/Rn8N5jwbnn9tAoGAcVeZ 59 | 7fxEKOhRxSXKGEaM0lBKnblXRZacmSdmXHAposkG+Sqcrv3iI6gCw0UAA7qr7ldo 60 | oX/tk3KTPplHBCNLioC47ne3m/5oudGsSTzWHJEtQwnN9KpmBD3H78uGbBh6C5lP 61 | 02mm7+GrMVf+N3jYDaTe1inxtAS4XcTfcS1XvEcCgYEAiohDWwiDO/GQloKPuZWc 62 | gVEJoAty/LbU/TyW+i3bM94rcJLKY8ySPBmTQb+ifeqvSRo4W2zv3tQ5lBag77y3 63 | pRYFQzk5UG6yo4V0/oo2UUSDY0UoxX9lVNcJvYVwPcNwKHnX9a9fRrlf3o+c5rrE 64 | jIxm1tgZheqRxqpv1LwQ4hQ= 65 | -----END PRIVATE KEY-----`) 66 | 67 | // 68 | const version string = "2.1.5" 69 | 70 | // 71 | 72 | type config struct { 73 | //php fetchserver path 74 | Fetchserver string `json:"fetchserver"` 75 | //password 76 | Password string `json:"password"` 77 | //when connect https php server,TLS sni extension 78 | Sni string `json:"sni"` 79 | //local listen address 80 | Listen string `json:"listen"` 81 | //enable http3 82 | Http3 bool `json:"http3"` 83 | //debug enable 84 | Debug bool `json:"debug"` 85 | //insecure connect to php server 86 | Insecure bool `json:"insecure"` 87 | //auto proxy 88 | Autoproxy bool `json:"autoproxy"` 89 | //user agent 90 | User_agent string `json:"user-agent"` 91 | //parent proxy 92 | Proxy string `json:"proxy"` 93 | //ca 94 | Ca string `json:"ca"` 95 | //key 96 | Key string `json:"key"` 97 | } 98 | 99 | func (c *config) init_config() { 100 | // 101 | confpath := "" 102 | // 103 | log.Printf("Php-Proxy version:v%s\n", version) 104 | // 105 | log.Printf("Go version:%s\n", runtime.Version()) 106 | // 107 | flag.CommandLine.SetOutput(os.Stdout) 108 | // 109 | flag.StringVar(&confpath, "c", "", "config file path") 110 | flag.StringVar(&c.Listen, "l", "127.0.0.1:8081", "Local listen address(HTTP Proxy address)") 111 | flag.StringVar(&c.Password, "p", "123456", "php server password") 112 | flag.StringVar(&c.Sni, "sni", "", "HTTPS sni extension ServerName(default fetchserver hostname)") 113 | flag.StringVar(&c.Fetchserver, "s", "https://a.bc.com/php-proxy/index.php", "php fetchserver path(http/https)") 114 | flag.StringVar(&c.User_agent, "ua", "", "customize User-Agent to php server(default use brower User-Agent)") 115 | flag.StringVar(&c.Proxy, "fp", "", "connect php server via Forward Proxy(https://user:password@domain.com,http://user:password@127.0.0.1:8080,socks5://user:password@127.0.0.1:1080)") 116 | flag.StringVar(&c.Ca, "ca", "", "ca file path") 117 | flag.StringVar(&c.Key, "key", "", "key file path") 118 | flag.BoolVar(&c.Debug, "d", false, "enable debug mode for debug") 119 | flag.BoolVar(&c.Http3, "h3", false, "enable http3 client mode") 120 | flag.BoolVar(&c.Autoproxy, "a", false, "enable auto proxy") 121 | flag.BoolVar(&c.Insecure, "k", false, "insecure connect to php server(ignore certs verify/middle attack)") 122 | flag.Parse() 123 | // 124 | //c.writeconfig() 125 | if len(os.Args) < 2 || confpath != "" { 126 | c.loadconfig(confpath) 127 | } else { 128 | c.writeconfig() 129 | } 130 | // 131 | if c.Autoproxy { 132 | log.Printf("Autoproxy enabled") 133 | } else { 134 | log.Printf("Autoproxy not enabled") 135 | } 136 | if c.Http3 { 137 | log.Printf("Http3 enabled") 138 | } else { 139 | log.Printf("Http3 not enabled") 140 | } 141 | // 142 | log.Printf("php Fetch server:%s\n", c.Fetchserver) 143 | // 144 | if c.Proxy == "" { 145 | log.Printf("Forward Proxy not enabled") 146 | } else { 147 | log.Printf("Forward Proxy enabled:" + c.Proxy) 148 | } 149 | } 150 | 151 | func (c *config) loadconfig(confpath string) { 152 | dir, err := os.Getwd() 153 | if err != nil { 154 | log.Fatal(err) 155 | } 156 | fpath := "" 157 | if confpath != "" { 158 | fpath = confpath 159 | } else { 160 | fpath = dir + "/php-proxy.json" 161 | } 162 | raw, err1 := ioutil.ReadFile(fpath) 163 | if err1 != nil { 164 | //log.Print(err1) 165 | return 166 | } 167 | log.Print("Load config from " + fpath) 168 | err = json.Unmarshal(raw, c) 169 | if err != nil { 170 | log.Print(err) 171 | } 172 | } 173 | func (c *config) writeconfig() { 174 | dir, err := os.Getwd() 175 | if err != nil { 176 | log.Fatal(err) 177 | } 178 | raw, err1 := json.MarshalIndent(c, "", "") 179 | //raw, err1 := json.Marshal(c) 180 | //log.Print(string(raw)) 181 | if err1 != nil { 182 | log.Print(err1) 183 | return 184 | } 185 | err = ioutil.WriteFile(dir+"/php-proxy.json", raw, 0644) 186 | if err != nil { 187 | log.Print(err) 188 | return 189 | } 190 | log.Print("Write config to " + dir + "/php-proxy.json") 191 | } 192 | -------------------------------------------------------------------------------- /server/index_v3_2_6.php: -------------------------------------------------------------------------------- 1 | 16 | 17 | ${title} 18 | 28 | 29 | 30 | 31 | 32 | 33 |
Error
 
34 |
35 |

${banner}

36 | ${detail} 37 | 38 |

39 |

40 |
41 | 42 | MESSAGE_STRING; 43 | return $error; 44 | } 45 | 46 | 47 | function decode_request($data) { 48 | list($headers_length) = array_values(unpack('n', substr($data, 0, 2))); 49 | $headers_data = gzinflate(substr($data, 2, $headers_length)); 50 | $body = substr($data, 2+intval($headers_length)); 51 | 52 | $lines = explode("\r\n", $headers_data); 53 | 54 | $request_line_items = explode(" ", array_shift($lines)); 55 | $method = $request_line_items[0]; 56 | $url = $request_line_items[1]; 57 | 58 | $headers = array(); 59 | $kwargs = array(); 60 | $kwargs_prefix = 'X-URLFETCH-'; 61 | 62 | foreach ($lines as $line) { 63 | if (!$line) 64 | continue; 65 | $pair = explode(':', $line, 2); 66 | $key = $pair[0]; 67 | $value = trim($pair[1]); 68 | if (stripos($key, $kwargs_prefix) === 0) { 69 | $kwargs[strtolower(substr($key, strlen($kwargs_prefix)))] = $value; 70 | } else if ($key) { 71 | $key = join('-', array_map('ucfirst', explode('-', $key))); 72 | $headers[$key] = $value; 73 | } 74 | } 75 | if (isset($headers['Content-Encoding'])) { 76 | if ($headers['Content-Encoding'] == 'deflate') { 77 | $body = gzinflate($body); 78 | $headers['Content-Length'] = strval(strlen($body)); 79 | unset($headers['Content-Encoding']); 80 | } 81 | } 82 | return array($method, $url, $headers, $kwargs, $body); 83 | } 84 | 85 | 86 | function echo_content($content) { 87 | global $__password__, $__content_type__; 88 | if ($__content_type__ == 'image/gif') { 89 | echo $content ^ str_repeat($__password__[0], strlen($content)); 90 | } else { 91 | echo $content; 92 | } 93 | } 94 | 95 | 96 | function curl_header_function($ch, $header) { 97 | global $__content__, $__content_type__; 98 | $pos = strpos($header, ':'); 99 | if ($pos == false) { 100 | $__content__ .= $header; 101 | } else { 102 | $key = join('-', array_map('ucfirst', explode('-', substr($header, 0, $pos)))); 103 | if ($key != 'Transfer-Encoding') { 104 | $__content__ .= $key . substr($header, $pos); 105 | } 106 | } 107 | if (preg_match('@^Content-Type: ?(audio/|image/|video/|application/octet-stream)@i', $header)) { 108 | $__content_type__ = 'image/x-png'; 109 | } 110 | if (!trim($header)) { 111 | header('Content-Type: ' . $__content_type__); 112 | } 113 | return strlen($header); 114 | } 115 | 116 | 117 | function curl_write_function($ch, $content) { 118 | global $__content__; 119 | if ($__content__) { 120 | // for debug 121 | // echo_content("HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n"); 122 | echo_content($__content__); 123 | $__content__ = ''; 124 | } 125 | echo_content($content); 126 | return strlen($content); 127 | } 128 | 129 | 130 | function post() { 131 | global $__content_type__; 132 | list($method, $url, $headers, $kwargs, $body) = @decode_request(@file_get_contents('php://input')); 133 | 134 | $password = $GLOBALS['__password__']; 135 | if ($password) { 136 | if (!isset($kwargs['password']) || $password != $kwargs['password']) { 137 | header("HTTP/1.0 403 Forbidden"); 138 | echo message_html('403 Forbidden', 'Wrong Password', "please confirm your password."); 139 | exit(-1); 140 | } 141 | } 142 | 143 | $hostsdeny = $GLOBALS['__hostsdeny__']; 144 | if ($hostsdeny) { 145 | $urlparts = parse_url($url); 146 | $host = $urlparts['host']; 147 | foreach ($hostsdeny as $pattern) { 148 | if (substr($host, strlen($host)-strlen($pattern)) == $pattern) { 149 | header('Content-Type: ' . $__content_type__); 150 | echo_content("HTTP/1.0 403\r\n\r\n" . message_html('403 Forbidden', "hostsdeny matched($host)", $url)); 151 | exit(-1); 152 | } 153 | } 154 | } 155 | 156 | if ($body) { 157 | $headers['Content-Length'] = strval(strlen($body)); 158 | } 159 | if (isset($headers['Connection'])) { 160 | $headers['Connection'] = 'close'; 161 | } 162 | 163 | $header_array = array(); 164 | foreach ($headers as $key => $value) { 165 | $header_array[] = join('-', array_map('ucfirst', explode('-', $key))).': '.$value; 166 | } 167 | 168 | $timeout = $GLOBALS['__timeout__']; 169 | 170 | $curl_opt = array(); 171 | 172 | switch (strtoupper($method)) { 173 | case 'HEAD': 174 | $curl_opt[CURLOPT_NOBODY] = true; 175 | break; 176 | case 'GET': 177 | break; 178 | case 'POST': 179 | $curl_opt[CURLOPT_POST] = true; 180 | $curl_opt[CURLOPT_POSTFIELDS] = $body; 181 | break; 182 | case 'PUT': 183 | case 'DELETE': 184 | case 'OPTIONS': 185 | case 'PATCH': 186 | $curl_opt[CURLOPT_CUSTOMREQUEST] = $method; 187 | $curl_opt[CURLOPT_POSTFIELDS] = $body; 188 | break; 189 | default: 190 | header('Content-Type: ' . $__content_type__); 191 | echo_content("HTTP/1.0 502\r\n\r\n" . message_html('502 Urlfetch Error', 'Invalid Method: ' . $method, $url)); 192 | exit(-1); 193 | } 194 | 195 | $curl_opt[CURLOPT_HTTPHEADER] = $header_array; 196 | $curl_opt[CURLOPT_RETURNTRANSFER] = true; 197 | $curl_opt[CURLOPT_BINARYTRANSFER] = true; 198 | 199 | $curl_opt[CURLOPT_HEADER] = false; 200 | $curl_opt[CURLOPT_HEADERFUNCTION] = 'curl_header_function'; 201 | $curl_opt[CURLOPT_WRITEFUNCTION] = 'curl_write_function'; 202 | 203 | $curl_opt[CURLOPT_FAILONERROR] = false; 204 | $curl_opt[CURLOPT_FOLLOWLOCATION] = false; 205 | 206 | $curl_opt[CURLOPT_CONNECTTIMEOUT] = $timeout; 207 | $curl_opt[CURLOPT_TIMEOUT] = $timeout; 208 | 209 | $curl_opt[CURLOPT_SSL_VERIFYPEER] = false; 210 | $curl_opt[CURLOPT_SSL_VERIFYHOST] = false; 211 | 212 | $ch = curl_init($url); 213 | curl_setopt_array($ch, $curl_opt); 214 | $ret = curl_exec($ch); 215 | $errno = curl_errno($ch); 216 | if ($GLOBALS['__content__']) { 217 | echo_content($GLOBALS['__content__']); 218 | } else if ($errno) { 219 | $content = "HTTP/1.0 502\r\n\r\n" . message_html('502 Urlfetch Error', "PHP Urlfetch Error curl($errno)", curl_error($ch)); 220 | if (!headers_sent()) { 221 | header('Content-Type: ' . $__content_type__); 222 | } else if($errno==CURLE_OPERATION_TIMEOUTED) { 223 | $content = ""; 224 | } 225 | echo_content($content); 226 | } 227 | curl_close($ch); 228 | } 229 | 230 | function get() { 231 | $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']; 232 | $domain = preg_replace('/.*\\.(.+\\..+)$/', '$1', $host); 233 | if ($host && $host != $domain && $host != 'www'.$domain) { 234 | header('Location: http://www.' . $domain); 235 | } else { 236 | header('Location: https://www.google.com'); 237 | } 238 | } 239 | 240 | 241 | function main() { 242 | if ($_SERVER['REQUEST_METHOD'] == 'POST') { 243 | post(); 244 | } else { 245 | get(); 246 | } 247 | } 248 | 249 | main(); 250 | -------------------------------------------------------------------------------- /server/index.php: -------------------------------------------------------------------------------- 1 | 17 | 18 | ${title} 19 | 29 | 30 | 31 | 32 | 33 | 34 |
Error
 
35 |
36 |

${banner}

37 | ${detail} 38 | 39 |

40 |

41 |
42 | 43 | MESSAGE_STRING; 44 | return $error; 45 | } 46 | 47 | 48 | function decode_request($data) { 49 | list($headers_length) = array_values(unpack('n', substr($data, 0, 2))); 50 | $headers_data = gzinflate(substr($data, 2, $headers_length)); 51 | $body = substr($data, 2+intval($headers_length)); 52 | 53 | $lines = explode("\r\n", $headers_data); 54 | 55 | $request_line_items = explode(" ", array_shift($lines)); 56 | $method = $request_line_items[0]; 57 | $url = $request_line_items[1]; 58 | 59 | $headers = array(); 60 | $kwargs = array(); 61 | $kwargs_prefix = 'X-URLFETCH-'; 62 | 63 | foreach ($lines as $line) { 64 | if (!$line) 65 | continue; 66 | $pair = explode(':', $line, 2); 67 | $key = $pair[0]; 68 | $value = trim($pair[1]); 69 | if (stripos($key, $kwargs_prefix) === 0) { 70 | $kwargs[strtolower(substr($key, strlen($kwargs_prefix)))] = $value; 71 | } else if ($key) { 72 | $key = join('-', array_map('ucfirst', explode('-', $key))); 73 | $headers[$key] = $value; 74 | } 75 | } 76 | if (isset($headers['Content-Encoding'])) { 77 | if ($headers['Content-Encoding'] == 'deflate') { 78 | $body = gzinflate($body); 79 | $headers['Content-Length'] = strval(strlen($body)); 80 | unset($headers['Content-Encoding']); 81 | } 82 | } 83 | return array($method, $url, $headers, $kwargs, $body); 84 | } 85 | 86 | 87 | function echo_content($content) { 88 | global $__password__, $__content_type__,$__chunked__,$__content__; 89 | $chunk=""; 90 | if($__chunked__==1) { 91 | if(empty($__content__)) { 92 | $chunk=sprintf("%x\r\n%s\r\n", strlen($content), $content); 93 | } else { 94 | $chunk=$content; 95 | } 96 | } else { 97 | $chunk=$content; 98 | } 99 | // 100 | if ($__content_type__ == 'image/gif') { 101 | $chunk = $chunk ^ str_repeat($__password__[0], strlen($chunk)); 102 | } else { 103 | $chunk = $chunk; 104 | } 105 | echo $chunk; 106 | } 107 | 108 | 109 | function curl_header_function($ch, $header) { 110 | global $__content__, $__content_type__,$__chunked__; 111 | $pos = strpos($header, ':'); 112 | if ($pos == false) { 113 | $__content__ .= $header; 114 | } else { 115 | $key = join('-', array_map('ucfirst', explode('-', substr($header, 0, $pos)))); 116 | //if ($key != 'Transfer-Encoding') { 117 | $__content__ .= $key . substr($header, $pos); 118 | //} 119 | } 120 | if (preg_match('@^Content-Type: ?(audio/|image/|video/|application/octet-stream)@i', $header)) { 121 | $__content_type__ = 'image/x-png'; 122 | } 123 | if (!trim($header)) { 124 | header('Content-Type: ' . $__content_type__); 125 | } 126 | if (preg_match('@^Transfer-Encoding: ?(chunked)@i', $header)) { 127 | $__chunked__ = 1; 128 | } 129 | return strlen($header); 130 | } 131 | 132 | 133 | function curl_write_function($ch, $content) { 134 | global $__content__,$__chunked__,$__trailer__; 135 | if ($__content__) { 136 | // for debug 137 | // echo_content("HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n"); 138 | echo_content($__content__); 139 | $__content__ = ''; 140 | $__trailer__ = $__chunked__; 141 | } 142 | echo_content($content); 143 | return strlen($content); 144 | } 145 | 146 | 147 | function post() { 148 | global $__content_type__; 149 | list($method, $url, $headers, $kwargs, $body) = @decode_request(@file_get_contents('php://input')); 150 | 151 | $password = $GLOBALS['__password__']; 152 | if ($password) { 153 | if (!isset($kwargs['password']) || $password != $kwargs['password']) { 154 | header("HTTP/1.0 403 Forbidden"); 155 | echo message_html('403 Forbidden', 'Wrong Password', "please confirm your password."); 156 | exit(-1); 157 | } 158 | } 159 | 160 | $hostsdeny = $GLOBALS['__hostsdeny__']; 161 | if ($hostsdeny) { 162 | $urlparts = parse_url($url); 163 | $host = $urlparts['host']; 164 | foreach ($hostsdeny as $pattern) { 165 | if (substr($host, strlen($host)-strlen($pattern)) == $pattern) { 166 | header('Content-Type: ' . $__content_type__); 167 | echo_content("HTTP/1.0 403\r\n\r\n" . message_html('403 Forbidden', "hostsdeny matched($host)", $url)); 168 | exit(-1); 169 | } 170 | } 171 | } 172 | 173 | if ($body) { 174 | $headers['Content-Length'] = strval(strlen($body)); 175 | } 176 | //if (isset($headers['Connection'])) { 177 | // $headers['Connection'] = 'close'; 178 | //} 179 | 180 | $header_array = array(); 181 | foreach ($headers as $key => $value) { 182 | $header_array[] = join('-', array_map('ucfirst', explode('-', $key))).': '.$value; 183 | } 184 | 185 | $timeout = $GLOBALS['__timeout__']; 186 | 187 | $curl_opt = array(); 188 | 189 | switch (strtoupper($method)) { 190 | case 'HEAD': 191 | $curl_opt[CURLOPT_NOBODY] = true; 192 | break; 193 | case 'GET': 194 | break; 195 | case 'POST': 196 | $curl_opt[CURLOPT_POST] = true; 197 | $curl_opt[CURLOPT_POSTFIELDS] = $body; 198 | break; 199 | case 'PUT': 200 | case 'DELETE': 201 | case 'OPTIONS': 202 | case 'PATCH': 203 | $curl_opt[CURLOPT_CUSTOMREQUEST] = $method; 204 | $curl_opt[CURLOPT_POSTFIELDS] = $body; 205 | break; 206 | default: 207 | header('Content-Type: ' . $__content_type__); 208 | echo_content("HTTP/1.0 502\r\n\r\n" . message_html('502 Urlfetch Error', 'Invalid Method: ' . $method, $url)); 209 | exit(-1); 210 | } 211 | 212 | $curl_opt[CURLOPT_HTTPHEADER] = $header_array; 213 | $curl_opt[CURLOPT_RETURNTRANSFER] = true; 214 | $curl_opt[CURLOPT_BINARYTRANSFER] = true; 215 | 216 | $curl_opt[CURLOPT_HEADER] = false; 217 | $curl_opt[CURLOPT_HEADERFUNCTION] = 'curl_header_function'; 218 | $curl_opt[CURLOPT_WRITEFUNCTION] = 'curl_write_function'; 219 | 220 | $curl_opt[CURLOPT_FAILONERROR] = false; 221 | $curl_opt[CURLOPT_FOLLOWLOCATION] = false; 222 | 223 | $curl_opt[CURLOPT_CONNECTTIMEOUT] = $timeout; 224 | $curl_opt[CURLOPT_TIMEOUT] = $timeout; 225 | 226 | $curl_opt[CURLOPT_SSL_VERIFYPEER] = false; 227 | $curl_opt[CURLOPT_SSL_VERIFYHOST] = false; 228 | 229 | $ch = curl_init($url); 230 | curl_setopt_array($ch, $curl_opt); 231 | $ret = curl_exec($ch); 232 | $errno = curl_errno($ch); 233 | if ($GLOBALS['__content__'] && $GLOBALS['__trailer__']==0 ) { 234 | echo_content($GLOBALS['__content__']); 235 | } else if ($errno) { 236 | $content = "HTTP/1.0 502\r\n\r\n" . message_html('502 Urlfetch Error', "PHP Urlfetch Error curl($errno)", curl_error($ch)); 237 | if (!headers_sent()) { 238 | header('Content-Type: ' . $__content_type__); 239 | echo_content($content); 240 | } else if($errno==CURLE_OPERATION_TIMEOUTED) { 241 | if($GLOBALS['__chunked__']==1) { 242 | $content = "-1\r\n\r\n";//fake chunked end flag 243 | $GLOBALS['__chunked__']=0; 244 | $GLOBALS['__trailer__']=0; 245 | } else { 246 | $content = ""; 247 | } 248 | echo_content($content); 249 | } 250 | } 251 | //when chunked there may be trailer 252 | if ($GLOBALS['__trailer__']==1 && $GLOBALS['__content__']){ 253 | $GLOBALS['__chunked__']=0; 254 | echo_content("0\r\n".$GLOBALS['__content__']."\r\n"); 255 | } 256 | //normal chunked end 257 | if ($GLOBALS['__chunked__']==1){ 258 | echo_content(""); 259 | } 260 | curl_close($ch); 261 | } 262 | 263 | function get() { 264 | $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']; 265 | $domain = preg_replace('/.*\\.(.+\\..+)$/', '$1', $host); 266 | if ($host && $host != $domain && $host != 'www'.$domain) { 267 | header('Location: http://www.' . $domain); 268 | } else { 269 | header('Location: https://www.google.com'); 270 | } 271 | } 272 | 273 | 274 | function main() { 275 | if ($_SERVER['REQUEST_METHOD'] == 'POST') { 276 | post(); 277 | } else { 278 | get(); 279 | } 280 | } 281 | 282 | main(); 283 | -------------------------------------------------------------------------------- /proxy.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | //"context" 6 | "crypto/tls" 7 | "crypto/x509" 8 | //"fmt" 9 | "io" 10 | "io/ioutil" 11 | "log" 12 | "net" 13 | "net/http" 14 | "os" 15 | "strings" 16 | "sync" 17 | "time" 18 | ) 19 | 20 | var mux sync.Mutex 21 | 22 | const num_connection int = 5 23 | 24 | var conn_index int = 0 25 | 26 | type proxy struct { 27 | //global config 28 | cfg *config 29 | //prepare static buf 30 | bufpool sync.Pool 31 | //php client 32 | client [num_connection]*client 33 | //ca sign ssl cert for middle intercept 34 | signer *CaSigner 35 | //ca root cert info for middle attack check 36 | cert *x509.Certificate 37 | } 38 | 39 | func (prx *proxy) load_ca() []byte { 40 | dir, err := os.Getwd() 41 | if err != nil { 42 | log.Fatal(err) 43 | } 44 | ca_path := "" 45 | if prx.cfg.Ca == "" { 46 | ca_path = dir + "/php-proxy.crt" 47 | } else { 48 | ca_path = prx.cfg.Ca 49 | } 50 | raw, err1 := ioutil.ReadFile(ca_path) 51 | if err1 != nil { 52 | return nil 53 | } 54 | log.Print("Load ca cert from " + ca_path + " file") 55 | return raw 56 | } 57 | 58 | func (prx *proxy) load_key() []byte { 59 | dir, err := os.Getwd() 60 | if err != nil { 61 | log.Fatal(err) 62 | } 63 | key_path := "" 64 | if prx.cfg.Key == "" { 65 | key_path = dir + "/php-proxy.key" 66 | } else { 67 | key_path = prx.cfg.Key 68 | } 69 | raw, err1 := ioutil.ReadFile(key_path) 70 | if err1 != nil { 71 | return nil 72 | } 73 | log.Print("Load ca key from " + key_path + " file") 74 | return raw 75 | } 76 | 77 | func (prx *proxy) init_ca() { 78 | // 79 | var use_ca, use_key []byte 80 | prx.signer = NewCaSignerCache(1024) 81 | cert := prx.load_ca() 82 | key := prx.load_key() 83 | if cert != nil && key != nil { 84 | use_ca = cert 85 | use_key = key 86 | log.Print("Using external customize CA file") 87 | 88 | } else { 89 | use_ca = CaCert 90 | use_key = CaKey 91 | log.Print("Using internal Php-Proxy CA file") 92 | } 93 | ca, err := tls.X509KeyPair(use_ca, use_key) 94 | if err != nil { 95 | log.Fatal(err) 96 | } else { 97 | prx.signer.Ca = &ca 98 | } 99 | //parse our own php-proxy ca to get info 100 | prx.cert, err = x509.ParseCertificate(ca.Certificate[0]) 101 | if err != nil { 102 | log.Fatal(err) 103 | } 104 | //prepare gen google cert for cache(not must) 105 | _ = prx.signer.SignHost("www.google.com") 106 | _ = prx.signer.SignHost("www.youtube.com") 107 | _ = prx.signer.SignHost("www.googlevideo.com") 108 | _ = prx.signer.SignHost("www.gstatic.com") 109 | _ = prx.signer.SignHost("www.ggpht.com") 110 | } 111 | 112 | func (prx *proxy) init_proxy() { 113 | // 114 | prx.init_ca() 115 | // 116 | 117 | log.Println("HTTP Proxy Listening on " + prx.cfg.Listen) 118 | 119 | //connect php server config 120 | for i := 0; i < num_connection; i++ { 121 | prx.client[i] = &client{cfg: prx.cfg} 122 | prx.client[i].cert = prx.cert 123 | prx.client[i].init_client() 124 | } 125 | // 126 | prx.bufpool = sync.Pool{ 127 | New: func() interface{} { 128 | return make([]byte, 32*1024) 129 | }, 130 | } 131 | // 132 | log.Fatal(http.ListenAndServe(prx.cfg.Listen, prx)) 133 | // 134 | 135 | } 136 | 137 | func (prx *proxy) IOCopy(dst io.Writer, src io.Reader) (written int64, err error) { 138 | //not use tmp mem,use prepared mem 139 | buf := prx.bufpool.Get().([]byte) 140 | written, err = io.CopyBuffer(dst, src, buf) 141 | prx.bufpool.Put(buf) 142 | return written, err 143 | } 144 | 145 | var hopHeaders = []string{ 146 | "Connection", 147 | "Keep-Alive", 148 | "Proxy-Authenticate", 149 | "Proxy-Authorization", 150 | "Te", 151 | "Trailers", 152 | "Transfer-Encoding", 153 | "Upgrade", 154 | } 155 | 156 | func (prx *proxy) ServePROXY(rw http.ResponseWriter, req *http.Request) { 157 | hijacker, ok := rw.(http.Hijacker) 158 | if !ok { 159 | log.Println("Not Support Hijacking") 160 | } 161 | client, _, err := hijacker.Hijack() 162 | if err != nil { 163 | log.Println(err) 164 | } 165 | defer client.Close() 166 | // 167 | var address string 168 | if strings.Index(req.Host, ":") == -1 { //host port not include,default 80 169 | address = req.Host + ":http" 170 | } else { 171 | address = req.Host 172 | } 173 | 174 | server, err := net.Dial("tcp", address) 175 | if err != nil { 176 | log.Println(err) 177 | return 178 | } 179 | defer server.Close() 180 | // 181 | if req.Method == http.MethodConnect { 182 | io.WriteString(client, "HTTP/1.1 200 Connection established\r\n\r\n") 183 | //exchange data 184 | go prx.IOCopy(server, client) 185 | prx.IOCopy(client, server) 186 | return 187 | } 188 | // 189 | for _, h := range hopHeaders { 190 | req.Header.Del(h) 191 | } 192 | // 193 | Req := req 194 | //http proxy keep alive 195 | for true { 196 | err = Req.Write(server) 197 | if err != nil { 198 | return 199 | } 200 | Res, err := http.ReadResponse(bufio.NewReader(server), Req) 201 | if err != nil { 202 | return 203 | } 204 | err = Res.Write(client) 205 | if err != nil { 206 | return 207 | } 208 | Req, err = http.ReadRequest(bufio.NewReader(client)) 209 | if err != nil { 210 | return 211 | } 212 | // 213 | for _, h := range hopHeaders { 214 | req.Header.Del(h) 215 | } 216 | // 217 | } 218 | 219 | } 220 | 221 | func (prx *proxy) isblocked(host string) bool { 222 | hostname := stripPort(host) 223 | hostnamelth := len(hostname) 224 | for key, _ := range gfwlist { 225 | if hostnamelth >= len(key) { 226 | subhost := hostname[(hostnamelth - len(key)):] 227 | if key == subhost { 228 | return true 229 | } 230 | } 231 | } 232 | return false 233 | 234 | } 235 | func (prx *proxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) { 236 | var tlscon *tls.Conn 237 | // 238 | if prx.cfg.Autoproxy && (req.Method == http.MethodConnect || req.Method != http.MethodConnect && req.URL.IsAbs()) { 239 | blocked := prx.isblocked(req.Host) 240 | if blocked == false { 241 | log.Printf("Direct Connect %s", req.Host) 242 | prx.ServePROXY(rw, req) 243 | return 244 | } 245 | } 246 | // 247 | if req.Method != http.MethodConnect && !req.URL.IsAbs() { 248 | // 249 | req.URL.Scheme = "https" 250 | if req.Host == "" { 251 | req.URL.Host = "localhost" 252 | } else { 253 | req.URL.Host = req.Host 254 | } 255 | if prx.cfg.Debug { 256 | log.Printf("Request Host:%s", req.URL.Host) 257 | } 258 | 259 | } 260 | // 261 | //Strip ssl 262 | if req.Method == http.MethodConnect { 263 | hijacker, ok := rw.(http.Hijacker) 264 | if !ok { 265 | if req.Body != nil { 266 | req.Body.Close() 267 | } 268 | log.Println("Not Support Hijacking") 269 | return 270 | } 271 | conn, _, err := hijacker.Hijack() 272 | if err != nil { 273 | if req.Body != nil { 274 | req.Body.Close() 275 | } 276 | log.Println(err) 277 | return 278 | } 279 | 280 | _, err = io.WriteString(conn, "HTTP/1.1 200 Connection established\r\n\r\n") 281 | if err != nil { 282 | log.Println(err) 283 | conn.Close() 284 | return 285 | } 286 | 287 | tlscon, err = prx.handleClientConnectRequest(conn, req.URL.Hostname()) 288 | if err != nil { 289 | log.Println(err) 290 | tlscon.Close() 291 | return 292 | } 293 | loConn, err := net.Dial("tcp", prx.cfg.Listen) 294 | if err != nil { 295 | log.Println(err) 296 | tlscon.Close() 297 | return 298 | } 299 | 300 | go prx.IOCopy(tlscon, loConn) 301 | prx.IOCopy(loConn, tlscon) 302 | err = tlscon.Close() 303 | if err != nil { 304 | log.Println(err) 305 | } 306 | err = loConn.Close() 307 | if err != nil { 308 | log.Println(err) 309 | } 310 | return 311 | 312 | } 313 | // 314 | req_op := &request{cfg: prx.cfg, http_req: req} 315 | // 316 | //parse http request 317 | start := time.Now() 318 | req_op.parse_request() 319 | if prx.cfg.Debug == true { 320 | elapsed := time.Since(start) 321 | log.Println("HTTP POST body Proc Time:", elapsed) 322 | } 323 | // 324 | //connect php server 325 | start = time.Now() 326 | var conn_index_tmp int 327 | mux.Lock() 328 | conn_index_tmp = conn_index 329 | conn_index++ 330 | conn_index = conn_index % num_connection 331 | mux.Unlock() 332 | Res, err := prx.client[conn_index_tmp].Do(req_op.cli_req) 333 | if prx.cfg.Debug == true { 334 | elapsed := time.Since(start) 335 | log.Println("HTTP POST Time:", elapsed) 336 | } 337 | if err != nil { 338 | log.Println(err) 339 | if prx.client[conn_index_tmp].tr3 != nil { 340 | prx.client[conn_index_tmp].tr3.Close() 341 | } 342 | origin := req_op.http_req.Header.Get("Origin") 343 | if origin != "" { 344 | rw.Header().Add("Access-Control-Allow-Origin", origin) 345 | rw.Header().Add("Access-Control-Allow-Credentials", "true") 346 | } 347 | http.Error(rw, "empty response", http.StatusBadGateway) 348 | return 349 | } 350 | // 351 | defer Res.Body.Close() 352 | // 353 | proxy_res_data := &response{res: Res, cfg: prx.cfg} 354 | resp := proxy_res_data.parse_response() 355 | 356 | if resp == nil { 357 | log.Println("Response is nil") 358 | return 359 | } 360 | 361 | defer resp.Body.Close() 362 | 363 | for key, values := range resp.Header { 364 | for _, value := range values { 365 | rw.Header().Add(key, value) 366 | if prx.cfg.Debug { 367 | log.Print(key + ":" + value) 368 | } 369 | } 370 | } 371 | //Patch CORS 372 | origin := req_op.http_req.Header.Get("Origin") 373 | if origin != "" && rw.Header().Get("Access-Control-Allow-Origin") == "" { 374 | rw.Header().Add("Access-Control-Allow-Origin", origin) 375 | } 376 | if origin != "" && rw.Header().Get("Access-Control-Allow-Credentials") == "" { 377 | rw.Header().Add("Access-Control-Allow-Credentials", "true") 378 | } 379 | //rw.Header().Set("Set-Cookie", rw.Header().Get("Set-Cookie") + ";HttpOnly;Secure;SameSite=Strict" ) 380 | // 381 | rw.WriteHeader(resp.StatusCode) 382 | _, err = prx.IOCopy(rw, resp.Body) 383 | // 384 | if err != nil { 385 | if strings.Contains(err.Error(), io.ErrUnexpectedEOF.Error()) == true { 386 | hijacker, ok := rw.(http.Hijacker) 387 | if !ok { 388 | log.Println("Not Support Hijacking") 389 | } 390 | conn, _, err := hijacker.Hijack() 391 | if err != nil { 392 | log.Println(err) 393 | } 394 | err = conn.Close() 395 | if err != nil { 396 | log.Println(err) 397 | } 398 | 399 | } else if strings.Contains(err.Error(), "invalid byte in chunk length") == true { 400 | hijacker, ok := rw.(http.Hijacker) 401 | if !ok { 402 | log.Println("Not Support Hijacking") 403 | } 404 | conn, _, err := hijacker.Hijack() 405 | if err != nil { 406 | log.Println(err) 407 | } 408 | err = conn.Close() 409 | if err != nil { 410 | log.Println(err) 411 | } 412 | } else { 413 | log.Println(err) 414 | } 415 | } 416 | } 417 | func (prx *proxy) handleClientConnectRequest(client net.Conn, host string) (tlscon *tls.Conn, err error) { 418 | // 419 | cer := prx.signer.SignHost(host) 420 | // 421 | config := &tls.Config{ 422 | Certificates: []tls.Certificate{*cer}, 423 | } 424 | tlscon = tls.Server(client, config) 425 | err = tlscon.Handshake() 426 | if err != nil { 427 | return tlscon, err 428 | } 429 | return tlscon, nil 430 | } 431 | -------------------------------------------------------------------------------- /server/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | var __version__ ='1.0.1' 4 | var __content_type__='image/gif' 5 | var __password__='123456' 6 | var __chunked__ = 0 7 | 8 | 9 | const about = ` 10 | /****************************************************************************** 11 | * GotoX remote server 0.6 in CloudFlare Workers 12 | * https://github.com/SeaHOH/GotoX 13 | * The MIT License - Copyright (c) 2020 SeaHOH 14 | * 15 | * 16 | * API 17 | * 18 | * "POST" the body to "/gh" or "/gh/" 19 | * With "X-Fetch-Options" header and value is a json format string 20 | * 21 | * {"password": "password", "redirect": false, "decodeemail": true} 22 | * 23 | * Body 24 | * +------------+ 25 | * | 2 bytes | <- deflated request metadata length in uint16 26 | * +------------+ 27 | * | some bytes | <- raw deflated request metadata 28 | * +------------+ 29 | * | others ... | <- origin request body, if has 30 | * +------------+ 31 | * 32 | * Request metadata 33 | * +------------------+ 34 | * | method name l 35 | * +------------------+ 36 | * | a space " " l 37 | * +------------------+ 38 | * | full URL l 39 | * +------------------+ 40 | * | a line wrap "/n" l ---------------+ 41 | * +------------------+ | 42 | * | header name l | 43 | * +------------------+ | 44 | * | a tab "/t" l | <- repeat, if has more headers 45 | * +------------------+ | 46 | * | header value l | 47 | * +------------------+ | 48 | * | more headers ... l ---------------+ 49 | * +------------------+ 50 | * 51 | * 52 | * Direct "GET" "/ws" or "/ws/" for forward WebSocket 53 | * With "X-Fetch-Options" header and value is a json format string 54 | * 55 | * {"password": "password", "url": "needs-origin-ws-url"} 56 | * 57 | * 58 | * Notices 59 | * 60 | * If succeed, returned normal response with a header "X-Fetch-Status: ok", 61 | * or returned response with a header "X-Fetch-Status: fail" and has the 62 | * reason in body. For WebSocket, whether it is a connected response, just 63 | * check the status equal to 101. 64 | * 65 | * Those headers should be removed in local server: 66 | * 67 | * "X-Fetch-Status" is private/self use 68 | * "Expect-CT" is not allowed, we use self-sign CA in local server 69 | * "Nel", "Report-To" are not allowed, this is a proxy server 70 | * "Set-Cookie" which includes "domain=.*.workers.dev" 71 | * "Server" is always "cloudflare" 72 | * "CF-", "Source-" which name starts with it 73 | * 74 | * Those headers should be added in local server: 75 | * 76 | * of response header "Source-" which not in response 77 | * 78 | ******************************************************************************/ 79 | ` 80 | 81 | const nullChunk = new Uint8Array(0) 82 | 83 | // 拦截请求返回自定义响应 84 | addEventListener('fetch', event => event.respondWith(handleRequest(event.request))) 85 | 86 | /* 87 | * Parse the request's fetch options, additional status and error 88 | * @param {Request} request 89 | * @return {Object} 90 | * @return {Number} 91 | * @return {String} 92 | */ 93 | function parseFetch(request, ws) { 94 | const password = '' // 直接在此处设置使用密码,类型为字符串 95 | const headers = request.headers 96 | let fetchOptions, status = 0, err 97 | 98 | try { 99 | // 读取代理设置 100 | fetchOptions = headers.has('X-Fetch-Options') && headers.get('X-Fetch-Options') 101 | fetchOptions = fetchOptions ? JSON.parse(fetchOptions) : {} 102 | // 处理非法请求 103 | if (ws && !(request.method === 'GET' && fetchOptions.url && headers.has('Sec-WebSocket-Key')) || 104 | !ws && !(request.method === 'POST' && headers.has('Content-Length') && !isNaN(headers.get('Content-Length')))) { 105 | throw 'Bad request, please use via GotoX [ https://github.com/SeaHOH/GotoX ].' 106 | } 107 | if (password && fetchOptions.password !== password) { 108 | status = 403 109 | throw 'Access denied, the password is wrong.' 110 | } 111 | status = 0 112 | } catch (error) { 113 | err = error.toString() 114 | } 115 | return [fetchOptions, status, err] 116 | 117 | } 118 | 119 | /* 120 | * Functions of object to decode Scrape Shield Email Address Obfuscation 121 | * function cfEmail.decode 122 | * @param {String} html 123 | * @return {String} 124 | * e.g. 125 | * [email protected] 126 | * 127 | */ 128 | const cfEmail = { 129 | reLink: /<[aA] .+?(email-protection#)([a-f\d]+).+?<\/[aA]>/g, 130 | reLinkSub: /[^"]+email-protection#[^"]+/, 131 | reText: /<[^<]+(data-cfemail=")([a-f\d]+)[^>]+>[^>]+>/g, 132 | decodeEmail: function (match, type, encoded) { 133 | let email = '', r = parseInt(encoded.substring(0, 2), 16) 134 | for (let i = 2; encoded.length - i; i += 2) 135 | email += String.fromCharCode(parseInt(encoded.substring(i, i + 2), 16) ^ r) 136 | // class="__cf_email__" 和 data-cfemail 原始文本为文本 137 | // email-protection# 为超链接 138 | try { 139 | email = decodeURIComponent(escape(email)) 140 | } catch (e) {} 141 | if (type == 'email-protection#') { 142 | email = email.replace(/"/g, '"') 143 | return match.replace(this.reLinkSub, `mailto:${email}`) 144 | } 145 | return email 146 | }, 147 | decode: function (html) { 148 | return html.replace(this.reText, this.decodeEmail) 149 | .replace(this.reLink, this.decodeEmail) 150 | }, 151 | bindAll: function() { 152 | for (let key in this) 153 | if (typeof this[key] === 'function') 154 | this[key] = this[key].bind(this) 155 | } 156 | } 157 | cfEmail.bindAll() 158 | 159 | // 160 | async function streamTransformBody(response, writable) { 161 | 162 | let writer = writable.getWriter() 163 | // 164 | let headerstr= 'HTTP/1.1 '+response.status + ' '+response.statusText +'\r\n' 165 | 166 | for (let [key, value] of response.headers.entries()) { 167 | 168 | if(key == 'transfer-encoding' && value == 'chunked') { 169 | __chunked__ = 0; 170 | } else { 171 | headerstr = headerstr + key + ': ' + value + '\r\n' 172 | } 173 | } 174 | headerstr = headerstr + '\r\n' 175 | // 176 | let uint8array = new TextEncoder("utf-8").encode(headerstr) 177 | 178 | await writer.write(uint8array) 179 | 180 | //some response has not body,only has header 181 | if(response.body==null) { 182 | await writer.close() 183 | return 184 | } 185 | 186 | let reader = response.body.getReader() 187 | // 188 | while (true) { 189 | // 190 | let { done, value } = await reader.read() 191 | if (done) { 192 | if(__chunked__==1) { 193 | let chunkarray = new TextEncoder("utf-8").encode('0\r\n\r\n') 194 | await writer.write(chunkarray) 195 | } 196 | break 197 | } 198 | // 199 | /*XOR encrypt 200 | for (let x = 0; x < value.length; x++){ 201 | value[x] = '1' ^ value[x] 202 | }*/ 203 | if(__chunked__==1) { 204 | let datalthstr=value.length.toString(16) 205 | let datastr = new TextDecoder().decode(value) 206 | let chunkarray = new TextEncoder("utf-8").encode(datalthstr+'\r\n'+datastr+'\r\n') 207 | await writer.write(chunkarray) 208 | } else { 209 | await writer.write(value) 210 | } 211 | 212 | } 213 | 214 | await writer.close() 215 | } 216 | /* 217 | * Main request handler 218 | * @param {Request} request 219 | * @return {Response} 220 | */ 221 | async function handleRequest(request) { 222 | const url = request.url 223 | const path = '/go' //url.substring(url.indexOf('/', 8)) 224 | switch (path) { 225 | case '/gh': 226 | case '/go': 227 | case '/gh/': 228 | if(request.method != 'POST') { 229 | return new Response('OK.', {status: 200}) 230 | } 231 | if(request.body==null) { 232 | return new Response('NULL Post Body.', {status: 200}) 233 | } 234 | /** GotoX 代理 API,普通请求 **/ 235 | try { 236 | let [fetchOptions, status, err] = [{},0,'']//parseFetch(request, false) 237 | 238 | if (err) throw err 239 | // 读取解析代理请求并获取代理请求响应 240 | const response = await fetch(await readRequest(request, fetchOptions), { 241 | redirect: fetchOptions.redirect ? 'follow' : 'manual', 242 | cf: { 243 | scrapeShield: false, // 设置无效果 244 | polish: 'off', 245 | minify: {javascript: false, css: false, html: false}, 246 | mirage: false, 247 | apps: false, 248 | cacheTtl: -1 249 | } 250 | }) 251 | 252 | let body = response.body 253 | const headers = new Headers(response.headers) 254 | //headers.set('X-Fetch-Status', 'ok') 255 | if (fetchOptions.decodeemail) { 256 | // https://support.cloudflare.com/hc/en-us/articles/200170016-What-is-Email-Address-Obfuscation- 257 | // cf.scrapeShield 参数无法关闭 Email Address Obfuscation,解码替换恢复 258 | const ct = headers.has('Content-Type') ? headers.get('Content-Type') : '' 259 | if (ct.includes('text/html') || ct.includes('application/xhtml+xml')) { 260 | body = response.clone().body 261 | // text() 强制使用 UTF-8 解码,编码错误时自动以备用字符替换 262 | // U+FFFD �: REPLACEMENT CHARACTER 263 | const html = await response.text() 264 | if (!html.includes('\ufffd\ufffd\ufffd\ufffd')) { 265 | const decoded = cfEmail.decode(html) 266 | if (decoded !== html) 267 | body = decoded 268 | } 269 | } 270 | } 271 | // 272 | let { readable, writable } = new TransformStream() 273 | //no await 274 | streamTransformBody(response,writable) 275 | // 276 | return new Response(readable, { 277 | //...response, 278 | status:200, 279 | statusText:'OK', 280 | //headers: headers 281 | headers:new Headers({'Content-Type': 'image/x-png'}) 282 | }) 283 | } catch (error) { 284 | const errString = error.toString() 285 | if (status !== 400 && errString.substring(0, 11) === 'Bad request') 286 | status = 400 287 | return new Response(errString, { 288 | status: status || 502, 289 | headers: new Headers({'X-Fetch-Status': 'fail'}) 290 | }) 291 | } 292 | case '/ws': 293 | case '/ws/': 294 | /** GotoX 代理 API,WebSocket 请求 **/ 295 | try { 296 | let [fetchOptions, status, err] = parseFetch(request, true) 297 | if (err) throw err 298 | // 新建代理请求 Headers 299 | const wsHeaders = new Headers() 300 | for (let [key, value] of request.headers.entries()) 301 | // 排除 headers 中保存的请求 IP 等信息 302 | if (!['cf', 'x'].includes(key.substring(0, key.indexOf('-')))) 303 | wsHeaders.append(key, value) 304 | wsHeaders.set('Host', new URL(fetchOptions.url).host) 305 | // 获取代理请求响应 306 | return fetch(new Request(fetchOptions.url, {headers: wsHeaders})) 307 | } catch (error) { 308 | return new Response(error.toString(), { 309 | status: status || 502, 310 | headers: new Headers({'X-Fetch-Status': 'fail'}) 311 | }) 312 | } 313 | case '/robots.txt': 314 | return new Response('User-agent: *\nDisallow: /\n', {status: 200}) 315 | case '/about': 316 | return new Response(about, {status: 200}) 317 | case '/': 318 | return new Response('OK.', {status: 200}) 319 | default: 320 | return new Response('Not found.', {status: 404}) 321 | } 322 | } 323 | 324 | /* 325 | * Read and return a proxy request 326 | * @param {Request} request 327 | * @param {{Object}} fetchOptions 328 | * @return {Request} 329 | */ 330 | async function readRequest(request, fetchOptions) { 331 | 332 | // 根据从第一块数据读取的尺寸为压缩数据分配空间 333 | const bodyReader = request.body.getReader() 334 | let {value: chunk, done: readerDone} = await bodyReader.read() 335 | const requestMetedataLength = new DataView(chunk.buffer, 0, 2).getUint16() 336 | const deflatedBytes = new Uint8Array(requestMetedataLength) 337 | 338 | // 读取压缩数据 339 | let offset = 0, left = requestMetedataLength 340 | chunk = chunk.subarray(2) 341 | do { 342 | if (chunk.length <= left) { 343 | deflatedBytes.set(chunk, offset) 344 | offset += chunk.length 345 | left -= chunk.length 346 | chunk = nullChunk 347 | } 348 | else { 349 | deflatedBytes.set(chunk.subarray(0, left), offset) 350 | chunk = chunk.subarray(left) 351 | break 352 | } 353 | if (!readerDone && left) 354 | ({value: chunk, done: readerDone} = await bodyReader.read()) 355 | } while (left && chunk.length) 356 | 357 | // 解压缩数据 358 | const requestMetadata = new TextDecoder().decode(new Zlib.RawInflate(deflatedBytes).decompress()) 359 | 360 | // 解析代理请求 361 | const [requestLine, ...requestHeadersStrings] = requestMetadata.split('\r\n') 362 | 363 | const [requestMethod, url, protocal] = requestLine.split(' ') 364 | 365 | if (['CONNECT', 'TRACE', 'TRACK'].includes(requestMethod)) 366 | throw `Bad request, ${requestMethod} method is not supported.` 367 | const requestHeaders = new Headers() 368 | for (let headerString of requestHeadersStrings) { 369 | const [key,value] = headerString.split(': ') 370 | if(key!='') { 371 | requestHeaders.append(key,value) 372 | } 373 | } 374 | if(requestHeaders.get('X-Urlfetch-Password')!=__password__) { 375 | throw 'Access denied, the password is wrong.' 376 | } 377 | requestHeaders.delete('X-Urlfetch-Password') 378 | requestHeaders.delete('X-URLFETCH-insecure') 379 | 380 | if (fetchOptions.decodeemail && requestHeaders.has('Accept-Encoding')) { 381 | // 出于文本编辑的需求,当压缩编码为 brotli 时,Worker 无法解码,需禁用 Accept-Encoding: br 382 | let ae = requestHeaders.get('Accept-Encoding').split(/, */) 383 | for (let i = ae.length; --i + 1;) 384 | if (ae[i].includes('br')) 385 | ae.splice(i, 1) 386 | if (ae.length) 387 | requestHeaders.set('Accept-Encoding', ae.join(', ')) 388 | else 389 | requestHeaders.delete('Accept-Encoding') 390 | } 391 | 392 | // 新建代理请求参数 393 | const newRequestInit = { 394 | method: requestMethod, 395 | headers: requestHeaders 396 | } 397 | 398 | // 设置代理请求负载,free plan 限制 100 MB 负载 399 | // fetch() 无法使用 chunked 方式,始终要全部读取后才开始发出请求 400 | // 对上传大量数据是个障碍,会造成多余的延时 401 | 402 | const requestBodyLength = parseInt(request.headers.get('Content-Length')) - 2 - requestMetedataLength 403 | 404 | if (requestBodyLength) 405 | if (['GET', 'HEAD', 'OPTIONS'].includes(requestMethod)) 406 | throw `Bad request, ${requestMethod} method should not has a body.` 407 | else 408 | newRequestInit.body = chunk.length == requestBodyLength && chunk || makeReadableStream(bodyReader, requestBodyLength, left && chunk) 409 | else 410 | bodyReader.releaseLock() 411 | 412 | // 返回代理请求实例 413 | return new Request(url, newRequestInit) 414 | } 415 | 416 | /* 417 | * Convert the give reader and stream length and bytes into a readable stream 418 | * @param {ReadableStreamDefaultReader} reader 419 | * @param {Number} length 420 | * @param {Uint8Array} bytes 421 | * @return {ReadableStream} 422 | */ 423 | function makeReadableStream(reader, length, bytes) { 424 | const pipe = new TransformStream() 425 | pipeStream(reader, pipe.writable.getWriter(), length, bytes) 426 | return pipe.readable 427 | } 428 | 429 | /* 430 | * Pipe give reader and bytes and stream length to give writer 431 | * @param {ReadableStreamDefaultReader} reader 432 | * @param {ReadableStreamDefaultWriter} writer 433 | * @param {Number} length 434 | * @param {Uint8Array} bytes 435 | */ 436 | async function pipeStream(reader, writer, length, bytes) { 437 | let left = length, chunk = bytes || nullChunk, readerDone = false 438 | do { 439 | if (chunk.length) { 440 | await writer.write(chunk) 441 | left -= chunk.length 442 | chunk = nullChunk 443 | } 444 | if (!readerDone && left) 445 | ({value: chunk, done: readerDone} = await reader.read()) 446 | } while (left && chunk.length) 447 | writer.close() 448 | reader.releaseLock() 449 | } 450 | 451 | /* 452 | * Zlib.RawInflate 0.3.1 453 | * @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License 454 | */ 455 | (function() {'use strict';var k=void 0,aa=this;function r(c,d){var a=c.split("."),b=aa;!(a[0]in b)&&b.execScript&&b.execScript("var "+a[0]);for(var e;a.length&&(e=a.shift());)!a.length&&d!==k?b[e]=d:b=b[e]?b[e]:b[e]={}};var t="undefined"!==typeof Uint8Array&&"undefined"!==typeof Uint16Array&&"undefined"!==typeof Uint32Array&&"undefined"!==typeof DataView;function u(c){var d=c.length,a=0,b=Number.POSITIVE_INFINITY,e,f,g,h,l,n,m,p,s,x;for(p=0;pa&&(a=c[p]),c[p]>=1;x=g<<16|p;for(s=n;s>>=1;switch(c){case 0:var d=this.input,a=this.d,b=this.b,e=this.a,f=d.length,g=k,h=k,l=b.length,n=k;this.c=this.f=0;if(a+1>=f)throw Error("invalid uncompressed block header: LEN");g=d[a++]|d[a++]<<8;if(a+1>=f)throw Error("invalid uncompressed block header: NLEN");h=d[a++]|d[a++]<<8;if(g===~h)throw Error("invalid uncompressed block header: length verify");if(a+g>d.length)throw Error("input buffer is broken");switch(this.i){case A:for(;e+g>b.length;){n=l-e;g-=n;if(t)b.set(d.subarray(a,a+n),e),e+=n,a+=n;else for(;n--;)b[e++]=d[a++];this.a=e;b=this.e();e=this.a}break;case y:for(;e+g>b.length;)b=this.e({o:2});break;default:throw Error("invalid inflate mode");}if(t)b.set(d.subarray(a,a+g),e),e+=g,a+=g;else for(;g--;)b[e++]=d[a++];this.d=a;this.a=e;this.b=b;break;case 1:this.j(ba,ca);break;case 2:for(var m=B(this,5)+257,p=B(this,5)+1,s=B(this,4)+4,x=new (t?Uint8Array:Array)(C.length),Q=k,R=k,S=k,v=k,M=k,F=k,z=k,q=k,T=k,q=0;q=U?8:255>=U?9:279>=U?7:8;var ba=u(P),V=new (t?Uint8Array:Array)(30),W,ea;W=0;for(ea=V.length;W=g)throw Error("input buffer is broken");a|=e[f++]<>>d;c.c=b-d;c.d=f;return h}function D(c,d){for(var a=c.f,b=c.c,e=c.input,f=c.d,g=e.length,h=d[0],l=d[1],n,m;b=g);)a|=e[f++]<>>16;if(m>b)throw Error("invalid code length: "+m);c.f=a>>m;c.c=b-m;c.d=f;return n&65535}w.prototype.j=function(c,d){var a=this.b,b=this.a;this.n=c;for(var e=a.length-258,f,g,h,l;256!==(f=D(this,c));)if(256>f)b>=e&&(this.a=b,a=this.e(),b=this.a),a[b++]=f;else{g=f-257;l=H[g];0=e&&(this.a=b,a=this.e(),b=this.a);for(;l--;)a[b]=a[b++-h]}for(;8<=this.c;)this.c-=8,this.d--;this.a=b};w.prototype.s=function(c,d){var a=this.b,b=this.a;this.n=c;for(var e=a.length,f,g,h,l;256!==(f=D(this,c));)if(256>f)b>=e&&(a=this.e(),e=a.length),a[b++]=f;else{g=f-257;l=H[g];0e&&(a=this.e(),e=a.length);for(;l--;)a[b]=a[b++-h]}for(;8<=this.c;)this.c-=8,this.d--;this.a=b};w.prototype.e=function(){var c=new (t?Uint8Array:Array)(this.a-32768),d=this.a-32768,a,b,e=this.b;if(t)c.set(e.subarray(32768,c.length));else{a=0;for(b=c.length;aa;++a)e[a]=e[d+a];this.a=32768;return e};w.prototype.u=function(c){var d,a=this.input.length/this.d+1|0,b,e,f,g=this.input,h=this.b;c&&("number"===typeof c.o&&(a=c.o),"number"===typeof c.q&&(a+=c.q));2>a?(b=(g.length-this.d)/this.n[2],f=258*(b/2)|0,e=fd&&(this.b.length=d),c=this.b);return this.buffer=c};r("Zlib.RawInflate",w);r("Zlib.RawInflate.prototype.decompress",w.prototype.t);var X={ADAPTIVE:y,BLOCK:A},Y,Z,$,fa;if(Object.keys)Y=Object.keys(X);else for(Z in Y=[],$=0,X)Y[$++]=Z;$=0;for(fa=Y.length;$ 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------