├── .gitignore ├── LICENSE ├── OPENSOURCELICENSE ├── README.md ├── boolflag.go ├── build └── build.sh ├── config.go ├── dns.go ├── main.go └── open.go /.gitignore: -------------------------------------------------------------------------------- 1 | build/go-pixiv-* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2018] [eternal-flame-AD] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /OPENSOURCELICENSE: -------------------------------------------------------------------------------- 1 | === 2 | # goproxy 3 | 4 | Copyright (c) 2012 Elazar Leibovich. All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are 8 | met: 9 | 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above 13 | copyright notice, this list of conditions and the following disclaimer 14 | in the documentation and/or other materials provided with the 15 | distribution. 16 | * Neither the name of Elazar Leibovich. nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | === -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-pixiv 2 | 3 | Bypass SNI censorship on Pixiv with golang 4 | 5 | golang隐藏SNI绕过对Pixiv的SNI封锁 6 | 7 | ## Installation 8 | 9 | ### 下载二进制文件 10 | 从[发布页](https://github.com/eternal-flame-AD/go-pixiv/releases)下载最新二进制build 11 | ### 从源码编译 12 | ```bash 13 | go get -u -v github.com/eternal-flame-AD/go-pixiv 14 | ``` 15 | 16 | ## Usage 17 | 18 | 1. 在计算机上安装[这个CA证书](https://github.com/eternal-flame-AD/goproxy/raw/master/ca.pem)(右键另存为),安装方法自行百度(帮你百度好了[Chrome](https://jingyan.baidu.com/article/c843ea0bc4142a77921e4a79.html)和[Firefox](https://jingyan.baidu.com/article/4e5b3e191205d291911e2463.html)的) 19 | 2. 设置浏览器代理为 http://127.0.0.1:8080 ,方法参见上一步,**注意HTTPS也要走代理(勾选“对以下协议使用相同代理”)** 20 | 3. 运行go-pixiv,浏览器应该会自动打开一个诊断窗口,检查浏览器的代理和证书信任配置是否正确,DNS能否正常工作。 21 | 4. OK 22 | 23 | ## Troubleshooting 24 | 25 | - `Proxy is not enabled, please set your local proxy to http://127.0.0.1:8080/` 未设置浏览器代理 26 | - `CA Trust: Error` 浏览器不信任Go-Pixiv使用的证书,检查Usage中第一步是否正确,注意Firefox有自己的keychain 27 | - `DNS-Over-Https: Error` 部分域名未能解析到可用的IP地址,解析正常的域名可以继续访问。如果遇到全部错误的情况,可能是你的网络封禁了1.0.0.1 -------------------------------------------------------------------------------- /boolflag.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | type boolflag struct { 9 | val *bool 10 | } 11 | 12 | func (c boolflag) String() string { 13 | if c.val == nil { 14 | return "" 15 | } 16 | return strconv.FormatBool(*c.val) 17 | } 18 | 19 | func (_ boolflag) IsBoolFlag() bool { 20 | return true 21 | } 22 | 23 | func (c boolflag) Set(s string) error { 24 | switch s { 25 | case "no": 26 | case "false": 27 | case "yes": 28 | fallthrough 29 | case "true": 30 | fallthrough 31 | case "": 32 | *c.val = true 33 | default: 34 | return fmt.Errorf("Failed to parse boolflag param %s", s) 35 | } 36 | return nil 37 | } 38 | 39 | func (c *boolflag) Get() interface{} { 40 | return *c.val 41 | } 42 | -------------------------------------------------------------------------------- /build/build.sh: -------------------------------------------------------------------------------- 1 | env GOOS=linux GOARCH=386 go build -ldflags="-s -w" -o go-pixiv-linux-386 -v github.com/eternal-flame-AD/go-pixiv 2 | env GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o go-pixiv-linux-amd64 -v github.com/eternal-flame-AD/go-pixiv 3 | env GOOS=windows GOARCH=386 go build -ldflags="-s -w" -o go-pixiv-windows-386.exe -v github.com/eternal-flame-AD/go-pixiv 4 | env GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o go-pixiv-windows-amd64.exe -v github.com/eternal-flame-AD/go-pixiv 5 | upx --lzma go-pixiv-* 6 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | var ( 4 | Config struct { 5 | DNSEndpoint string 6 | Verbose bool 7 | } 8 | ) 9 | -------------------------------------------------------------------------------- /dns.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "strconv" 7 | 8 | httpclient "github.com/ddliu/go-httpclient" 9 | ) 10 | 11 | const ( 12 | QueryRetryTimes = 5 13 | UserAgent = "go-pixiv" 14 | WfJSON = "application/dns-json" 15 | ) 16 | 17 | type DNSQuery struct { 18 | name string 19 | rrtype string 20 | endpoint string 21 | dnssec bool 22 | insecure bool 23 | } 24 | 25 | func (c *DNSQuery) Do() (*DNSQueryResponse, error) { 26 | url := fmt.Sprintf("%s?ct=%s&name=%s&type=%s&do=%s&cd=%s", c.endpoint, WfJSON, c.name, c.rrtype, strconv.FormatBool(c.dnssec), strconv.FormatBool(c.insecure)) 27 | var err error 28 | var respbytes []byte 29 | for i := 0; i < QueryRetryTimes; i++ { 30 | resp, err := httpclient. 31 | Begin(). 32 | WithHeader("User-Agent", UserAgent). 33 | Get(url) 34 | if err != nil { 35 | continue 36 | } 37 | respbytes, err = resp.ReadAll() 38 | if err != nil { 39 | continue 40 | } 41 | break 42 | } 43 | if err != nil { 44 | return nil, err 45 | } 46 | answer := &DNSQueryResponse{} 47 | err = json.Unmarshal(respbytes, answer) 48 | return answer, err 49 | } 50 | 51 | type DNSQueryResponse struct { 52 | Status int `json:"Status"` 53 | Truncated bool `json:"TC"` 54 | RecursiveDesired bool `json:"RD"` 55 | RecursiveAvailable bool `json:"RA"` 56 | DNSSECVerified bool `json:"AD"` 57 | DNSSECVerifyDisabled bool `json:"CD"` 58 | Question []DNSQuestion `json:"Question"` 59 | Answer []DNSAnswer `json:"Answer"` 60 | } 61 | type DNSQuestion struct { 62 | Name string `json:"name"` 63 | Type int `json:"type"` 64 | } 65 | type DNSAnswer struct { 66 | Type int `json:"type"` 67 | TTL int `json:"TTL"` 68 | Data string `json:"data"` 69 | } 70 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "crypto/tls" 7 | "crypto/x509" 8 | "encoding/json" 9 | "errors" 10 | "flag" 11 | "fmt" 12 | "html/template" 13 | "io" 14 | "io/ioutil" 15 | "log" 16 | "net" 17 | "net/http" 18 | "runtime/debug" 19 | "strings" 20 | "sync" 21 | "time" 22 | 23 | "github.com/eternal-flame-AD/goproxy" 24 | ) 25 | 26 | var ( 27 | BlackHoleDomains = []string{ 28 | "www.google.com", 29 | "google.com", 30 | "fonts.googleapis.com", 31 | } 32 | 33 | PixivDomains = []string{ 34 | "pixiv.net", 35 | "www.pixiv.net", 36 | "i.pximg.net", 37 | "source.pixiv.net", 38 | "accounts.pixiv.net", 39 | "touch.pixiv.net", 40 | "imgaz.pixiv.net", 41 | "app-api.pixiv.net", 42 | "oauth.secure.pixiv.net", 43 | "dic.pixiv.net", 44 | "comic.pixiv.net", 45 | "factory.pixiv.net", 46 | "g-client-proxy.pixiv.net", 47 | "sketch.pixiv.net", 48 | "payment.pixiv.net", 49 | "sensei.pixiv.net", 50 | "novel.pixiv.net", 51 | "en-dic.pixiv.net", 52 | "i1.pixiv.net", 53 | "i2.pixiv.net", 54 | "i3.pixiv.net", 55 | "i4.pixiv.net", 56 | "d.pixiv.org", 57 | "pixiv.pximg.net", 58 | "fanbox.pixiv.net", 59 | "s.pximg.net", 60 | "pixivsketch.net", 61 | "pximg.net", 62 | } 63 | 64 | PixivDomainsWithPort []string 65 | BlackHoleDomainsWithPort []string 66 | 67 | FakeConfigCache = make(map[string]*tls.Config, 0) 68 | IPCache = struct { 69 | Data map[string]string 70 | Lock sync.RWMutex 71 | }{make(map[string]string), sync.RWMutex{}} 72 | ) 73 | 74 | func orPanic(err error) { 75 | if err != nil { 76 | panic(err) 77 | } 78 | } 79 | 80 | func init() { 81 | PixivDomainsWithPort = make([]string, len(PixivDomains)) 82 | BlackHoleDomainsWithPort = make([]string, len(BlackHoleDomains)) 83 | for i, name := range PixivDomains { 84 | PixivDomainsWithPort[i] = name + ":443" 85 | } 86 | for i, name := range BlackHoleDomains { 87 | BlackHoleDomainsWithPort[i] = name + ":443" 88 | } 89 | } 90 | 91 | func updateDeadline(conn *tls.Conn, duration time.Duration) { 92 | conn.SetDeadline(time.Now().Add(duration)) 93 | } 94 | 95 | func main() { 96 | verbosevar := boolflag{new(bool)} 97 | flag.Var(verbosevar, "v", "verbose") 98 | listen := flag.String("l", ":8080", "listen address") 99 | endpoint := flag.String("e", "https://1.0.0.1/dns-query", "DoH endpoint") 100 | flag.Parse() 101 | Config.DNSEndpoint = *endpoint 102 | Config.Verbose = verbosevar.Get().(bool) 103 | 104 | proxy := goproxy.NewProxyHttpServer() 105 | proxy.OnRequest( 106 | goproxy.ReqHostIs("go-pixiv.local"), 107 | ).DoFunc(func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { 108 | client := http.Client{} 109 | r.URL.Host = "127.0.0.1:8081" 110 | req, err := http.NewRequest(r.Method, r.URL.String(), r.Body) 111 | req.Header.Add("X-Proxy-Thru", "1") 112 | resp, err := client.Do(req) 113 | if err != nil { 114 | return r, nil 115 | } 116 | resp.Header.Add("X-Proxy-Thru", "1") 117 | resp.Header.Add("Access-Control-Allow-Origin", "*") 118 | return r, resp 119 | }) 120 | 121 | proxy.OnRequest( 122 | goproxy.ReqHostIs("go-pixiv.local:443"), 123 | ).HijackConnect(func(req *http.Request, clientraw net.Conn, ctx *goproxy.ProxyCtx) { 124 | cfg, err := goproxy.TLSConfigFromCA(&goproxy.GoproxyCa)("go-pixiv.local", ctx) 125 | if err != nil { 126 | log.Panicln(err) 127 | } 128 | server := tls.Server(clientraw, cfg) 129 | body := "" 130 | resp := &http.Response{ 131 | Status: "200 OK", 132 | StatusCode: 200, 133 | Proto: "HTTP/1.1", 134 | ProtoMajor: 1, 135 | ProtoMinor: 1, 136 | Body: ioutil.NopCloser(bytes.NewBufferString(body)), 137 | ContentLength: int64(len(body)), 138 | Request: req, 139 | Header: make(http.Header, 0), 140 | } 141 | resp.Header.Add("Access-Control-Allow-Origin", "*") 142 | resp.Write(server) 143 | server.CloseWrite() 144 | }) 145 | 146 | proxy.OnRequest( 147 | goproxy.ReqHostIs(BlackHoleDomainsWithPort...), 148 | ).HandleConnect(goproxy.AlwaysReject) 149 | 150 | proxy.OnRequest( 151 | goproxy.ReqHostIs(PixivDomainsWithPort...), 152 | ).HijackConnect(func(req *http.Request, clientraw net.Conn, ctx *goproxy.ProxyCtx) { 153 | defer func() { 154 | if e := recover(); e != nil { 155 | ctx.Logf("error connecting to remote: %v", e) 156 | if Config.Verbose { 157 | debug.PrintStack() 158 | } 159 | clientraw.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n")) 160 | } 161 | clientraw.Close() 162 | }() 163 | 164 | log.Printf("Establishing connection to %s\n", ctx.Req.URL.Hostname()) 165 | 166 | processchan := make(chan error) 167 | clientTLSConfig, err := func(host string) (*tls.Config, error) { 168 | if config, ok := FakeConfigCache[host]; ok { 169 | return config, nil 170 | } 171 | config, err := goproxy.TLSConfigFromCA(&goproxy.GoproxyCa)(host, ctx) 172 | if err != nil { 173 | return nil, err 174 | } 175 | FakeConfigCache[host] = config 176 | return config, nil 177 | }(ctx.Req.URL.Host) 178 | orPanic(err) 179 | client := tls.Server(clientraw, clientTLSConfig) 180 | updateDeadline(client, 5*time.Second) 181 | orPanic(client.Handshake()) 182 | defer client.Close() 183 | 184 | clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client)) 185 | 186 | remoteraw := func() net.Conn { 187 | IPCache.Lock.RLock() 188 | ip, ok := IPCache.Data[ctx.Req.URL.Hostname()] 189 | IPCache.Lock.RUnlock() 190 | if ok { 191 | remoteraw, err := net.Dial("tcp", ip+ctx.Req.Host[strings.LastIndex(ctx.Req.Host, ":"):]) 192 | if err == nil { 193 | if Config.Verbose { 194 | log.Println("Successfully retrieved IP cache for " + ctx.Req.URL.Hostname()) 195 | } 196 | return remoteraw 197 | } 198 | } 199 | query := DNSQuery{ 200 | ctx.Req.URL.Hostname(), 201 | "A", 202 | Config.DNSEndpoint, 203 | false, 204 | false, 205 | } 206 | log.Printf("Obtaining DNS records for %s\n", ctx.Req.URL.Hostname()) 207 | res, err := query.Do() 208 | orPanic(err) 209 | for _, ans := range res.Answer { 210 | var err error 211 | if ans.Type != 1 { 212 | continue 213 | } 214 | remoteraw, err := net.Dial("tcp", ans.Data+ctx.Req.Host[strings.LastIndex(ctx.Req.Host, ":"):]) 215 | if err == nil { 216 | IPCache.Lock.Lock() 217 | IPCache.Data[ctx.Req.URL.Hostname()] = ans.Data 218 | IPCache.Lock.Unlock() 219 | return remoteraw 220 | } 221 | if Config.Verbose { 222 | fmt.Println("Error while attempting connect: " + err.Error()) 223 | } 224 | } 225 | return nil 226 | }() 227 | if remoteraw == nil { 228 | panic("No available IPs for " + ctx.Req.URL.Hostname()) 229 | } 230 | if Config.Verbose { 231 | log.Printf("Estabished remote connection for %s (%s)\n", ctx.Req.URL.Hostname(), remoteraw.RemoteAddr()) 232 | } 233 | defer remoteraw.Close() 234 | 235 | remote := tls.Client(remoteraw, &tls.Config{ 236 | InsecureSkipVerify: true, 237 | VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error { 238 | certs := make([]*x509.Certificate, len(rawCerts)) 239 | for i, c := range rawCerts { 240 | var err error 241 | certs[i], err = x509.ParseCertificate(c) 242 | if err != nil { 243 | return errors.New("Cert parse failed: " + err.Error()) 244 | } 245 | } 246 | opts := x509.VerifyOptions{ 247 | DNSName: ctx.Req.URL.Hostname(), 248 | Intermediates: x509.NewCertPool(), 249 | } 250 | 251 | for i, cert := range certs { 252 | if i == 0 { 253 | continue 254 | } 255 | opts.Intermediates.AddCert(cert) 256 | } 257 | _, err := certs[0].Verify(opts) 258 | if err != nil { 259 | //Fallback 260 | for _, name := range PixivDomains { 261 | opts.DNSName = name 262 | _, err := certs[0].Verify(opts) 263 | if err == nil { 264 | return nil 265 | } 266 | } 267 | } 268 | if err != nil { 269 | log.Printf("Refusing to connect to %s: Cert invalid: Remote certificate is for %s\n", ctx.Req.URL.Hostname(), certs[0].DNSNames) 270 | } 271 | return err 272 | }, 273 | }) 274 | orPanic(remote.Handshake()) 275 | log.Printf("Handshake to %s succeeded:)\n", ctx.Req.URL.Hostname()) 276 | defer remote.Close() 277 | remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote)) 278 | 279 | go func() { 280 | buffer := make([]byte, 1024) 281 | var err error 282 | for { 283 | updateDeadline(client, 5*time.Second) 284 | num, err := clientBuf.Read(buffer) 285 | if err == io.EOF { 286 | break 287 | } 288 | if err != nil { 289 | break 290 | } 291 | _, err = remoteBuf.Write(buffer[:num]) 292 | if err != nil { 293 | break 294 | } 295 | if err = remoteBuf.Flush(); err != nil { 296 | break 297 | } 298 | } 299 | processchan <- err 300 | }() 301 | go func() { 302 | buffer := make([]byte, 1024) 303 | var err error 304 | for { 305 | updateDeadline(client, 5*time.Second) 306 | num, err := remoteBuf.Read(buffer) 307 | if err == io.EOF { 308 | break 309 | } 310 | if err != nil { 311 | break 312 | } 313 | _, err = clientBuf.Write(buffer[:num]) 314 | if err != nil { 315 | break 316 | } 317 | if err = clientBuf.Flush(); err != nil { 318 | break 319 | } 320 | } 321 | processchan <- err 322 | }() 323 | 324 | orPanic(<-processchan) 325 | orPanic(<-processchan) 326 | 327 | if Config.Verbose { 328 | log.Println("Closing connection for " + ctx.Req.URL.Hostname()) 329 | } 330 | }) 331 | proxy.Verbose = Config.Verbose 332 | 333 | go func() { 334 | managemux := http.NewServeMux() 335 | managemux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 336 | if r.Header.Get("X-Proxy-Thru") == "" { 337 | // No proxy, check proxy config with fetch 338 | w.Header().Add("Content-Type", "text/html") 339 | w.WriteHeader(200) 340 | w.Write([]byte(` 341 | 344 | `)) 351 | return 352 | } 353 | 354 | tpl, err := template.New("Manage-Main").Parse(` 355 | 356 | 357 | Go-Pixiv 358 | 369 | 370 | 371 |

