2 Copyright (C) 2021 Sergey Matveev <stargrave@stargrave.org>
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, version 3 of the License.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program. If not, see <http://www.gnu.org/licenses/>.
37 "github.com/dustin/go-humanize"
38 "go.cypherpunks.ru/ucspi"
42 tlsNextProtoS = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
43 caCert *x509.Certificate
44 caPrv crypto.PrivateKey
45 transport = http.Transport{
46 DialTLSContext: dialTLS,
47 ForceAttemptHTTP2: true,
49 sessionCache = tls.NewLRUClientSessionCache(1024)
54 imageExts = map[string]struct{}{
72 func dialTLS(ctx context.Context, network, addr string) (net.Conn, error) {
73 host := strings.TrimSuffix(addr, ":443")
75 VerifyPeerCertificate: func(
77 verifiedChains [][]*x509.Certificate,
79 return verifyCert(host, nil, rawCerts, verifiedChains)
81 ClientSessionCache: sessionCache,
82 NextProtos: []string{"h2", "http/1.1"},
84 conn, dialErr := tls.Dial(network, addr, &cfg)
86 if _, ok := dialErr.(ErrRejected); ok {
89 cfg.InsecureSkipVerify = true
90 cfg.VerifyPeerCertificate = func(
92 verifiedChains [][]*x509.Certificate,
94 return verifyCert(host, dialErr, rawCerts, verifiedChains)
97 conn, err = tls.Dial(network, addr, &cfg)
99 sinkErr <- fmt.Sprintf("%s\t%s", addr, dialErr.Error())
103 connState := conn.ConnectionState()
104 if connState.DidResume {
105 sinkTLS <- fmt.Sprintf(
107 strings.TrimSuffix(addr, ":443"),
108 ucspi.TLSVersion(connState.Version),
109 tls.CipherSuiteName(connState.CipherSuite),
110 spkiHash(connState.PeerCertificates[0]),
111 connState.NegotiatedProtocol,
117 func roundTrip(w http.ResponseWriter, req *http.Request) {
118 if req.Method == http.MethodHead {
119 http.Error(w, "go away", http.StatusMethodNotAllowed)
122 sinkReq <- fmt.Sprintf("%s %s", req.Method, req.URL.String())
123 host := strings.TrimSuffix(req.URL.Host, ":443")
125 for _, spy := range SpyDomains {
126 if strings.HasSuffix(host, spy) {
127 http.NotFound(w, req)
128 sinkOther <- fmt.Sprintf(
129 "%s %s\t%d\tspy one",
138 if host == "www.reddit.com" {
139 req.URL.Host = "old.reddit.com"
140 http.Redirect(w, req, req.URL.String(), http.StatusMovedPermanently)
144 if host == "habrastorage.org" && strings.Contains(req.URL.Path, "r/w780q1") {
145 req.URL.Path = strings.Replace(req.URL.Path, "r/w780q1/", "", 1)
146 http.Redirect(w, req, req.URL.String(), http.StatusFound)
150 resp, err := transport.RoundTrip(req)
152 sinkErr <- fmt.Sprintf("%s\t%s", req.URL.Host, err.Error())
153 w.WriteHeader(http.StatusBadGateway)
154 w.Write([]byte(err.Error()))
158 for k, vs := range resp.Header {
159 if k == "Location" || k == "Content-Type" || k == "Content-Length" {
162 for _, v := range vs {
167 switch resp.Header.Get("Content-Type") {
168 case "application/font-woff", "application/font-sfnt":
169 // Those are deprecated types
171 case "font/otf", "font/ttf", "font/woff", "font/woff2":
172 http.NotFound(w, req)
173 sinkOther <- fmt.Sprintf(
174 "%s %s\t%d\tfonts are not allowed",
182 if strings.Contains(req.Header.Get("User-Agent"), "AppleWebKit/538.15") {
186 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.webp")
191 defer os.Remove(tmpFd.Name())
192 defer resp.Body.Close()
193 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
194 log.Printf("Error during %s: %+v\n", req.URL, err)
195 http.Error(w, err.Error(), http.StatusBadGateway)
199 cmd := exec.Command(CmdDWebP, tmpFd.Name(), "-o", "-")
200 data, err := cmd.Output()
202 http.Error(w, err.Error(), http.StatusBadGateway)
205 w.Header().Add("Content-Type", "image/png")
206 w.WriteHeader(http.StatusOK)
208 sinkOther <- fmt.Sprintf(
209 "%s %s\t%d\tWebP transcoded to PNG",
216 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.jxl")
221 defer os.Remove(tmpFd.Name())
222 defer resp.Body.Close()
223 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
224 log.Printf("Error during %s: %+v\n", req.URL, err)
225 http.Error(w, err.Error(), http.StatusBadGateway)
229 dstFn := tmpFd.Name() + ".png"
230 cmd := exec.Command(CmdDJXL, tmpFd.Name(), dstFn)
232 defer os.Remove(dstFn)
234 http.Error(w, err.Error(), http.StatusBadGateway)
237 data, err := ioutil.ReadFile(dstFn)
239 http.Error(w, err.Error(), http.StatusBadGateway)
242 w.Header().Add("Content-Type", "image/png")
243 w.WriteHeader(http.StatusOK)
245 sinkOther <- fmt.Sprintf(
246 "%s %s\t%d\tJPEG XL transcoded to PNG",
254 if req.Method == http.MethodGet {
256 switch resp.StatusCode {
257 case http.StatusMovedPermanently, http.StatusPermanentRedirect:
258 redirType = "permanent"
260 case http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:
261 if strings.Contains(req.Header.Get("User-Agent"), "newsboat/") {
264 if _, ok := imageExts[filepath.Ext(req.URL.Path)]; ok {
267 redirType = "temporary"
273 w.Header().Add("Content-Type", "text/html")
274 w.WriteHeader(http.StatusOK)
275 location := resp.Header.Get("Location")
278 `<html><head><title>%d %s: %s redirection</title></head>
279 <body>Redirection to <a href="%s">%s</a></body></html>`,
280 resp.StatusCode, http.StatusText(resp.StatusCode),
281 redirType, location, location,
283 sinkRedir <- fmt.Sprintf(
284 "%s %s\t%s\t%s", req.Method, resp.Status, req.URL.String(), location,
290 for _, h := range []string{"Location", "Content-Type", "Content-Length"} {
291 if v := resp.Header.Get(h); v != "" {
295 w.WriteHeader(resp.StatusCode)
296 n, err := io.Copy(w, resp.Body)
298 log.Printf("Error during %s: %+v\n", req.URL, err)
306 resp.Header.Get("Content-Type"),
307 humanize.IBytes(uint64(n)),
309 if resp.StatusCode == http.StatusOK {
316 type Handler struct{}
318 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
319 if req.Method != http.MethodConnect {
323 hj, ok := w.(http.Hijacker)
325 log.Fatalln("no hijacking")
327 conn, _, err := hj.Hijack()
332 conn.Write([]byte(fmt.Sprintf(
335 http.StatusOK, http.StatusText(http.StatusOK),
337 host := strings.Split(req.Host, ":")[0]
339 keypair, ok := hostCerts[host]
340 if !ok || !keypair.cert.NotAfter.After(time.Now().Add(time.Hour)) {
341 keypair = newKeypair(host, caCert, caPrv)
342 hostCerts[host] = keypair
345 tlsConn := tls.Server(conn, &tls.Config{
346 Certificates: []tls.Certificate{{
347 Certificate: [][]byte{keypair.cert.Raw},
348 PrivateKey: keypair.prv,
351 if err = tlsConn.Handshake(); err != nil {
352 log.Printf("TLS error %s: %+v\n", host, err)
356 Handler: &HTTPSHandler{host: req.Host},
357 TLSNextProto: tlsNextProtoS,
359 err = srv.Serve(&SingleListener{conn: tlsConn})
361 if _, ok := err.(AlreadyAccepted); !ok {
362 log.Printf("TLS serve error %s: %+v\n", host, err)
368 type HTTPSHandler struct {
372 func (h *HTTPSHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
373 req.URL.Scheme = "https"
374 req.URL.Host = h.host
379 crtPath := flag.String("cert", "cert.pem", "Path to server X.509 certificate")
380 prvPath := flag.String("key", "prv.pem", "Path to server PKCS#8 private key")
381 bind := flag.String("bind", "[::1]:8080", "Bind address")
382 certs = flag.String("certs", "certs", "Directory with pinned certificates")
383 dnsSrv = flag.String("dns", "[::1]:53", "DNS server")
384 fifos = flag.String("fifos", "fifos", "Directory with FIFOs")
385 notai = flag.Bool("notai", false, "Do not prepend TAI64N to logs")
387 log.SetFlags(log.Lshortfile)
391 _, caCert, err = ucspi.CertificateFromFile(*crtPath)
395 caPrv, err = ucspi.PrivateKeyFromFile(*prvPath)
400 ln, err := net.Listen("tcp", *bind)
406 TLSNextProto: tlsNextProtoS,
408 log.Println("listening:", *bind)
409 if err := srv.Serve(ln); err != nil {