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 strings.HasPrefix(req.URL.Host, "www.reddit.com") {
139 req.URL.Host = "old.reddit.com"
140 http.Redirect(w, req, req.URL.String(), http.StatusMovedPermanently)
144 resp, err := transport.RoundTrip(req)
146 sinkErr <- fmt.Sprintf("%s\t%s", req.URL.Host, err.Error())
147 w.WriteHeader(http.StatusBadGateway)
148 w.Write([]byte(err.Error()))
152 for k, vs := range resp.Header {
153 if k == "Location" || k == "Content-Type" || k == "Content-Length" {
156 for _, v := range vs {
161 switch resp.Header.Get("Content-Type") {
162 case "application/font-woff", "application/font-sfnt":
163 // Those are deprecated types
165 case "font/otf", "font/ttf", "font/woff", "font/woff2":
166 http.NotFound(w, req)
167 sinkOther <- fmt.Sprintf(
168 "%s %s\t%d\tfonts are not allowed",
176 if strings.Contains(req.Header.Get("User-Agent"), "AppleWebKit/538.15") {
180 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.webp")
185 defer os.Remove(tmpFd.Name())
186 defer resp.Body.Close()
187 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
188 log.Printf("Error during %s: %+v\n", req.URL, err)
189 http.Error(w, err.Error(), http.StatusBadGateway)
193 cmd := exec.Command(CmdDWebP, tmpFd.Name(), "-o", "-")
194 data, err := cmd.Output()
196 http.Error(w, err.Error(), http.StatusBadGateway)
199 w.Header().Add("Content-Type", "image/png")
200 w.WriteHeader(http.StatusOK)
202 sinkOther <- fmt.Sprintf(
203 "%s %s\t%d\tWebP transcoded to PNG",
210 tmpFd, err := ioutil.TempFile("", "tofuproxy.*.jxl")
215 defer os.Remove(tmpFd.Name())
216 defer resp.Body.Close()
217 if _, err = io.Copy(tmpFd, resp.Body); err != nil {
218 log.Printf("Error during %s: %+v\n", req.URL, err)
219 http.Error(w, err.Error(), http.StatusBadGateway)
223 dstFn := tmpFd.Name() + ".png"
224 cmd := exec.Command(CmdDJXL, tmpFd.Name(), dstFn)
226 defer os.Remove(dstFn)
228 http.Error(w, err.Error(), http.StatusBadGateway)
231 data, err := ioutil.ReadFile(dstFn)
233 http.Error(w, err.Error(), http.StatusBadGateway)
236 w.Header().Add("Content-Type", "image/png")
237 w.WriteHeader(http.StatusOK)
239 sinkOther <- fmt.Sprintf(
240 "%s %s\t%d\tJPEG XL transcoded to PNG",
248 if req.Method == http.MethodGet {
250 switch resp.StatusCode {
251 case http.StatusMovedPermanently, http.StatusPermanentRedirect:
252 redirType = "permanent"
254 case http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:
255 if strings.Contains(req.Header.Get("User-Agent"), "newsboat/") {
258 if _, ok := imageExts[filepath.Ext(req.URL.Path)]; ok {
261 redirType = "temporary"
267 w.Header().Add("Content-Type", "text/html")
268 w.WriteHeader(http.StatusOK)
269 location := resp.Header.Get("Location")
273 <head><title>%d %s: %s redirection</title></head>
274 <body>Redirection to <a href="%s">%s</a>
276 resp.StatusCode, http.StatusText(resp.StatusCode),
277 redirType, location, location,
279 sinkRedir <- fmt.Sprintf(
280 "%s %s\t%s\t%s", req.Method, resp.Status, req.URL.String(), location,
286 for _, h := range []string{"Location", "Content-Type", "Content-Length"} {
287 if v := resp.Header.Get(h); v != "" {
291 w.WriteHeader(resp.StatusCode)
292 n, err := io.Copy(w, resp.Body)
294 log.Printf("Error during %s: %+v\n", req.URL, err)
302 resp.Header.Get("Content-Type"),
303 humanize.IBytes(uint64(n)),
305 if resp.StatusCode == http.StatusOK {
312 type Handler struct{}
314 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
315 if req.Method != http.MethodConnect {
319 hj, ok := w.(http.Hijacker)
321 log.Fatalln("no hijacking")
323 conn, _, err := hj.Hijack()
328 conn.Write([]byte(fmt.Sprintf(
331 http.StatusOK, http.StatusText(http.StatusOK),
333 host := strings.Split(req.Host, ":")[0]
335 keypair, ok := hostCerts[host]
336 if !ok || !keypair.cert.NotAfter.After(time.Now().Add(time.Hour)) {
337 keypair = newKeypair(host, caCert, caPrv)
338 hostCerts[host] = keypair
341 tlsConn := tls.Server(conn, &tls.Config{
342 Certificates: []tls.Certificate{{
343 Certificate: [][]byte{keypair.cert.Raw},
344 PrivateKey: keypair.prv,
347 if err = tlsConn.Handshake(); err != nil {
348 log.Printf("TLS error %s: %+v\n", host, err)
352 Handler: &HTTPSHandler{host: req.Host},
353 TLSNextProto: tlsNextProtoS,
355 err = srv.Serve(&SingleListener{conn: tlsConn})
357 if _, ok := err.(AlreadyAccepted); !ok {
358 log.Printf("TLS serve error %s: %+v\n", host, err)
364 type HTTPSHandler struct {
368 func (h *HTTPSHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
369 req.URL.Scheme = "https"
370 req.URL.Host = h.host
375 crtPath := flag.String("cert", "cert.pem", "Path to server X.509 certificate")
376 prvPath := flag.String("key", "prv.pem", "Path to server PKCS#8 private key")
377 bind := flag.String("bind", "[::1]:8080", "Bind address")
378 certs = flag.String("certs", "certs", "Directory with pinned certificates")
379 dnsSrv = flag.String("dns", "[::1]:53", "DNS server")
380 fifos = flag.String("fifos", "fifos", "Directory with FIFOs")
381 notai = flag.Bool("notai", false, "Do not prepend TAI64N to logs")
383 log.SetFlags(log.Lshortfile)
387 _, caCert, err = ucspi.CertificateFromFile(*crtPath)
391 caPrv, err = ucspi.PrivateKeyFromFile(*prvPath)
396 ln, err := net.Listen("tcp", *bind)
402 TLSNextProto: tlsNextProtoS,
404 log.Println("listening:", *bind)
405 if err := srv.Serve(ln); err != nil {