Go-Pixiv

372 | 383 | 384 | 424 | 425 | 426 | `) 427 | if err != nil { 428 | log.Println(err) 429 | } 430 | w.WriteHeader(200) 431 | tpl.Execute(w, PixivDomains) 432 | }) 433 | 434 | managemux.HandleFunc("/dns", func(w http.ResponseWriter, r *http.Request) { 435 | host := r.URL.RawQuery 436 | 437 | response := struct { 438 | Success bool `json:"success"` 439 | Data string `json:"data"` 440 | }{} 441 | req := DNSQuery{ 442 | host, 443 | "A", 444 | Config.DNSEndpoint, 445 | false, 446 | false, 447 | } 448 | res, err := req.Do() 449 | if err != nil { 450 | response.Data = err.Error() 451 | resp, _ := json.Marshal(response) 452 | w.WriteHeader(500) 453 | w.Write(resp) 454 | return 455 | } 456 | for _, item := range res.Answer { 457 | if item.Type != 1 { 458 | continue 459 | } 460 | 461 | remoteraw, err := net.Dial("tcp", item.Data+":443") 462 | if err != nil { 463 | response.Success = false 464 | response.Data = err.Error() 465 | continue 466 | } 467 | response.Success = true 468 | IPCache.Lock.Lock() 469 | IPCache.Data[host] = item.Data 470 | IPCache.Lock.Unlock() 471 | response.Data = item.Data 472 | remoteraw.Close() 473 | break 474 | } 475 | resp, err := json.Marshal(response) 476 | if err != nil { 477 | log.Println(err) 478 | } 479 | w.WriteHeader(200) 480 | w.Write(resp) 481 | }) 482 | http.ListenAndServe("127.0.0.1:8081", managemux) 483 | }() 484 | go func() { 485 | openbrowser("http://127.0.0.1:8081") 486 | }() 487 | 488 | log.Fatal(http.ListenAndServe(*listen, proxy)) 489 | } 490 | -------------------------------------------------------------------------------- /open.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os/exec" 6 | "runtime" 7 | ) 8 | 9 | func openbrowser(url string) error { 10 | var err error 11 | 12 | switch runtime.GOOS { 13 | case "linux": 14 | err = exec.Command("xdg-open", url).Start() 15 | case "windows": 16 | err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() 17 | case "darwin": 18 | err = exec.Command("open", url).Start() 19 | default: 20 | err = fmt.Errorf("unsupported platform") 21 | } 22 | return err 23 | 24 | } 25 | --------------------------------------------------------------------------------